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
This chapter describes how to use the ILOM's command-line interface (CLI). The sections include: To connect to the CLI, see Section 2.1, Connecting to the ILOM This section describes how to use CLI commands. CLI commands are case-sensitive.. FIGURE 3-1 Typical SP Namespace The CLI provides two privilege levels: administrator and operator. Administrators have full access to ILOM functionality and operators have read-only access to ILOM information. The syntax of a command is: verb options target properties The following sections describe each of these. The CLI supports the following command verbs. The CLI supports the options listed in TABLE 3-2. Not all options are supported for all commands. See a specific command section for the options that are valid with that command. The help option can be used with any command. Every object in your namespace is a target. Not all targets. To execute most commands, you need to specify the location of the target, then enter the command. You can execute commands individually, or you can combine them on the same command line. 1. To execute commands individually: a. Navigate to the namespace using the CD command. For example: cd /SP/services/http b. Enter the verb, target, and value. For example: set port=80 2. To combine commands, use the form verb path/target=value. For example: set /SP/services/http port=80 The following display shows both methods:
http://docs.oracle.com/cd/E19121-01/sf.x4500/820-0280-12/cli_using.html
CC-MAIN-2015-27
refinedweb
238
61.63
Hi Henrik, Per Magne Skueseth, Thanks a lot for your replies and yes, I'm able to resolve this by adding the below class. I hovered over the message and found the error stating I dont have no matching support for jpg...(Apologies, it dint strike me to check the error message :-) ) I then added the below class (referred to AlloyTech) and it is working fine now. In my episerver 6 project, this was not there, hence i got confused. [ContentType(GUID = "0A89E464-56D4-449F-AEA8-2BF774AB8730")] [MediaDescriptor(ExtensionString = "jpg,jpeg,jpe,ico,gif,bmp,png")] public class ImageFile : ImageData { /// <summary> /// Gets or sets the copyright. /// </summary> /// <value> /// The copyright. /// </value> public virtual string Copyright { get; set; } } One other doubt : Is it possible to pickup the extension string from config file? so i can modify anytime in future.. regards, senthil You could/should create a generic class like this: [ContentType(GUID = "EE3BD195-7CB0-4756-AB5F-E5E223CD9820")] public class GenericMedia : MediaData { /// <summary> /// Gets or sets the description. /// </summary> public virtual String Description { get; set; } } This will take all files where there are no match on other mediadata that has extensionstring on it. Hi, I'm currently setting up a new episerver 7.5 site, and configured a VPP with following configurations. However, when I try to upload a file, "I got an error upload failed". 1. I looked into episerver log, and I could see only the below error message: ERROR EPiServer.Web.Hosting.VirtualPathHandler: VirtualPathProvider of type 'EPiServer.Web.Hosting.VirtualPathVersioningProvider' is registered for virtualPath '~/Upload/'. 2. File upload/Media dialog shows "Failed" as status. But I couldnt debug further. Can you please let me know if I need to add additional code or is it expected to work out-of-the box. Kindly let me know if I'm missing any steps. Thanks, senthil.
https://world.episerver.com/forum/developer-forum/-Episerver-75-CMS/Thread-Container/2015/2/virtualpathversioningprovider-not-working/
CC-MAIN-2020-45
refinedweb
305
57.57
There is an easy and quick method to transmit Hex values from a Windows PC over a serial port. Use the Embedded Evaluator tool from. Connect to the serial port, then add your hex values in the code window and click the 'Execute' button. Detailed Instructions: Attach any USB to Serial converter to your Windows PC. Bring up HyperSerialPort. Go to File->Properties, select the serial port to use from the combo box. Select the 'Bits Per Second' (typically 115200) and 'Flow Control' (none), leave the text boxes at their defaults. Hit 'Ok' to exit Properties. Click on the 'Connect' button. Go to Test Tools->Embedded Evaluator. In the code window (the large bottom left window), delete the IronPython code and replace it with this: import sys import clr clr.AddReference ('System.Windows.Forms') from System.Windows.Forms.import* x += chr(0x30) + chr(0x31) + chr(0x32) COMPort.Write(x) Then click on the 'Execute' button. The serial port will transmit the hex values 0x30, 0x31, and 0x32 over the serial bus. If you use another PC on the receiving end of this communication the results on a terminal emulator will be: 0 1 2 This is because, 0x30, 0x31, 0x32 is 0, 1, 2 in ASCII. You can add as many hex values to the above string as you like, just include it in the character function "chr()".
https://forum.arduino.cc/t/transmitting-hex-values-over-serial-port-using-hyperserialport/91687
CC-MAIN-2022-33
refinedweb
228
67.15
This is a split from 58866. We need to store filenames in Unicode (either in UTF8 or UCS2) and call a set of new NSPR_UCS2 interfaces. code issue, QA to yokoyama@netscape.com for now, please reassign for QA. Created attachment 97885 [details] [diff] [review] Supporting NSPR-UCS2. Storing mWorkingPath and mResolvedPath to be in UTF8 Phew, It's more than what I have initially thought; but I think I covered the most of cases and ready for review. dougt: can you review? Here is the run down: - store mWorkingPath and mResolvedPath in UTF8 - call new PR_fooUCS2() instead - Get/SetNativeFoo() converts path by calling UTF8toFS and FStoUTF8 respectively =================================================================== RCS file: /cvsroot/mozilla/xpcom/io/nsDirectoryService.cpp,v + #ifdef MOZ_UNICODE ... + if ( ::GetModuleFileNameW(0, buf, sizeof(buf)) ) { .. + #else ... if ( ::GetModuleFileName(0, buf, sizeof(buf)) ) { Does GetModuleFileNameW exist on Win95/98/ME ? If NO, will this put into #ifdef cause load time error with the #ifdef turn on under Win95/98/ME ? Does it function on Win95/98/ME ? If No, will this put into #ifdef always return false under Win95/98/ME ? Same question for _wstat in void nsFileSpec::GetModDate, nsFileSpec::GetFileSize(), nsFileSpec::IsFile(), nsFileSpec::IsDirectory() ::ShellExecuteW in nsLocalFile::Launch() The strategy changed since I posted the patch on 09/04. We intended to have a pure unicode application and use MS Layer for Unicode for Win9x OS. However, we decided _not_to use MSLU. I'll post a new patch to accomodate the change of strategy. Created attachment 104906 [details] [diff] [review] store mWorkingPath and mResolvedPath in UTF8 and call PR_fooUCS2() Last patch was rotten so I need to redo the patch..... I'd like to provide an incremental patch for supporting file i/o issues. With this patch we can: - open non-locale file dougt: can you review? I want to check this as soon as we are open for moz 1.3 Comment on attachment 104906 [details] [diff] [review] store mWorkingPath and mResolvedPath in UTF8 and call PR_fooUCS2() r=dougt bulk milestone change Comment on attachment 104906 [details] [diff] [review] store mWorkingPath and mResolvedPath in UTF8 and call PR_fooUCS2() sr=kin@netscape.com ==== Put a space after the equals sign: + output =NS_ConvertUCS2toUTF8(input); ==== So how does this relate to bug 170852, where you are actually removing MOZ_UNICODE ifdefs? Are you going to remove the MOZ_UNICODE ifdefs for this patch, when you land those changes? Created attachment 125174 [details] [diff] [review] another patch This patch is based on Roy's patch, but it checks the OS version at the run-time and calls either UTF16'nized PR_File* APIS or non-UTF16nized PR_File* APIs. This is not optimized, but is just to show how it can be done. Because this patch relies on NSPR UTF-16 APIs, NSPR has to be compiled with MOZ_UNICODE defined. Currently UTF-16 APIs are only compiled in with MOZ_UNICODE defined. Can we turn them on by default on Windows? Perhaps, a better approach is to check the OS (9x/ME vs 2k/XP) in xpcom/io and then to set function pointers accordingly to points to non-UTF16 calls and UTF-16 calls as was done in widget. Whichever way we can take, we can solve most problems in xpcom/io. Below is a bit off-topic. However, PR_*File* APIs are also used directly (not via xpcom/io). To fix those cases, we may have to modify NSPR file-related APIs so that on Windows, file paths in C-string are always interpreted as in UTF-8. With this change, NSPR can internally convert UTF-8 to UTF-16 and invoke 'W' APIs on Win2k/XP (and on Win9x/ME with Microsoft layers for Unicode, the presence of which has to be detected when NSPR is initialized) while on Win9x/ME with MSLU UTF-8 has to be converted to the system code page and 'A' APIs have to be invoked. It might not be very realistic because NSPR is not only for Mozilla but also for other projects. Nonetheless, this is something we have to think about. Created attachment 125219 [details] [diff] [review] a new patch I need to check this out on Win9x/ME, but on Win2k, it works fine. At the beginning of the patch is a small fix to downloadmanager.js (see bug 208113 comment #8). In SpecialSystemDirectory.cpp, I switched to 'W' APIs and added emulators for them on Win 9x/ME. The approach is similar to what's done in widget/src/windows by Roy. This patch also exposes NS_IsWindowsNT() that is available once xpcom is init'd. Its two applications outside xpcom/io are in xpinstall and netwerk/base/src where 0x5c is special-cased on DBCS OS. Because with this patch, native path will be in UTF-8 on Win2k/XP. I changed those checks done only if the OS is Win 9x/ME. I can remove MOZ_UNICODE define in Makefile.in in xpcom if UTF16 APIs in NSPR are turned on by default for XP_WIN. Created attachment 125603 [details] [diff] [review] another experimental patch (it's working) This works rather well. I can make and read files of which names include Thai, Devanagari, Greek, Cyrillic letters altogether ! However, this is still experimental (especially, 'extern nsNativeToUnicode() is a hack I just played with that I'm gonna get rid of). In terms of actual implementation, I still need to figure out what the best course is. I'm wondering how good/bad an idea is to have something like nsWin32API::WinAPIName (that is accessible across the tree). This is to avoid some overlap with what's done in widget/src/windows/nsToolkit.* Comment on attachment 125603 [details] [diff] [review] another experimental patch (it's working) Bah, this conflicts with an old (but unfortunately no sr) patch in bug 156422. I wonder what the point of MakeUpperCase is. Neil, thanks for the note about bug 156422. It seems easy to make attachment 94582 [details] [diff] [review] (to bug 156422) 'Unicode-aware'. I can make a new patch with attachment 94582 [details] [diff] [review] incorporated if you want. As for |MakeUpperCase|, I have little idea other than it's probably to make filenames case-insensitive on Windows. This bug is not for doing something new, but for making Mozilla 'unicode-aware' on Win2k/XP so that I just recast whatever is there in 'W" APIs. If we don't need it, that's nice The Windows filesystem already is case-insensitive. I know that[1] and thought it's a bit strange to have MakeUpperCase. Anyway, please don't ask me about MakeUpperCase. I just recast it in W APIs without thinking much. In this bug, I just want to focus on making Win32 file I/O in Mozilla Unicode-aware. We can remove it later if it's not necessary. [1] Case-insensitivity beyond US-ASCII is not so simple as one may think. *** Bug 226928 has been marked as a duplicate of this bug. *** err. FAT is case preserving. NTFS can be case sensitive. Please don't ever change the file name's case from the flavor the os offers. Really? Where is NTFS case-sensitive? google found: "Although NTFS does support case sensitive filenames, currently only the POSIX subsystem uses case sensitive names." also, there's a flag to CreateFile that allows to create two files with names differing only in case: FILE_FLAG_POSIX_SEMANTICS Is there anyway for us to move this forward? We need to make changes in NSPR and I have yet to hear from wtc. It's embarrasing thta Mozilla on win32 is not yet fully Unicode-aware. I have a patch and an idea, but without NSPR fix, not much can be done. Adding leaf for nspr, darin for xpcom and some drivers to Cc, retargetting and assigning to myself. Related threads: (in n.p.m.nspr) 1. Enabling NSPR UTF16 APIs news://news.mozilla.org:119/bfe3c5$4ha2@ripley.netscape.com 2. making |nsWindowsAPI| news://news.mozilla.org:119/bfr3cc$nfg1@ripley.netscape.com I really love to fix this (and a bunch of other related bugs that will be fixed or become very easy to fix once this is fixed), but I'm stuck because I don't know how to move forward necessary NSPR changes. Any thought or help would be appreciated. It's easier to use google than 'news' URL. btw, I wrote to wtc about NSPR Unicode file I/O and getenv/setenv vs wgetenv/wsetenv (bug 227500) (In reply to comment #22) > 2. making |nsWindowsAPI| > news://news.mozilla.org:119/bfr3cc$nfg1@ripley.netscape.com > I've just found |nsINativeAppSupportWin|. It seems that we can put all those W/A API-related stuffs there including IsWindowsNT()? (In reply to comment #24) > I've just found |nsINativeAppSupportWin|. It seems that we can put all those W/A > API-related stuffs there including IsWindowsNT()? making large parts of the tree depend on xpfe sounds like no good idea to me I agree. I didn't realize that it's in xpfe. What I want to have/implement is something akin to |nsCRT| for Windows APIs. See my news posting mentioned in comment #23. *** Bug 243558 has been marked as a duplicate of this bug. *** Created attachment 150920 [details] MZLU (proof of concept) Here is a proof of concept library for wrapping Win32 calls. It is a very basic implementation similar to MSLU but freely licenced for Mozilla and other open source projects under the tri-licence. (I've thus called it MZLU). Essentially what it does is define symbols like: GetTempPathMz CreateFileMz which are function pointers to functions which have the same signature as the W version of the WIN32 or CRT API. A client program needs to link with the very slim C static lib that defines these pointers. The only other thing the static lib does is have an initialization function to set the pointers to the appropriate implementation. Hard to tell exactly how much overhead in linked code, but probably just a few Kb. On Windows NT based OS the pointers are set to the real W functions. e.g. CreateFileMz = ::CreateFileW; Thus the penalty for using this library on NT/2K/XP is very low. Just the extra few Kb for the static lib, plus one more indirection per OS call. On 9x/ME systems, these functions are set to wrapped versions of the ansi code page based API. These wrapped functions don't exist in the C static lib, but instead exist in a dynamically loaded DLL loaded only by 9x/ME systems. I thought about using direct calls to the W functions and on Win9x/ME rewriting the import tables to point to our wrapped functions, which would save the single indirection on NT, however the current method allows us to also support functions which are only conditionally available. e.g. GetDiskFreeSpaceEx (not available on Win95). On systems which doesn't have it available, the function pointer will be left NULL. On systems which does support it the function pointer is set. Thus simplifying the test for availability (although at the cost of having the DLL loaded from startup, however since these are probably all major system DLLs which are likely to be loaded anyhow, it is just a mapping into our process that will be created). The wrapper functions are implemented to convert between wide/narrow chars while retaining the function specification. Sometimes this is simple (e.g. DeleteFile), sometimes more difficult (e.g. _wgetdcwd or GetTempPath). See the DLL implementation (mzlua) for details. The functions currently implemented for proof of concept are CRT and WIN32 functions that are used in nsLocalFileWin.cpp ... _wgetdcwd CopyFile CreateDirectory CreateFile DeleteFile GetDiskFreeSpaceEx GetDiskFreeSpace GetFileAttributes GetLogicalDriveStrings GetTempPath MoveFile RemoveDirectory ShellExecute In order to use this library to fully Unicode enable Mozilla on Windows. All calls to non-Unicode API would need to be re-routed through this library. In addition, all NSPR UCS2 functions would also need to use this library to allow them to be called on all OS versions. Is this acceptable to the Mozilla and NSPR philosophy? Brodie: Thanks for taking the time to create MZLU. I don't have a "final" answer for you, but I think this may be the right direction. The challenge is really deciding what we want to do with NSPR. I haven't heard a final decision there. I know that wtc is not thrilled about adding new APIs to NSPR, but perhaps that is the best solution. We need to hear from wtc on this matter. Jshin: what are your thoughts on this? I know you spoke about wanting something like MZLU... is this duplicating work you have already done, or is this the missing puzzle piece? It seems strange to not use the MSLU when it provides the vendor recommended solution of Unicode on all platforms. I've looked at bug 118013 and bug 162362 which asserts that there was discussion about this but doesn't note where. Can someone point me towards the problems with bundling MSLU with Mozilla? Licence- wise it seems that one clause might be the problem... "(c) you distribute your Application containing the Redistributable Components pursuant to an End-User License Agreement (which may be "break-the- seal", "click-wrap" or signed), with terms no less protective than those contained herein;". Is it possible to create another product which is compatible with the terms of the MSLU licence, and then require users to install it in order for Mozilla to be used on the appropriate platforms? Not particularly nice, but MSLU is a good solution... If not, then I am quite happy to move all of nsToolkit into MZLU, complete the implementation of all API that NSPR requires, and then get all of Moz using this. I really want to implement all of the Unicode support here. Working with MBCS is a major pain and makes things far more complex than it needs to be. As for the problem of NSPR and it's API. Perhaps we should just use UTF-8 in all NSPR API on Windows (build option of ANSI or UTF-8 to maintain compatibility) and just wear the to/from UTF-8/UTF-16 conversions that it requires? No API change required, a new build option and different implementation internally. Wan-Teh -> what do you think? Others? I know this doesn't make much difference to English speaking single byte "pizza is as international as I get" sort of people, but lets try and get this app fully internationalized for the rest of the world... Unicode isn't the future, it's already here. Mozilla has fallen behind. (In reply to comment #29) Brodie, thank you for 'waking up' darin's interest in this bug :-) > The challenge is > really deciding what we want to do with NSPR. I haven't heard a final decision > there. I know that wtc is not thrilled about adding new APIs to NSPR, but > perhaps that is the best solution. I tend to agree about adding new APIs. An alternative (using UTF-8 on Win 2k/XP) is a bit risky as discussed in the thread at > We need to hear from wtc on this matter. Unfortunately, he hasn't replied to my emails. I've written to him (and leaf, the other owner of NSPR) at least a few times since summer 2003, but nothing came back. I understand that he's busy, but it's frustrating not to hear anything. Anyway, I really hope this time around he can find some time to resolve this long standing issue. > Jshin: what are your thoughts on this? I know you spoke about wanting something > like MZLU... is this duplicating work you have already done, or is this the > missing puzzle piece? What's missing is, as you wrote, wtc's decision as to what to do with NSPR file APIs. MZLU can solve the problem I talked about in two news postings (comment #23) and it can simplify a lot of things. I was approaching the problem from a different angle (although equivalent) and didn't hit upon an idea of rolling out our own version of MSLU. Then, a question arises why not just use MSLU. I asked the question before, but no resolution has been reached yet. It's available on virtually all installations of MS Windows because MS IE comes with it (we don't have to increase the code size to dupe what's already available). There's an irony here in that we have to require MS IE be installed to run Mozilla. However, some other parts of Mozilla already rely on DLLs that come with MS IE so that relying on MSLU should not be a problem, IMHO. Even if MS IE is not installed, it's likely that some other applications (e.g. MS Office) with MSLU are present. I'm adding some more people who may be at a better position to resolve this issue (whether or not to make Mozilla depend on MSLU). In bug 239279, we discussed the possibility of making Mozilla depend on MSLU. There are quite a number of bugs nothing to do with file I/O that can be easily fixed by using 'W' APIs available for Win9x/ME via MSLU. (see bug 232969, bug 240272, bug 9449, bug 243618 for instance). All those bugs are independent of NSPR file I/O APIs.So, let's keep on discussing, in bug 239279, as to whether we want to make Mozilla depend on MSLU or we want to implement our own (MZLU). Created attachment 151998 [details] MZLU v0.1 This version of MZLU implements all of the functions that nsLocalFileWin uses and that are implemented in nsToolkit/nsWindowsAPI. While we are arguing over/waiting to hear whether or not to use the actual MSLU library or not, let's start using MZLU instead. It will be very easy to move from calling MZLU functions to calling actual MSLU wide functions (replace the Mz postfix from all functions with W). There seems to be a number of places where people are actively adding new wrappers for A/W, so we could at least move that to a centralized place. On nsLocalFileWin.cpp, I found that I could get rid of nearly every call to NSPR apart from PR_Open by going directly to the Win32 API. Since this is a Windows only component I don't see any reason why we shouldn't do so. This means that at least for the file handling, we only need PR_Open to support unicode... You could also implement PRFileDesc yourself in terms of the WIN32 API, but that is probably not ideal ;-) The biggest concerns I have with moving to a full Unicode backend is what to do with the "native" character encoding defined by nsIFile/nsILocalFile. If we keep that using the ANSI codepage, then won't we have a lossy conversion from nsIFile to file:// URL? Remember, that file:// URLs are currently generated from the "native" file path. I think we might want to solve these problems by using UTF-8 as the "native" character encoding under Win32 builds. Or, perhaps we could even have an optional runtime mode in which that is enabled. We also have to keep in mind that changing the encoding of file:// URLs affects interoperability with other applications when users drag-n-drop file:// URLs from Mozilla to other applications. We should choose an encoding that is most compatible with Unicode aware applications. E.g., how does Microsoft Office encode non-ASCII file:// URLs? NOTE: Under most Linux distros, UTF-8 is the default character encoding, and it is therefore what we use for file:// URLs and nsIFile::nativePath under Linux. The same is true of OSX. (In reply to comment #34) > I think we might want to solve these problems by using UTF-8 as the "native" > character encoding under Win32 builds. the downside is that mozilla is not backwards-compatible wrt to its file urls then. for example, sucks if you had a homepage (as a local file) in a directory containing non-ascii characters before, because the url would no longer work. Christian: I agree... that's a major concern. Perhaps we need to utilize a failover technique. Or maybe we can unescape file:// URLs and test whether they are UTF-8 or not (using IsUTF8). If they are not UTF-8, then we try using the ANSI codepage. That might be the best solution. We could probably do all of this inside nsURLHelperWin.cpp. Comment on attachment 151998 [details] MZLU v0.1 See bug 239279 for updates of MZLU. *** Bug 253164 has been marked as a duplicate of this bug. *** jshin, any progress on this one? if there still is a chance of a low risk patch renominate for 1.0 Sorry I don't have enough time to fix this before 1.0. Even if I have a lot more time, the patch may be too extensive to be regarded as safe for 1.0. *** Bug 266718 has been marked as a duplicate of this bug. *** *** Bug 279224 has been marked as a duplicate of this bug. *** I am using Mozilla code as a base for an application for e-learning, for already some years. Right now we are having troubles because customers in russia and polen have problems because of this issue, so I created an own class that converts (and creates) the unicode path and converts it to its alternate path, and uses this alternate short path to create a NS_NewLocalFile, so that PR_Open works correctly. Of course, this is far far away from what should be, but so I get my code working and customers satisfied. But what about the idea of converting the path to its short variant? The only downside is, as far as i can see, is the creating of new files, which will not be made with NSPR. But it would be possible to create a shortnamefile with nspr, and then rename it. BTW, the current solution of converting characters to "_" because "?" is not a valid filename is bad too - because of this, if you are going to save a page in mozilla (1.7.5), you can select a directory with russian characters, and it ends up in a totally different folder. Which is, in my opinion, even worse than disallowing such pathnames. Is there any way that I can be helpful to you? I would like to help out, just tell me what to do. it's possible for shortfile variants to be disabled, which means you'll gain nothing by trying. You are right; I was not aware of this. I just read. I started fixing the unicode file i/o related bugs since 2002 and as far as I remember, only stuff waiting for supporting the _full_ unicode in Windows is to enable NSPR to call W APIs. (except that non-ASCII Commandline issue is still outstanding, i believe) I believe I have tested file:// URL and drag-drop of non-system filenames before I checked in the code (all with MOZ_UNICODE) There appears to have new path to use MZLU; but bug 239279 turning up to a licensing talk. We also discussed using MSLU years back and decided not to use it simply because we don't want to introduce another dependency. Can we turn on the flag (MOZ_UNICODE) in NSPR after we branch out for Gecko1.8? Darin, Chris? Is WTC still active in mozilla? See comment #9, comment #10, comment #11 and comment #22 (two news postings and responses to them in the newsgroup). Anyway, people don't seem to like introducing new 'Wide' APIs to NSPR. *** Bug 188383 has been marked as a duplicate of this bug. *** darin, what's your opinion of introducing wide APIs to NSPR? Alternatives are: 1. implementing equivalents of NSPR APIs in xpcom with Windows W APIs 2. pass UTF-8 (on Windows 2k/XP) to existing NSPR APIs and let NSPR do the conversion I'm afraid the second alternative has a performance issue because we have to go back and forth between UTF-8 and UTF-16 on Win 2k/XP.. Neither of us have time to implement it though. The biggest challenge, I think, is in supporting those UTF-16 APIs on non-Win32 platforms. That's where the code in nsNativeCharsetUtils (or some large part of it) will come in handy. One more point: I don't think NSPR should depend on MZLU or something like that since there really aren't that many wide APIs to implement. (In reply to comment #50) >. So, WTC has changed his mind since 2003. That's fine because I also agree with you. > challenge, I think, is in supporting those UTF-16 APIs on non-Win32 platforms. We don't need those APIs on platforms other than Windows at least for now. If implementing NSPR 'W' APIs only on Windows for now is acceptable, I'll begin with attachment 125603 [details] [diff] [review]. I would really like to see us try to provide the same NSPR API on all platforms. I think we can given the code in nsNativeCharsetUtils.cpp. Yes, let's make the current PR_xxxUTF16 functions official, and avoid making NSPR depend on MZLU (at least in the first implementation). PR_xxxUTF16 functions are #ifdef'ed with MOZ_UNICODE. All NSPR needs to do is to enable the flag. From the comment in prdir.c : Bug 162358: added NSPR file I/O functions that take UTF16 pathnames. The patch is contributed by Roy Yokoyama <yokoyama@netscape.com>. Modified Files: config/config.mk prio.h prtypes.h _win95.h primpl.h prdir.c prfile.c w95io.c ptio.c (In reply to comment #53) > I would really like to see us try to provide the same NSPR API on all platforms. > I think we can given the code in nsNativeCharsetUtils.cpp. As you implied, moving nsNativeCharsetUtils to NSPR is more involved than simple copy'n'paste partly because of the language difference. For the sake of completenetss, it's good to provide the same NSPR API on all platforms, but do we really want to hold this Windows-specific bug just for that? How about just adding a 'dummy' implementation for other platforms for now? (there's no non-Windows consumer at the moment). I'm not against doing things in stages, but we need to decide what form we want this to be in when Firefox 1.1 ships. Maybe WTC has some thoughts on this? I'd love to see this bug fixed for Firefox 1.1, but we're talking about a pretty significant API change for NSPR. (In reply to comment #57) > but we're talking about a pretty significant API change for NSPR. We're not gonna remove existing file APIs (char-based), are we? UTF-16 APIs are not likely to be used by non-Windows consumers.. > We're not gonna remove existing file APIs (char-based), are we? No, definitely.. I don't think it matters that much either way. That said, I think the current code that uses GetProcAddress to resolve CreateFileW and friends is wrong. Those symbols exist on Windows 9x, but they are simply not implemented. The current NSPR implementation for these routines assumes that callers will handle "not implemented" errors appropriately. I'm not sure I like that. I'd prefer to see us implement the UTF-16 functions in all cases. However, I suppose we could entertain the idea of making all users of the UTF-16 routines know how to failover to the ANSI versions. But, that is the least desirable solution IMO. (In reply to comment #59) > > We're not gonna remove existing file APIs (char-based), are we? > > No, definitely not. The question was rhetorical one because adding UTF16 APIs didn't seem to me as significant as you think it. I'm not saying we will never implement them on other platforms. We need to implement them on all platforms to use them in cross-platform code which directly invoke NSPR APIs instead of going through xpcom/io (so my statement 'not likely to be .... other platforms' is not quite right). However, there's no consumer outside xpcom/io so that I think we can do it in stages adding a very prominent warning that UTF-16 APIs should not be used on other platforms for now. > I don't think it matters that much either way. That said, I think the current > code that uses GetProcAddress to resolve CreateFileW and friends is wrong. > Those symbols exist on Windows 9x, but they are simply not implemented. I'll change it to check the OS version and do the 'right' thing depending on the result. > I'd prefer to see us implement the UTF-16 functions in all cases. So would I. That means, xpcom/io can move some of |if (isNT) ...| over to NSPR.,). *** Bug 296316 has been marked as a duplicate of this bug. *** *** Bug 294914 has been marked as a duplicate of this bug. *** *** Bug 297304 has been marked as a duplicate of this bug. *** *** Bug 306335 has been marked as a duplicate of this bug. *** *** Bug 310394 has been marked as a duplicate of this bug. *** *** Bug 312287 has been marked as a duplicate of this bug. *** *** Bug 315353 has been marked as a duplicate of this bug. *** *** Bug 315353 has been marked as a duplicate of this bug. *** *** Bug 316168 has been marked as a duplicate of this bug. *** (In reply to comment #61) >, >). But How to patch for Fx 1.5b1/2? I'm sure people are going to say I'm just making noise here, but I still like to remind that Windows Vista is due to be out next year, and Win98 is to be abandoned even more. Please, for the well-being of the whole humanity, or at least of the Mozilla community, forget about Win9x family. The lastest versions of FF and TB (1.5 and 1.0.7 resp.) are stable enough for those who are forced to use Win9x. We must move forward. How many times I'm pissed off because TB can't attach a file and I'm forced to change the name to something totally non-sense to suit it. I know that more and more TB users are switched to Outlook (and Outlook Express) because of the user-friendliness it offers. The more we are stagnant in this stage, the more TB is getting worse. We need to be more determined. > We need to be more determined. I agree. Are you volunteering to write code? Sure. But I'm mostly a Java and web programmer. I can't say I'm very efficient in C++. Anyway, I've tried to take a look at how to do get the source code and learnt that we need to have Cygwin and Visual C++ 6. I could install VC6 but I would like not to do so if possible. And then it talks about VS.NET. I'd probably misunderstood something... OTOH, in this bug as well as in other bugs, it seems that the Unicode support (NSLU) is already there for years but developpers are just reluctant to use them because that would need extensice testing (in Win9x and WinNT platforms). Teng-Fong, I'll try to resurrect my 2.5 year old patch (attachment 125603 [details] [diff] [review]), make changes to work with the current code and do what darin suggested in bug 239279 comment #116. However, my time is limited and won't begin to work on it this year (well, I'm hoping I'll have some free time to work on this in the first few days of next year). However, if you're willing to work on this, you're free to go ahead. As to what compiler to use, see and Created attachment 208200 [details] [diff] [review] patch (far far from review-ready) This is a just wip (hodgepodge of various patches). However, I don't think I'll take the approach taken in this patch. I just began to write a totally different patch that almost exclusilvey uses 'W' APIs on Windows. What I wanna do is to make things work on Win 2k/XP first and see how much effort it takes to make it work on Win 9x/ME if we still want to support them in FF 3.0, which is not very likely. Current plan is not to support Windows 98 in Firefox 3 / Gecko 1.9. I'm not sure about ME -- cc'ing vlad. /be ME's in the same boat as 98 -- (its usage numbers are even lower than 98's) I'm glad to see people working on this bug. XPCOM/IO was the last item I needed to do to fully support Unicode filenames back then; but it never materialized for reasons I don't want to get in. I look forward to your real patch, Jungshik. does "not support w9x in gecko 1.9" (it is more than firefox) mean "we won't spend extra effort on w9x" or "we will actively break it and don't want patches for it"? > does "not support w9x in gecko 1.9" (it is more than firefox) mean "we won't > spend extra effort on w9x" or "we will actively break it and don't want patches > for it"? In the discussions I've heard on this topic, the intention is the latter... to accept patches. Sorry, I meant: In the discussions I've heard on this topic, the intention is to accept patches. In other words, if members of the community wish to support Win9x, then we should support them in their efforts. Again, vlad should comment, but short of a lot of work, the rendering subsystem moving to Thebes/Cairo in 1.9 means Win98 will perform poorly in some cases. From what I remember, very poorly. If someone writes a patch to correct this, it may require a lot of work. It may require graphics card level hacking. It may not be possible at all. /be I have no say in this, but I hope it's OK for me to express my opinion. Even if someone is dedicated enough to do something as crazy as that, why should the code be littered with hacks/workarounds/etc... for a dying (dead) OS? Microsoft has long dropped support for Win98SE () and will drop support for WinME in 2006. More Windows support cycles at. I believe that the only reason people still use Win9x is because they're stuck with it on their ancient hardware. And once the old computer dies, it will be replaced with something that will run atleast Windows XP. Created attachment 208388 [details] [diff] [review] patch (stage 1) This gets compiled, but my build hasn't yet finished so that I haven't tested it. mResolvedPath and mWorkingPath are now in nsString and UTF-16 APIs directly invoke 'W' APIs while 'native' APIs call UTF-16 APIs with encoding conversions. Instead of using NSPR UTF-16 APIs, simplified and modified implementations were added to nsLocalFileWin.cpp. I added a flag, PR_LD_PATHW (0x4000) to PR_LoadLibraryWithFlags to pass a UTF-16 string (casted into 'char *'). This doesn't work on Win 9x/ME, but I'm eager to see this fixed in FF 2.0 so that I'll add Win 9x/ME support. SpecialSystemDirectory needs to be patched as well (attachment 208200 [details] [diff] [review] has an unfinished patch for that). To do that, I also have to add an OS-detection code somewhere (perhaps in nsNativeCharsetUtils init. routine). I may or may not fix xpcom/obsolete/nsSpecialSystemDirectory. Created attachment 208506 [details] [diff] [review] another checkpoint (nsLocalFileWin) With this patch applied, a trunk build works as well as a trunk build without it (except for a potential slow-down because 'native' methods are implemented in terms of UTF-16 methods and our codebase use 'native' methods more often than UTF-16 methods). However, there are a lot more to do to enable even a simple thing like opening a file whose name has characters not covered by the current 'legacy' codepage. That's because our code use 'native' (lossy) APIs all over the places. When I added a warning to GetNativePath, my console got bombarded with warnings. In many cases, we need to do something like #ifdef XP_WIN use UTF-16 APIs #else use 'native' APIs #endif An alternative is to make 'native' on Win 2k/XP UTF-8 (as done in my 'hodgepodge' patch) while leaving as it is on Win 9x/ME. In addition, for non-file related use of 'native' (registry, cmd line, env. variables), we might introduce 'nativeA' (as opposed to 'nativeW'). However, this is not compatible with a long-standing convention that 'native' filename can be fed to '(f)open'-like functions so that it's not such a good idea. Another alternative is to add 'UTF8' methods to nsILocalFile.... Whichever option we take, we have a lot of files to 'fix'. Of course, that has to be done in a separate bug. BTW, this patch is a lot easier to read than attachment 208388 [details] [diff] [review] thanks to the way methods are ordered in nsLocalFileWin.cpp (In reply to comment #86) > than UTF-16 methods). However, there are a lot more to do to enable even a > simple thing like opening a file whose name has characters not covered by the > current 'legacy' codepage. That's because our code use 'native' (lossy) APIs Oops. Just with this patch, opening a file with non-'native' characters in its name works file if it's done via File|Open (For a moment, I forgot that nsFilePicker was made to deal with the full Unicode range a long time ago by Roy). I guess opening with a double clicking should work if I apply the latest patch in bug 278161. Created attachment 209051 [details] [diff] [review] yet another checkpoint (with support for Win 9x/ME) It's still in WIP (especially when it comes to supporting Win 9x/ME) Would it be silly to use short names for 8-bit paths and long names for 16-bit? Created attachment 209325 [details] [diff] [review] patch confirmed to work on Windows ME I've tested a debug build with this patch on Windows ME (en-US) as well as Windows 2k (ko) to find that it actually works as intended. There are still some loose ends to tie up. They include potential errors (buffer overrun, memory leak, use of replacement char '?' vs '_' in W2M conversion, potential string API 'link' issue, xpcom/obsolete support, whether or not to expose emulated 'W' APIs globally and how to do that if necessary etc) in my 'W' API emulation on Windows 9x/ME. I also need to make sure that I can refer to the addresses of 'W' APIs on Windows 9x/ME (although they're not actually implemented) instead of using GetProcAddress(?). My test on Windows ME indicates that it's possible, but Wi 9x/ME differ slightly from each other in what APIs they have so that actual testing on Win 95/98 is ncessary. Due to a problem described in this thread (), I can't make an optimized build (even without profile added, cvpack gives me the same error when linking gklayout). If anybody is interested in testing a debug build (~13MB zipped) on Win 95/98, I'll put it up somewhere. Created attachment 209831 [details] [diff] [review] 1.8.x branch patch This is a patch for 1.8.x branch. With this patch, MS IE bookmarks with characters outside the system default codepage (Devanagari with Korean locale) were confirmed to be imported. Because this patch is a port of attachment 209325 [details] [diff] [review] to 1.8.x branch, it shares common issues with attachment 209325 [details] [diff] [review]. Created attachment 210834 [details] [diff] [review] patch that really works on Windows ME I have no idea what happened with attachment 209325 [details] [diff] [review]. There's no way it could have worked on Windows ME (was I hallucinating? ...) because a dozen of 'W' APIs (which would just lead to 'Not Implemented' error on Win ME) were called with that patch. I thought I had replaced them all with the corresponding nsWinAPIs, but I didn't. Moreover, in NSPR, LoadLibraryW was used, which resulted in the dll load failure on Win ME. Anyway, after a number of rebootings between Win 2k and Win ME, I finally made this patch work on Windows ME as well as on Windows 2k. While working on that, I realized that nsAppRunner.cpp uses nsILocalFile before xpcom initialization (and nsWinAPIs initialization). As an ad-hoc measure, I exposed NS_StartupWinAPIs so that it can be called in XRE_Main() of nsAppRunner.cpp. If there's a better way than this (e.g. calling it in nsLocalFileWinConstructor...), I'm willing to change it. Other remaining issues: - I didn't change xpcom/obsolete because I need to expose nsWinAPIs outside xpcom/io to fix xpcom/obsolete (alternatively, I have to duplicate a bunch of lines in xpcom/obsolete). I'm not sure what's the best way to expose 'W' API wrapper functions of nsWinAPIs. We may want to do that to avoid the code duplication anyway (even if we don't wanna fix xpcom/obsolete) because some other parts of our code directly call Windows APIs that are wrapped up (for Windows 9x/ME) in xpcom/io/nsWinAPIs (that I added in this patch) - A bit more simplification is possible if we abandon Windows 95 (before OSR2), but seamonkey is still supposed to work on Win 95 so that I guess I'll just have to keep them now. - I need to inspect the code for emulation of 'W' APIs more thoroughly for possible 'one-by-off' error and buffer overrun, etc. - Need to add more comments - Need to resolve bug 278161 before resolving this one (the patch uploaded here may be 'polluted' with my interim patch for bug 278161) - There may be some Windows CE issues (but given that Darin's nsIWindowsRegKey implementation works there, I don't expect many issues although there may be a few problems to work around/fix). Darin, can you take a look at this patch and give me some feedback (perhaps not in details but in the overall approach)? wtc, can you also take a look at the NSPR part (the amount of change is relatively small)? Thanks. Comment on attachment 210834 [details] [diff] [review] patch that really works on Windows ME You should add new prlink.h functions that take UTF-16 pathnames. We shouldn't make NSPR users cast a PRUnichar * string to a char * string just so we can avoid adding new NSPR functions. We should also convert all library pathnames to UTF-8, rather than converting just the ones given to NSPR in UTF-16. Hrm.. perhaps we should split the NSPR changes out into a separate bug. (In reply to comment #94) > Hrm.. perhaps we should split the NSPR changes out into a separate bug. That's a good idea given that there's apparently a "conflict" of "interest" between NSPR and Firefox et al. ;-) I filed bug 326168. (In reply to comment #93) > (From update of attachment 210834 [details] [diff] [review] [edit]) > You should add new prlink.h functions that take > UTF-16 pathnames. We shouldn't make NSPR users > cast a PRUnichar * string to a char * string > just so we can avoid adding new NSPR functions. The idea behind that was to minimize NSPR changes necessary to fix this bug, on which I thought we kinda agreed in our email discussion. Perhaps, I was mistaken or went too far in that direction. > We should also convert all library pathnames to > UTF-8, rather than converting just the ones given > to NSPR in UTF-16. That's one of what I had in mind when I wrote I needed to add more comment. In pr_UnlockedFindLibrary, it's only the leaf name (not the whole path) that matters, isn't it? That being the case, it should work either way (in 99.99% of cases) because virtually all DLL names are in ASCII only and the directory separator is the same in UTF-8, ASCII and legacy encodings. Anyway, that's certainly not bullet-proof because somebody may have a non-ASCII dll name. Does this patch address bug 210445? (In reply to comment #96) > Does this patch address bug 210445? No, it doesn't because to fix that, we need to use 'wmain' for the command line handling instead of main, but we can't do that as long as we support Win 9x/ME. In FF 3.0, perhaps we will switch to wmain because Win 9x/ME support will be dropped. GetCommandLineW? remember that we don't currently use main, because mozilla is a gui app, so it uses WinMain. (In reply to comment #99) > remember that we don't currently use main, because mozilla is a gui app, so it > uses WinMain. Aha. thanks. Anyway, that's beyond the scope of this bug. We already have a bug on that, don't we? Darin and others, do you have any comment on my latest patch (even if you haven't gone through it in details but just have had a cursory look) other than NSPR part? For PR_LoadLibraryWithFlags, it'd be nice to hear back some opinions in bug 326168 so that we can resolve this long standing bug before long. jungshik: I just read over the patch, and I think it is looking really great! (In reply to comment #98) >GetCommandLineW? Note that Win 9x/Me doesn't support CommandLineToArgvW. Created attachment 211597 [details] [diff] [review] another update(getting closer) Thanks, Darin, for taking a look. I'm getting closer. Updated my tree to sync with the trunk and cleaned up a bit. This patch also contains the latest patch for bug 326168 (with a typo fixed) Created attachment 212261 [details] [diff] [review] another update (should work on Win95) includes the latest patch for bug 326168 Created attachment 212321 [details] [diff] [review] patch for 1.8.x branch With this patch and the necko part of the latest patch for bug 278161, I can open a file whose name has chars. outside the default codepage on Windows 2k. It also works fine on Windows ME. It should also work on Windows 95/98 (which are basically the same as Win ME), but I can't test it myself. Kimura-san, can you test my patches (for trunk and for branch) on Windows 95? Thanks tons in advance. Created attachment 212322 [details] [diff] [review] patch for trunk attachment 212261 [details] [diff] [review] has a missing file. (prtypes.h) Created attachment 212323 [details] [diff] [review] a partial patch for bug 278161 necessary for testing my patch here To test attachment 212312 [details] [diff] [review] or attachment 212322 [details] [diff] [review] on Win 2k/XP/Vista (to see if a filename with characters outside the default repertoire works), this partial patch for bug 278161 needs to be applied. Comment on attachment 212322 [details] [diff] [review] patch for trunk >); GetFileVersionInfoW declaration does not also care about constness. You should cast them to make VC6 happy. Such as: > nsGetFileVersionInfo nsWinAPIs::mGetFileVersionInfo = (nsGetFileVersionInfo)GetFileVersionInfoW; > nsGetFileVersionInfoSize nsWinAPIs::mGetFileVersionInfoSize = (nsGetFileVersionInfoSize)GetFileVersionInfoSiz. With all the above errors resolved, I coudn't start on Win95 yet :-( I'm digging into the reason. Thanks for testing on Windows 95. (In reply to comment #109) > (From update of attachment 212322 [details] [diff] [review] [edit]) > >); ........ > You should cast them to make VC6 happy.. Thanks. I wrote wrappers for all three of them and both trunk and 1.8.x branch build seem to work fine on Win 2k/ME. I also tried emulating GetFileAttributesExA on WinME to see how it would work on Win95 and it worked well. Anyway, none of these tests can substitute actual tests on Win95 so that your test on Win95 would be appreciated. Created attachment 212367 [details] [diff] [review] trunk patch update addressing issues pointed out in comment #109 Masatoshi, can you try it on Win95? Testing on Win98 and other old Windows would be nice, too. Created attachment 212368 [details] [diff] [review] branch patch update Comment on attachment 212367 [details] [diff] [review] trunk patch update addressing issues pointed out in comment #109 "Program start error" does no longer occur, but it still fails with "This program has performed an illegal operation and will be shut down. If the problem persists, contact the program vendor."(actually in Japanese) We are the program vendor :-( I'm building a debug version... Thanks again for testing. Hmm... that's tough. BTW, I put up my debug build (trunk) at for others without a build set-up to test. (make a directory for it and unzip it in the directory and 'firefox' binary will be in the directory). On Windows 2k/XP, by setting the environment variable WINAPI_USE_API, one can sorta emulate Win 9x/ME. With that set, it would behave like ff 1.5/trunk. Without that set, it would be able to access the full unicode repertoire in file operations (e.g. File | open). Be aware that this patch alone does NOT fix all the bugs blocked by this bug. However, opening a file with Japanese name on French Windows 2k/XP should be possible. Saving a file to a desktop should work on Russian Windows 2k/XP whose default codepage is *changed* from the default (Windows-1251) to one that cannot represent Russian (e.g. Windows-1252 - French, German, English, etc). OK. I found a crash reason. On Win95 withoutIE, gGetSpecialPathProc will be initialized NS_GetSpecialFolderPath, but gGetSpecialFolderPathA aren't initialized because old shell32 doesn't export even A-version of GetSpecialFolderPath. Therefore NS_GetSpecialFolderPath tries to call null pointer, then crash. We should fall back to SHGetSpecialFolderLocation code path in this case. That is, + gGetSpecialFolderPathA = (nsGetSpecialFolderPathA) + GetProcAddress(gShell32DLLInst, "SHGetSpecialFolderPathA"); + gGetSpecialFolderPath = NS_GetSpecialFolderPath; should be like this. + gGetSpecialFolderPathA = (nsGetSpecialFolderPathA) + GetProcAddress(gShell32DLLInst, "SHGetSpecialFolderPathA"); + if (gGetSpecialFolderPathA) + gGetSpecialFolderPath = NS_GetSpecialFolderPath; With this change, I could start, open Japanese directory, and open Japanese filename successfully on Win95! Some minor problem remains: I could no longer open local root directrory (e.g.). This is a regression because I can open it without a patch. jshin, what is the target release for this work? On trunk we may and should use the W APIs directly because we're dropping support for anything less than win2k. The dynamic loading only makes sense if we're targeting ff2. (In reply to comment #117) > win2k. The dynamic loading only makes sense if we're targeting ff2. I'm targeting it at FF2. And even for FF3, there _might_ be some "non-GUI" consumers of XPCOM. BTW, whether we use W APIs directly or not, our codebase has tons of issues to deal with to take the full advantage of Unicode support on Win2k or later. (In reply to comment #116) > With this change, I could start, open Japanese directory, and open Japanese > filename successfully on Win95! Thanks !! > Some minor problem remains: > I could no longer open local root directrory (e.g.). > This is a regression because I can open it without a patch. Using GetFileAttributesEx rather FindFirstFile, I wanted to avoid the issue, but on Win95, I have to deal with it. See I can port that code over here, but we may as well just forget about Win95 without IE (and possibly Win NT 3.5x). Benjamin, Darin, Wan-Teh and I all agreed, in an offline discussion, that in the long run, we need to implement NSPR UTF-16 APIs and call them in xpcom i/o. The following is my plan I sent to Darin and Wan-Teh offline. 1. Finish what I've been doing and (try to) include it in FF 2.0 (and there are many places throughout our codebase I need to fix so that fixing bug 162361 has a real impact in mozilla) 2. Implement UTF-16 APIs on Win32 (it's relatively easy because we don't have to worry about charset name variants and iconv/wchar_t chaos on Unix) and possibly on Mac OS X. In this step, some lines of code added to nsLocalFileWin will become redudant. 3. Implement UTF-16 APIs on Unix and other platforms After step 2 is complete, we may want to make trunk use NSPR for WINNT (where NSPR UTF16 APIs will use 'W' APIs) instead of WIN95. Anyway, I could have used/can use a lot of '#ifdef MOZILLA_1_8_BRANCH' to use 'W' APIs directly, but given the above plan, it's not worth bothering to... (In reply to comment #110) >. But this may cause tbird tbox bustage. See bug 327675. Tbird tbox seems to not follow the build guide:-) It doesn't matter if this patch land after upgrading the tinderboxes, of course. Created attachment 214627 . Created attachment 214628 . jshin: the tinderbox startup tests record the lowest value of the five runs instead of the average. unfortunately it is really hard to get consistent startup numbers, so i guess someone figured this was a better way to estimate startup time. i think we might be better off throwing out the best and the worst and then averaging the middle three values or something like that ;-) (In reply to comment #121) > BTW, below is the result of the startup time measurement for my optimized trunk The numbers reported earlier turned out to be completely bogus. I wrote a shell script as following (to follow the instruction at ) and ran it from an xterm (under cygwin). ------------------- export NS_TIMELINE_ENABLE=1 for i in `seq 0 5` do ./firefox -P "Default User" > startup.log.$i 2>&1 done ------------- Somehow the lap time reported for 'main1' depends on when I move focus to firefox. (when firefox is started from an xterm under cygwin, the focus doesn't automatically move to firefox) That is, it can be made arbitrarily long. Using 'measure-simple.pl' didn't work either. I also tried it under a non-xterm cygwin console, but it has a similar but different problem. I'll try what tinderbox does (method 2). Incidentally, I'll exclude two extreme points before averaging as suggested by Darin. Here's the tally of 15 runs with and without my patch (optimized static trunk) on Windows 2k(P3 700Mhz, 512MB RAM). (btw, the numbers are sorted) patched not patched ------ --------- 1813 1812 1813 1882 1872 1892 1872 1893 1882 1903 1883 1903 1892 1903 1893 1903 1893 1913 1902 1913 1912 1913 1913 1913 1913 1923 1913 1933 1913 1943 ------------- 1885 1902.8 : average (all 15 points) 32 29 : std. deviation 1888 1906 : average(excluding max/min points) Two-sided Student t-test (assuming the equal variance) and Welch(sp?) t-test (not assuming the equal variance) gave me 0.135269 and 0.135387, which indicates that they're different. Apparently, we have some performance gain with the patch. nice! I had to run before posting my previous comment and made a couple of mistakes. First, the comparison was made between my build with the latest patches for this and bug 278161 and my build with only the patch for bug 278161. The patch for bug 278161 is likely to give a perf. edge to the build with this patch applied so that the comparison is not fair. Second, my conclusion was wrong based on the p-value of 0.13(one-sided p-value is 0.065). With that high p-value, the null hypothesis (two builds are equal in terms of startup time) should be accepted. That is, there's no strong evidence that two builds have any perf. difference. I made a new measurement (23 startups each) with fresh builds, one with only the patch for this bug and the other without any patch applied. One-sided t-test (with H_0 : patched is slower than unpatched) gave me p-value of 0.0074. With the significance level 0.01, H_0 is rejected so that my patched build is rather likely to be faster than unpatched. This is a little unexpected given my first point above. Anyway, the bottom line here is that my patch here does NOT make startup time longer. That is, we don't have to worry about the startup performance. Comment on attachment 214628 [details] [diff] [review] patch updated (for a new patch for bug 326168) Asking for review only for now. Created attachment 215170 [details] review comments from darin on attachment 214628 [details] [diff] [review] Comment on attachment 214628 [details] [diff] [review] patch updated (for a new patch for bug 326168) Please see my attached review comments. Created attachment 215618 [details] [diff] [review] trunk patch addressing Darin's review comment Darin, thanks a lot for your thorough review. I think I addressed all of your concerns. I used 'MAX_PATH' (it seems it's virtually identical to '_MAX_PATH' so that I thought I'd rather 'save' space in the source code :-)). I changed some boundary checking parts and static buffer size because I found that MAX_PATH(=_MAX_PATH) includes the terminating null (it's for paths like "C:\<256 chars>NULL"). Also added are a few more error checkings in SpecialSystemDirectory.cpp. The current trunk doesn't do that, but I thought it's better to be safe. I added nsWinAPIs::sDummy and initialized it with nsWinAPIs::GlobalInit(). I don't have to call NS_StartupWin in nsXREDir...cpp any more. I kept it in nsXPCOMInit.cpp just in case. Anyway, both static optimized build and non-static debug build worked fine. For OM check with SetLength, I added a template helper function |SetLengthAndCheck| to nsWinAPIs.cpp because the same pattern appears several times with nsAutoString and nsCAutoString. I deleted all the commented out codes and unncessary comments while adding a rather long comment about helper functions in nsLocalFileWin (OpenDir, ReadDir, OpenFile, etc.) that will eventually be removed once NSPR implements them. As for not bothering to take care of root path and paths ending with a slash on Win95 (nsWinAPIs.cpp : GetFileAttributesEx), it's very rare to see Win 95 without MS IE 4 or later. Even on such a machine, the only problem is that a user can't open a root path or a path ending with a slash. We can just release-note it instead of copying a raher big chunk of code from NSPR. Btw, MS's own emulation of GetFileAttributesEx in an SDK header file doesn't do that either. I haven't yet tested this patch on real Windows ME (I'm building a non-cairo build now), but with WINAPI_USE_ANSI on Windows 2k, a non-static debug build worked fine. Created attachment 215662 [details] [diff] [review] updated trunk patch to make it work on real Win 9x/ME attachment 215618 [details] [diff] [review] has a critical problem. It doesn't work on Win 9x/ME. 'WINAPI_USE_ANSI' cannot be a true substitute for testing it on an actual Win 9x/ME. |nsWinAPIs::sDummy| was defined _before_ function pointers for Win APIs are so that function pointers set to our emulated 'W' APIs in |GlobalInit| were reverted back to native 'W' APIs which are just stubs on Win 9x/ME. By initializing |sDummy| with |GlobalInit| _after_ function pointers for Win APIs, I was able to avoid the problem. I actually tested a non-cairo debug (non-static) on Windows ME and it worked well. I haven't yet tested an optimized static build (non-cairo), but I guess/hope a static build doesn't have any problem. Still a question remains : Can we rely on the behavior of VC++ 8.0 that the order static variables are initialized is the same as the order they're defined in the source file? Does C++ standard say anything about it? (In reply to comment #132) > Still a question remains : Can we rely on the behavior of VC++ 8.0 that the > order static variables are initialized is the same as the order they're defined > in the source file? Does C++ standard say anything about it? If it works in VC6, then it's fine for the 1.8 branch; for the trunk, Win9x/ME are not supported, so it's a moot point. You should not rely on the order of initializing static vars. Can't we do lazy-init in the nsLocalFile constructor or a similar place? the C++ standard does say that order of initialization is order of declaration. (you can't do a similar thing in C) (In reply to comment #134) > You should not rely on the order of initializing static vars. Can't we do > lazy-init in the nsLocalFile constructor or a similar place? I can (that's one of two alternatives Darin mentioned in his review comment), but because that's a hot spot, I was worried about the overload of a calling NS_StartupWinAPI(). It may not be a problem (can be buried in 'noise'. I need to measure it). If it's not a perf-hit, perhaps it's better to take this approach. (In reply to comment #135) > the C++ standard does say that order of initialization is order of declaration. The order of *declaration* (rather than the order of *definition*)?? Hmm... function pointers are public and declared before |sDummy| (in the defintion of |class nsWinAPIs| in nsWinAPIs.h) which is private, but |sDummy| was initialized *before* function pointers until I moved its definition *after* the definition of function pointers (in nsWinAPIs.cpp). I googled it (newsgroup search) and it seems that it's the order of *definitions* that matters, but it's not definitive . [1] (In reply to comment #133) > If it works in VC6, then it's fine for the 1.8 branch. > for the trunk, Win9x/ME are not supported, so it's a moot point. I know.. that's why I built a non-cairo build. In an unlikely(rare) case of non-GUI embedders, it might not ;-) [1] C++ draft standard (perhaps of C++ 98) has the following. <quote> 3.6.2 Initialization of nonlocal objects [basic.start.init] 1 The storage for objects with static storage duration (3.7.1) shall be zeroinitialized (8.5) before any other initialization takes place. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects of namespace scope with static storage duration _defined_ in the _same_ translation unit and dynamically initialized shall be initialized in the _order_ in which their _definition_ appears in the translation unit. </quote> So, it's the order of definitions that counts, but it's about objects of 'namespace scope' Oh... sorry, yeah, I think I actually mean definition (In reply to comment #133) > If it works in VC6, then it's fine for the 1.8 branch; for the trunk, Win9x/ME > are not supported, so it's a moot point. At least installer should start on Win9x to fix bug 330208. Do you mean bug 330208 should be WONTFIXed? (In reply to comment #136) > I can't build 1.8 branch with VC6 any more because VC6 and VC8-express cannot > coexist on a single machine. Really? I can build trunk with VC8 and build 1.8 branch with VC6 on the same machine. But my VC8 is Standard Edition, so it may make a difference. > >? (In reply to comment #138) > > >? > Gecko as a platform is dropping support for old versions of Windows (Win95,98,ME) for 1.9. Whenever SeaMonkey wishes to release with this gecko version they'll also drop support for those. I was told by the seamonkey council that they were going to work off the 1.8 branch for a long time and would migrate to 1.9 when they were ready. Because of this, upgrading the SeaMonkey windows tinderboxes has not been a priority. (In reply to comment #136) >. I'm writing this using a 1.8 branch build (optimized, static) with the latest patch (slightly changed for the branch) on Windows ME. I can't make a build with VC6, but I found a newsposting in VC++ newsgroup that it's compliant to the standard mentioned by biesi (comment #135 and comment #137) so that I guess we can go with this approach. pav: this patch is being developed with the goal of creating something that can ship in FF2. that may be a tall order, but it's why we are making the effort to support Win9x. For ff2 that makes sense, but for the trunk it seems like we're better off removing all the ascii calls entirely.. Created attachment 215753 [details] [diff] [review] patch for 1.8 branch This is basically identical to attachment 215662 [details] [diff] [review] except for a few differences necessary for 1.8.x branch. An optimized static build with this patch was tested on a real WinME box. > For ff2 that makes sense, but for the trunk it seems like we're better off > removing all the ascii calls entirely.. Perhaps. Maybe someone will want to port the trunk to Win9x? Are we going to tell them "no" ? (In reply to comment #144) > Perhaps. Maybe someone will want to port the trunk to Win9x? Are we going to > tell them "no" ? > I'm not really sure what the right answer is there. I think that developers should be able to ignore win9x and we should start moving our code away from it to cleaner and simpler code. If someone did want to keep it working on win9x it might be better for them to do it as a compatibility library so that we can keep most of the code clean. (In reply to comment #143) > Created an attachment (id=215753) [edit] > patch for 1.8 branch > That patch does not build on 1.8, it makes use of PR_LibSpec_PathnameU which is only on trunk, but that's not the only error. Comment on attachment 215662 [details] [diff] [review] updated trunk patch to make it work on real Win 9x/ME >Index: xpcom/build/nsXPComInit.cpp >@@ -501,14 +504,19 @@ NS_InitXPCOM3(nsIServiceManager* *result ... >+#ifdef XP_WIN >+ NS_StartupWinAPIs(); >+#endif Is this still necessary? >+// This is a dummy variable to make sure that WinAPI is initialized >+// at the very start. Note that |sDummy| must be defined AFTER >+// all the function pointers for Win APIs are initialized. Otherwise, >+// what's done in |GlobalInit| would have no effect. >+// XXX: Can we rely on that |sDummy| is initialized after all >+// the function pointers for Win APIs are? Does C/C++ standard anything to >+// say about the order of initializing static variables? >+PRBool nsWinAPIs::sDummy = nsWinAPIs::GlobalInit(); If we have decided that this works and is valid per the C++ spec, then let's go ahead and change this comment to remove the XXX part. Perhaps you should seek an additional review on this patch... maybe bsmedberg would be willing? ;-) (In reply to comment #146) > (In reply to comment #143) > > Created an attachment (id=215753) [edit] > > patch for 1.8 branch > > > > That patch does not build on 1.8, it makes use of PR_LibSpec_PathnameU which is > only on trunk, but that's not the only error. > I see, it relies on bug 326168 > > That patch does not build on 1.8, it makes use of PR_LibSpec_PathnameU which is > only on trunk, but that's not the only error. Yes, it relies on the patch for bug 326168 as you realized later. The patch for bug 326168 needs to be slightly changed (the diff context is a little different so that it can't be applied cleanly). (In reply to comment #145) > (In reply to comment #144) > > Perhaps. Maybe someone will want to port the trunk to Win9x? Are we going to > > tell them "no" ? > > > to cleaner and simpler code. If someone did want to keep it working on win9x > it might be better for them to do it as a compatibility library so that we can > keep most of the code clean. That's more or less what's done here. Almost everything for Win 9x/ME is confined to WinAPIs.{h,cpp}. Exceptions are that we use 'nsWinAPIs::mCopyFile" instead of '::CopyFileW' in other files(the same is true of other Win32 APIs we use in xpcom i/o) and that there are a couple of |if NS_UseUnicode() ... else ...| in other files. NSPR needs some changes as well (in bug 326168), but it has its 'own life' so that it's not much relevant here. when fixed, Bug 330276 would make it very hard to make trunk work on win9x w/o a compatibility library Created attachment 215818 [details] [diff] [review] updated trunk patch (NS_StartupWinAPIs is now gone) I got rid of the unncessary NS_StartupWinAPIs and NS_ShutdownWinAPIs as pointed out by Darin. I also removed 'XXX' comment about the initialization order. Comment on attachment 215818 [details] [diff] [review] updated trunk patch (NS_StartupWinAPIs is now gone) Darin and Benjamin, thanks for review. Darin, would you sr or should someone else do it? Comment on attachment 215818 [details] [diff] [review] updated trunk patch (NS_StartupWinAPIs is now gone) sr=darin let me know if you need help getting this landed. nice work on this patch, jshin! Thanks, everyone. I've just landed the patch. Without fixing bug 278161, opening a file with characters not covered by the default code page in filename wouldn't work. However, importing IE bookmarks with the same problem should work without fixing bug 278161. So, that should be taken as a test for this patch for now. Created attachment 215859 [details] [diff] [review] 1.8 branch patch updated (no more NS_StartupWinAPis) This is basically the same as attachment 215818 [details] [diff] [review] with a few differences due to the difference between the trunk and the 1.8 branch. This patch relies on NSPR changes in bug 326168 so that the latest patch uploaded for 1.8.x branch in that bug also has to be applied. I'll ask for 1.8 approval after some baking of attachment 215818 [details] [diff] [review] in trunk. In the meantime, anybody is welcome to test it on her/his box (especially Win 9x/ME). On Win 9x/ME, some startup (and other) performance loss is expected because we now store file paths in UTF-16 and convert to and from the native encoding for file I/O on Win 9x/ME. Created attachment 215907 [details] [diff] [review] Patch for mingw-header include/w32api/winver.h The fix for this bug broke compilation with MinGW due to an error in the MinGW header. This header can be corrected with the attached patch; I will also submit it to the MinGW project. The code checked into the trunk for this bug appears to have broken the Windows Thunderbird build. Patrocles is red in the Thunderbird tinderbox. (In reply to comment #157) > The code checked into the trunk for this bug appears to have broken the Windows > Thunderbird build. Patrocles is red in the Thunderbird tinderbox. See comment #110 and comment #120. I also filed bug 331433. Who can fix patrocles configuration? preed handles this sort of thing, i believe. This checkin appears to have caused the regression in bug 331453. Created attachment 216083 [details] [diff] [review] fix a "typo" in attachment 215818 [details] [diff] [review] I'm sorry somehow this stupid mistake crept in. This has a remote chance of being the cause of the regression reported in 331453 Comment on attachment 216083 [details] [diff] [review] fix a "typo" in attachment 215818 [details] [diff] [review] r+sr=darin (In reply to comment #162) > (From update of attachment 216083 [details] [diff] [review] [edit]) > r+sr=darin thanks. this got landed on the trunk Created attachment 216274 [details] [diff] [review] updated branch patch (with a 'typo' fixed, regression taken care of) This incorporates attachment 216083 [details] [diff] [review] and the latst patch for bug 331453 (regression in file download) Created attachment 216551 [details] [diff] [review] fix mingw bustage v1 |const WCHAR| vs |WCHAR| vs |CHAR| again. Probably it is better to fix MinGW directly and to use the proper function declarations using |const| (see Comment 156 and Attachment 215907 [details] [diff]), than to change the mozilla code (see Comment 165). MinGW's CVS is now updated, so the mentioned MinGW bustage should disappear when updating to the most recent MinGW version; see Bug 328499, Comment 48 for instructions. Created attachment 217241 [details] [diff] [review] branch patch with follow-up patches combined This patch includes the patches for bug 331453, bug 332123, bug 331433 (a temporary workaround for misconfigured tinderbox) as well as attachment 216083 [details] [diff] [review]. It's been in the trunk for about 10 days and I guess there won't be any more regression, but it might need still more baking on the trunk. (say, 10 more days...) Darin, can you approve for branch landing when you think this patch has been baked long enough? Once this patch is landed on the branch, we can remove nsWinAPIs on the trunk (as Win 9x/ME is not supported any more on trunk: bug 330276) OK. Let's shoot for later this week. Comment on attachment 217241 [details] [diff] [review] branch patch with follow-up patches combined a=darin checked in on branch on 2006-04-08 10:12 Created attachment 217750 [details] [diff] [review] Fix my branch tinderbox I would like this patch on the branch. It has also been tested on Windows XP. Neil landed his patch for NT 3.51 on 1.8 branch. I had landed my branch patch earlier as noted in comment #170. Comment on attachment 217750 [details] [diff] [review] Fix my branch tinderbox Ooops. Sorry I was mistaken by Neil's tinderbox comment. He just applied the patch to his NT 3.51 tinderbox, but not yet landed this patch. Yeah, this is what I would have done. r=jshin) fifox gave me: check my first attachment it replaced the russian letters with all the same %3F==? thi cant me right I created a second file: tö€ßн.html 2nd screenshot firefox failed of course of the russian н bug also won't display in the browser the € symbol instead %80 is shows %AC this test with some special characters but no russian ones and it works see 3rd screenshot looks perfect even with the € symbol and correct %80 Can somebody explain this? I can't, that's why I don't understand why this is marked as resolved fixed! Created attachment 217937 [details] 1st screenshot fails russian scriptCreated attachment 217937 [details] 1st screenshot fails russian script Created attachment 217938 [details] 2nd screenshot fails russian script and additionally € signCreated attachment 217938 [details] 2nd screenshot fails russian script and additionally € sign Created attachment 217939 [details] 3nd screenshot renders perfectlyCreated attachment 217939 [details] 3nd screenshot renders perfectly (In reply to comment #174) >) Please, set View | Character Encoding to UTF-8 before posting any non-ASCII character. You don't need to attach three screenshots to show what's already well-known. Bug 278161 is not yet fixed on 1.8 branch, which is why you still have the problem. On the trunk, bug 278161 has been fixed so that it should work fine. (see comment #154). Jungshik, I just downloaded Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) Gecko/20060415 Firefox/3.0a1 still fails! what am I doing wrong? (In reply to comment #179) > I just downloaded Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) > Gecko/20060415 Firefox/3.0a1 > still fails! How did you try to open the file? Did you try to open it by double-clicking on a file? That doesn't work yet because our command line handling and parameter passing (for file types associated with firefox) don't yet use 'W' APIs (there are bugs for both issues, but I don't remember bug numbers at the moment). Drag&Drop doesn't work either, but will be fixed very soon on the trunk. However, opening a file with 'File | Open' works fine. So does opening a file by typing '........' in the url bar (probably since the patch for bug 261929 was checked in.) I've just downloaded the latest trunk build and confirmed that both methods worked fine (opening a Hindi-named file) Jungshik, I used double-click only! That's probably the reason. Well, lets wait to have all opening ways patched! (In reply to comment #181) > I used double-click only! > That's probably the reason. That is the reason :-). I should have figured that out from question marks in your screenshot. Why don't you try 'file | open' or typing '<cyrilic file name>' in the url bar. > Well, lets wait to have all opening ways patched! I couldn't find a bug on 'double click and file opening'. The closest I found is bug 268290. I also filed bug 334282. (In reply to comment #182) > I couldn't find a bug on 'double click and file opening'. The closest I found > is bug 268290. I also filed bug 334282. I meant bug 267989. Bug 334282 was duped to bug 282285 Jungshik, just tried 1.9a1: 2006041604 trunk works as you have described altough produced while handling there files high CPU load which lead to browser crash I've just filed a bug relating to Unicode filename. Please see if it could be included in this bug's dependency tree: I know, I know, this bug is closed. Why is GetNativeCanonicalPath lossy? I thought short paths were always ASCII. Short path names are not guaranteed to be present. If the short path is not exist, GetShortPathName will return the input path without modification which may contain non-ASCII characters.
https://bugzilla.mozilla.org/show_bug.cgi?id=162361
CC-MAIN-2017-34
refinedweb
13,016
72.87
Here' ); [download]. has model_name => ( is => 'ro', isa => 'Str', default => 'DB' ); Probably don't want 'DB' as default. That's the perl debug namespace as I'm sure you're aware. I think it looks pretty good. Mind shooting me an email at my GSoC hiveminder address as to what you'd like for scaffolding? Quick note on the namespace - wouldn't CatalystX::Blog::Comments be more appropriate? That way you can stuff more associated classes in under ::Blog Perl Cookbook How to Cook Everything The Anarchist Cookbook Creative Accounting Exposed To Serve Man Cooking for Geeks Star Trek Cooking Manual Manifold Destiny Other Results (146 votes), past polls
http://www.perlmonks.org/index.pl?node_id=773350
CC-MAIN-2014-41
refinedweb
108
62.98
How can I install Scapy? - pythonista72 Hi, just read about 2.0 release, great! :-) But one question. How can I install something like Scapy? It's a complete package with many files... Thank you for your help! Try using the pipcommand in StaSh. I guarantee that you will find yourself using StaSh in the future for other tasks as well. I use this appex scripts for downloading things into pythonista: import urllib2, appex, time, zipfile, os a=time.time() if appex.is_running_extension(): url = appex.get_url() print url e=0 else: import clipboard, editor url = clipboard.get() e=1 response = urllib2.urlopen(url) file = response.read() name = url.split('/')[-1] home = os.path.expanduser('~/Documents/') output = open(home+name, 'w') output.write(file) output.close() print 'Downloaded '+name+' to /Documents/'+name+' in '+str(time.time()-a)+' seconds' if zipfile.is_zipfile(home+name): print 'Extracting zip...' zipfile.ZipFile(home+name).extractall(home) os.remove(home+name) if e: editor.reload_files() Go to the scapy website, download the zip. Once you see it in Safari like this: Click "Open in…", select pythonista, then run my script. Returning to pythonista, you should see a folder scapy-2.3.1. Go into this, and move the scapysubdirectory into site-packages @Webmaster4o Is that the right screenshot? :) @Webmaster4o Nevermind, I see you changed it. Fixed ;) Those were my math grades :) You script didn't work for me. This one did however and basically works as the open in replacement :) # coding: utf-8 # Olaf, Dec 2015, Pythonista 1.6 beta '''Appex GetFromURL Pythonista app extension for use on share sheet of other apps to import file from URL into Pythonista The file is saved at HOME/DESTINATION without user interaction (no 'save as' dialog) unless duplicate''' from __future__ import print_function try: import appex, console, contextlib, itertools, os, os.path, sys, time, urllib, urlparse except ImportError: assert False, 'This script needs the appex module in Pythonista version > 1.5' HOME, DESTINATION = 'Documents', 'FromURL' # you can change DESTINATION to any name of your liking @contextlib.contextmanager def callfunctionafterwardswithsec(function): '''Context-manager that calls function with duration of with block (sec) after termination >>> def pr_sec(sec): print('Duration {:3.2} sec'.format(sec)) >>> with callfunctionafterwardswithsec(pr_sec): pass Duration 0.0 sec''' start = time.clock() yield end = time.clock() function(end - start) def left_subpath_upto(path, sentinel): '''Left part (subpath) of path upto and including sentinel >>> print(left_subpath_upto('a/b/c', 'b')) a/b''' while path: head, tail = os.path.split(path) if tail == sentinel: break path = head return path def iter_pad(length, arg0, *args): '''Iterator to pad arguments (at least 1) to specified length by repetition of final argument >>> print(''.join(iter_pad(3, 'a', 'b'))) abb''' args = (arg0,) + args return itertools.islice(itertools.chain(args, itertools.repeat(args[-1])), length) def parse_into_paths(input_url, HOME=HOME, DESTINATION=DESTINATION): '''Parse input URL into paths tuple for further processing >>> parse_into_paths('', DESTINATION='TEST') # doctest: +ELLIPSIS ('x.py', '', 'Documents/TEST', '/private/var/.../TEST', '/priv.../TEST/x.py', True)''' url_tuple = urlparse.urlparse(input_url) scheme, netloc, basename = url_tuple.scheme, url_tuple.netloc, os.path.basename(url_tuple.path) input_short = urlparse.urlunparse(iter_pad(len(url_tuple), scheme, netloc, '')) output_short = os.path.join(HOME, DESTINATION) output_dir = os.path.join(left_subpath_upto(sys.argv[0], HOME), DESTINATION) output_path = os.path.join(output_dir, basename) is_Python = os.path.splitext(basename)[1].lower() == '.py' return basename, input_short, output_short, output_dir, output_path, is_Python def copy_url(input_url): '''Write a copy of the file at input_url to HOME/DESTINATION if the destination directory doesn't exist, it is created if the destination file already exists, the user can cancel or overwrite if it is a Python file, a comment line is added to log the origin''' basename, input_short, output_short, output_dir, output_path, is_Python = parse_into_paths(input_url) if not os.path.exists(output_dir): os.mkdir(output_dir) console.hud_alert('Created destination directory {}'.format(output_short)) if os.path.exists(output_path): try: console.alert('Duplicate file', '{} already exists in {}'.format(basename, output_short), 'Overwrite') # or Cancel except KeyboardInterrupt: return with contextlib.closing(urllib.urlopen(input_url)) as input: data = input.read() console.hud_alert('Got {} ({} chars) from {}'.format(basename, len(data), input_short)) with open(output_path, 'wb') as output: if is_Python: datetime = time.strftime('%a %d-%b-%Y %H:%M:%S', time.gmtime()) output.write('# Retrieved from {} on {}\n\n'.format(input_url, datetime)) output.write(data) console.hud_alert('Wrote {} to {}'.format(basename, output_short)) def main(): '''App extension logic, with unit tests if run within Pythonista''' if appex.is_running_extension(): if appex.get_url(): copy_url(appex.get_url()) appex.finish() else: console.hud_alert('No input URL found', 'error') else: console.hud_alert('This script must be run from the sharing extension', 'error') import doctest doctest.testmod() if __name__ == '__main__': main() Does Scapy actually run under Pythonista? @miwagner1 I updated it, that might fix your issue? Ya fixing the path to have Pythonista generate, os.path.expanduser did it. now lets hope apple won't make him pull the extension as its letting me do all sorts of cool stuff. Just for fun, I downloaded scapy 2.3.1, unzipped it, and moved it to site-packages. If I then try to run main.py, I get errors in console regarding IPv6 support disabled in Python. That's probably OK but then the program stops at line 278 with NameError:name 'LOOPBACK_NAME' is not defined. How did you get this to run? I didn't actually test it, I just imported. Import worked for me, though. I am getting the same NameError:name 'LOOPBACK_NAME' is not defined error that @ihf came across a year ago. Does anyone know how to get around that? I would really like to be able to use scapy. Thanks! Look at this link. I have not tried it. I came across this before but didnt make test the change because Im on an iPad running stash. Ill give it a shot and see what happens. Thanks! I added this to the ../windows/__init.py__file and there was no change. I then added it to the __init.py__file in the arch folder and that changed the error from LOOPBACK_NAME to consts... stash: <type 'exceptions.ImportError'>: No module named consts Any other ideas? Thanks in advance I posted a GitHub issue... Pythonista does not support modules like subprocess. Hence I think that you may not be able to run this on pythonista. I am able to install it but it gives error while running (not able to start the interactive session). @abcabc Interesting. So how are people actually using scapy then? Just running it from a script? Seems odd that there is no interactive shell to test on..
https://forum.omz-software.com/topic/2539/how-can-i-install-scapy
CC-MAIN-2018-05
refinedweb
1,083
53.78
Hi Everyone I am trying to solve Problem I gone through editorial but not able to get it . Below is the function where i got stuck .Could someone please tell me how to calculate below function efficiently for each n . Hi Everyone I am trying to solve Problem I gone through editorial but not able to get it . Below is the function where i got stuck .Could someone please tell me how to calculate below function efficiently for each n . Hi Everone , I tried problem , not able to comeup with any proper logic . I checked the editorial also, solution is not clear could someone help to understand how to approach this problem . We have set of intervals [theta,-theta] . I want to find out the optimal value of theta [-180,180] which lies in the maximum no of intervals . Value of theta can be float . Can you please help me find the way to find out the optimal theta. Every Friday night, Alice, Clara and Mary go to Koerner’s pub to relax after a long week. At the pub, lots of guys ask them for their phone numbers. In fact, the three ladies are so popular that they have started counting the number of times each one is asked for her phone number during one evening. On day i, Alice, Clara and Mary were asked Ai , Ci and Mi times, respectively. 100 Fridays have passed, and the records were lost, but there are 3 things Alice still remembers. 1. X of the 100 days, Ai was equal to Ci . 2. Y of the 100 days, Ci was equal to Mi . 3. Z of the 100 days, Ai was equal to Mi I want to find out the how many maximum and minimum no of day Ai,Bi,Ci will be equal ? I tried to use inclusion exclusion principle not able to get it exactly how to apply here ? A . Hi All, DEC Long challenge is over , can anyone please give some hint how to approach this problem Sereja and Increasing subsequence. (sorry for bad english) Edit :editorials are not published yet :( Hi Friends can you please help me solve the below problem . I try to find out some sources to Learn Nim and grundy theorem . But I did not find any explanation , why the logic works . Please refer some problems . I tried this Problem then i am able to get the dp relation dp[i][k]=(1/(i+1))*dp[i-1][k]+(i/(i+1))*dp[i-1][k-1] where dp[i][k] represent the probability of collection of k candies in first i bags . But here the value of N is very high so i am unable to solve it,that will be great help,Thanks in advance I tried this Problem but getting WA ,I don't know why i am keep getting WA .If some one find out the fault in my code that would be great help!! Your code here... #include<iostream> #include<cstdio> #include<utility> #include<map> #include<set> #include<queue> #include<algorithm> #include<cmath> #include<cstdlib> #include<cstring> #include<vector> using namespace std; #define si(x) scanf("%d",&x); #define s2i(a,b) si(a)si(b) #define sl(x) scanf("%I64",&x); #define s2l(a,b) sl(a)sl(b) #define ss(x) scanf("%s",x); #define pi(x) printf("%d",x); #define pl(x) printf("%I64",x); #define ps(x) printf("%s",x); #define line printf("\n"); #define space printf(" "); #define p2i(a,b) pi(a) space pi(b) #define p2l(a,b) pl(a) space pl(b) #define vinit(_size_,_value_) resize(_size_,_value_) #define _mem(value,_array_) memset(_array_,0,sizeof(_array_)) #define ULL long long int //#define ULL unsigned long long int #define _pi pair<int,int> #define _pl pair<LL,LL> #define _vi vector<int> #define _vl vector<LL> #define _vpi vector< _pi > #define _vpl vector< _pl > #define _f first #define _s second #define _pb push_back #define _mp make_pair ULL mygcd(ULL a,ULL b) { ULL c; while(a!=0) { c=a;a=b%a;b=c; } return b; } ULL mylcm(ULL a,ULL b) { ULL ans=a; ans=ans/mygcd(a,b); ans=ans*b; return ans; } ULL N,M,g,x,y,gx,gy,go,k; int main() { int tc; cin>>tc; while(tc--) { scanf("%lld%lld",&M,&N); g=mygcd(M,N); if(g==1) { cout<<M*N<<endl; continue; } x=M/g; y=N/g; k=x*y; gx=mygcd(g,x); gy=mygcd(g,y); k=k*gx*gy; printf("%lld\n",k); } return 0; } ` I tried this problem VPALIN ,I know it can be solvable using Trie ,but i am unable to frame the idea would anyone like to help to frame the idea :) ? Hii I am trying to solve this problem after thinking so many days i am not able to come up with efficient solution ,would any one like to suggest some idea, how to solve this ? I read the editorial of the this Problem but i am not able to get the idea, would anyone like to help me to understand the solution of problem . Actually This is a piece of question ,i am struggling in that part so i want help . 1. so the problem is you have two equations — v=x*v1+y*v2 — x*s1+y*s2<=s you have the values of v1,v2,s1,s2,s all are fit in 32 bit integer .you have to maximize the value of v ?? Constraints : s1>=1,s2>=1,v1>=1,v2>=1,v>=1,s>=1,x>=0,y>=0 and s1,s2,v1,v2,x,y,v,s all are positive integer. Here is Problem Link i read its editorial but unable to understand it would anyone like to make me understand this problem ? Here is the Link of the topcoder problem Link i read its editorial but not able to get it would anyone like to help me to understand this ?? I want to know how to create suffix link in suffix automaton ? I tried a lot, I read suffix automaton from this site but unable to get the idea . I tried some papers from that to hard to understand for me.If someone want to explain ,it will be great help for me and another naive coders .Hope if you use figures(pictures) that will be awesome. Can anyone Guide me how to optimize this relation where b[j]>=b[j+1] and a[i]<=a[i+1] .I know for optimization use convex hull trick and i read convex hull trick ,but i don't know how to use this trick to optimize this Dp relation. I am trying to solve the problem MATSUM on spoj.I try it using 2D Binary Indexed Tree.But keep getting Time Limit Exceeded.If my approach to solve this problem is not good enough then please suggest another methods.If my approach is correct then please guide me how to get rid-off from TLE. My code is below Your code here... #include<iostream> #include<cstdio> #include<vector> #include<queue> #include<stack> #include<utility> #include<map> #include<stdlib.h> #include<string.h> using namespace std; #define g getchar_unlocked() int scan()//fast input output { int t=0; char c; c=g; while(c<'0' || c>'9') c=g; while(c>='0' && c<='9') { t=(t<<3)+(t<<1)+c-'0'; c=g; }//end fast input output return(t); } vector<int> Matrix[1026]; int N; // MAXVAL for Binary indexed tree tree(1 based indexing) void initialize() { scanf("%d",&N); for(int i=0;i<N;i++) Matrix[i].resize(N+2); return ; } int Freq_at_idx(int idx,int vec_idx) { int sum=Matrix[vec_idx][idx]; if(idx>0) { int z=idx-(idx&-idx); idx--; while(idx!=z) { sum-=Matrix[vec_idx][idx]; idx-=(idx&-idx); } } return sum; } void update(int vec_idx,int idx,int v) { while(idx<=N) { Matrix[vec_idx][idx]+=v; idx+=(idx&-idx); } return ; } // it gives the sum of all the elements from 1 to idx of vector Matrix[vec_idx] int Cumilative_Freq(int vec_idx,int idx) { int sum=0; while(idx>0) { sum+=Matrix[vec_idx][idx]; idx-=(idx&-idx); } return sum; } void set_value(int x,int y,int v) { int v1; v1=Freq_at_idx(y+1,x); v=v-v1; if(v==0) return ; update(x,y+1,v); } void get_sum(int x1,int y1,int x2,int y2) { int sum=0; for(int i=x1;i<=x2;i++) { sum+=Cumilative_Freq(i,y2+1)-Cumilative_Freq(i,y1); } printf("%d\n",sum); return ; } int main() { int x,y,v,x1,x2,y1,y2; char str[5]; int tc; //scanf("%d",&tc); tc=scan(); while(tc--) { initialize(); scanf("%s",str); while(str[0]!='E') { if(str[1]=='E') { //scanf("%d%d%d",&x,&y,&v); x=scan(); y=scan(); v=scan(); set_value(x,y,v); } else { //scanf("%d%d%d%d",&x1,&y1,&x2,&y2); x1=scan(); y1=scan(); x2=scan(); y2=scan(); get_sum(x1,y1,x2,y2); } scanf("%s",str); } for(int i=0;i<N;i++) Matrix[i].clear(); } return 0; } I read the editorial of this Problem But i did't understand it's bruteforce solution (the one ,that is given in the editorial) how it work, it will be great help if you make me understand how it work.If anyone provide Dp solution,please provide it and the reference code. [problem:] HELP me in this problem can any one explain the logic behind this ? [problem:] HELP me in this problem can any one explain the logic behind this ? HERE IS THE CODE can any one t const int MAX = 86044176; const int LMT = 9267; const int LEN = 5000000; int flag[MAX>>6], primes[LEN+5]; void sieve() { register int i, j, k; for(i = 3; i < LMT; i+=2) { (i<100) && printf("%d\n",ifc(i)); if(!ifc(i)) for(j=i*i, k=i<<1; j < MAX; j+=k) isc(j); } primes[1] = 2; for(i=3, j=2; i < MAX && j <= LEN; i+=2) if(!ifc(i)) primes[j++] = i; } void print() { for(int i=0;i<(MAX>>6)&&i<300;i++) printf("%d\t",flag[i]); printf("\n"); /*for(int i=0;i;i++) printf("%d\t",primes[i]); printf("\n"); */ } int main() { char buff[11]; //register int q = atoi(fgets(buff, 11, stdin)); sieve(); //print(); //while(q--) printf("%d\n", primes[atoi(fgets(buff, 11, stdin))]); return 0; } can any one explain how to solve this problem i am very weak in dp ? how to think plz explain it fully (sorry for my poor english )
http://codeforces.com/blog/selfcompiler
CC-MAIN-2020-05
refinedweb
1,766
67.89
DNA Toolkit Part 3: GC Content Calculation In this article, we are going to implement two functions. The first function will count G and C nucleotides (GC Content) in a string, and the second function will use the first function but allow us to specify a ‘window’ size to calculate GC content in. Here is a Wikipedia excerpt on GC Content: In molecular biology and genetics, GC-content (or guanine-cytosine content) is the percentage of nitrogenous bases in a DNA or RNA molecule that are either guanine (G) or cytosine (C).. When it refers to a fragment, it may denote the GC-content of an individual gene or section of a gene (domain), a group of genes or gene clusters, a non-coding region, or a synthetic oligonucleotide such as a primer. A Wiki link: A discussion link: So open our dna_toolkit.py file and add the first function: def gc_content(seq): """GC Content in a DNA/RNA sequence""" return round((seq.count('C') + seq.count('G')) / len(seq) * 100) This is a very simple function as we only use built-in Python functionality. We search for character ‘C’ and ‘G’ using count() method of the sequence we pass to this function (seq). Then we use the most basic calculation to get the percentage (%). Basically: the amount of G and C, divided by the length of the whole sequence (seq) and then multiplied by a 100 to get %. So if we pass “ATCG” to our function, we should get 50% back, if we pass “ATCA”, we get 25% back and we get 75% if we pass “AGCG” for example. Now, what if we want to count GC content in sub-areas of a DNA sequence? Let’s say we are interested in ‘window’ size 3: window = 3 seq = "CGATGAATCTATA" So we would have something like that: [CGA]TGAATCTATA = 67% CGA[TGA]ATCTATA = 33% CGATGAA[TCT]ATA = 33% CGATGAATCTA[TAA] = 0% We can ‘prepare’ our DNA string before we pass it to gc_content(), and pass each part of size ‘windows’, but this will take a lot more code and users of our gc_content() function will not be happy about having to prepare data before using our function. So let’s fix that and program our second function: def gc_content_subsec(seq, k=5): """ GC Content in a DNA/RNA sub-sequence length k. k=20 by default """ res = [] for i in range(0, len(seq) - k + 1, k): subseq = seq[i:i + k] res.append(gc_content(subseq)) return res We are using our original gc_content() (line 9) function and we are adding a little bit of logic on top of that to handle the ‘window’, which we call ‘k‘ and we set it to 5 by default, just in case if you forget to pass k to our function. Our for loop makes sure we scan the whole sequence and make k (5 by default) jumps, to replicate the example above. We use string slicing to grab only the part of the string we need, which, again, is of size k (our window). And we accumulator results in a list res. So now if we run this on another test DNA string: “ATATGATAGATAGCCCAGTCCGT“, and a window size 5, we should have this output: [20, 20, 60, 60] Alright. Now we have our two new functions working, let’s add a proper output to our main.py file and run the whole thing: print(f'[5] + GC Content: {gc_content(DNAStr)}%\n') print(f'[6] + GC Content in Subsection k=5: {gc_content_subsec(DNAStr, k=5)}\n') If we run our main.py file now, we should see something like this: Sequence: CTGTCCTTCTCATCTACGGTGATTCCAATGTGGTACATTGCGCTTTTTCA [1] + Sequence Length: 50 [2] + Nucleotide Frequency: {'A': 8, 'C': 13, 'G': 9, 'T': 20} [3] + DNA/RNA Transcription: CUGUCCUUCUCAUCUACGGUGAUUCCAAUGUGGUACAUUGCGCUUUUUCA [4] + DNA String + Complement + Reverse Complement: 5' CTGTCCTTCTCATCTACGGTGATTCCAATGTGGTACATTGCGCTTTTTCA 3' |||||||||||||||||||||||||||||||||||||||||||||||||| 3' GACAGGAAGAGTAGATGCCACTAAGGTTACACCATGTAACGCGAAAAAGT 5' [Complement] 5' TGAAAAAGCGCAATGTACCACATTGGAATCACCGTAGATGAGAAGGACAG 3' [Rev. Complement] [5] + GC Content: 44% [6] + GC Content in Subsection k=5: [60, 40, 40, 60, 40, 40, 40, 40, 60, 20] This is it for this article. Feel free to watch a video version below, join our bioinformatics community and leave a comment below:
https://rebelscience.club/2020/04/dna-toolkit-part-3-gc-content-calculation/
CC-MAIN-2020-45
refinedweb
691
53.95
in reply to Executing use'd/require'd/base module code *after* use'r/require'r/child is compiled? You could use B::Hooks::EndOfScope in an import method. That's what namespace::clean uses to clean up the package's symbol table after it has been compiled. I hope this helps, but I'm not sure this exactly fits your use case. Is there a reason you don't want to be more explicit? Like, for example: wrap foo => sub { ... }; Perl Cookbook How to Cook Everything The Anarchist Cookbook Creative Accounting Exposed To Serve Man Cooking for Geeks Star Trek Cooking Manual Manifold Destiny Other Results (155 votes), past polls
http://www.perlmonks.org/?node_id=747342
CC-MAIN-2014-41
refinedweb
111
66.03
07 March 2008 13:56 [Source: ICIS news] SINGAPORE (ICIS news)--Singapore’s PCS has reduced its cracker’s operating rates to below full capacity due to high feedstock naphtha costs, resulting in lower output of aromatics, said a company source on Friday. ?xml:namespace> “Aromatics production is lower,” he said. Declining to reveal the reduced operating level, the source said that the cracker’s margins were poor due to the rally in naphtha prices. Production levels had been reduced since the beginning of the month and the company was assessing the market to decide when the cracker’s output would be ramped up, he added. The Jurong island-based plant produces 150,000 tonnes/year of toluene and 80,000 tonnes/year of solvent grade xylene. Meanwhile, a southeast Asia-based trader of solvent grade xylene said that the material was in tight supply in the region due to a reduction in production levels by regional makers. The naphtha to toluene spread was calculated at $74-87/tonne, while the spread with solvent grade xylene was at an even narrower range of $24-32/tonne. Traders estimated $130-140/tonne to be the break-even point and variable cost of production from naphtha to mixed xylenes (BTX). Toluene prices in Asia were assessed at $975-990/tonne FOB (free on board) Korea, solvent grade prices were at $925-935/tonne FOB Korea, while naphtha prices were at $901-903/tonne CFR (cost and freight) Japan,
http://www.icis.com/Articles/2008/03/07/9106897/pcs-lowers-cracker-output-on-high-naphtha-costs.html
CC-MAIN-2014-52
refinedweb
246
55.17
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives! Here's one: Hutton's Tutorial on the universality and expressiveness of fold. Another one I like (slightly beyond the things in the lecture, though): Y in Practical Programs by Bruce McAdam. The first slide: curlyC(A,B) = { A->B e curlyC } What is curlyC? Can I assume that this is just really sloppy notation? what does the "|-" symbol mean? And what does Gamma |- M : A mean? I'll take a shot at that (thus opening myself up to ridicule). Turnstile notation is used for formal logics. If L is a formal logic in which a particular proposition P can be proven, one writes L |- P. If your type system Gamma allows you to conclude that M has type A, you write Gamma |- M : A. I give a fairly in-depth answer to this question on the CS StackExchange: It also links to a blog post that connects the notation to code. I think what that stuff about curlyC means is "The notation curlyC(A, B), for any category curlyC and objects A and B in that category, shall mean the collection of every morphism f that goes from A to B in curlyC." This is known as the hom-set between A and B, and it has many notations. According to Wikipedia, "The collection of all morphisms from X to Y is denoted homC(X,Y) or simply hom(X, Y) and called the hom-set between X and Y. Some authors write MorC(X,Y), Mor(X, Y) or C(X, Y)." So this is Wadler establishing what notation will be used for the hom-set in this presentation. --- Meanwhile, "Gamma |- M : A" is type theory notation. It means "In the context Gamma, the expression M has type A." A context is also known as a scope or environment. It encodes what variables are available and what their known types and/or bindings are. Contexts are often given the name Gamma, for some reason. At 38 minutes. Eh, what does that mean for actual programming? He's just described the principle of duality in category theory, which I'm happy to agree is a cool thing about category theory. But whether it has anything to do with actual programming depends on whether you subscribe to the pure-functional agenda for actual programming. Personally, I don't. It's quite true that our mathematical technology does a lousy job of coping with side-effects in programs; Wadler sees in that a problem with side-effects, I see in it a problem with our mathematical technology. Either way, he's working through the connection between logic and programming called the Curry-Howard correspondence (CH). An important (imho) thing to keep in mind about CH is that it's a connection between formal reasoning about types in programs, and formal reasoning in general. That's important because of what it doesn't say: CH is not a connection between formal reasoning and computation. It's all just about types. In programming, types are (at best) a means to an end; actually doing computation is what really matters, and types are an incidental device intended to help correctly specify how to do computations. In formal logic, the actual reasoning is the whole point; working through the correspondence, it's as if making sure your program is correctly typed were more important than what happens when you run it. This leads, of course, to one of the things I deeply disapprove of about CH: I see it as distracting from things in programming that should matter more than typing. My attitude is, of course, so alien from Wadler's mindset that I suspect we may not even be disagreeing so much as thinking past each other. Yes, I caught that comment about side-effects. My immediate thought was "and how are you going to model side-effects in this formalism?". Thanks for the clarification. I was actually hoping for a theorem "If your programming model satisfies this duality then you can not have deadlock" (or whatever other desirable property) and I could then live with a corollary "functional languages satisfy this duality so they don't have deadlock" (or whatever). I've tried reading up on categories several times now, and have never come across such a theorem that would explain why I would care. It's all nifty, but to me it never leaves the domain of the abstract. Well, the question "and how are you going to model side-effects in this formalism?" has an answer, of course: monads. (Speaking of type systems run amok.) Though I don't think we've anywhere near a mathematical handle on side-effects, a small first step is the variant lambda-calculus of Felleisen's dissertation (to which my own dissertation added the notion of specialized classes of mediating variables). A curious result I've heard of: Timothy Griffin showed that the usual Curry-Howard correspondence, which relates lambda-calculus to intuitionistic logic, can be extended to relate Felleisen's side-effect-ful calculus to classical logic. Which doesn't deter my criticisms of Curry-Howard, but seems like a glimmering of... something. You can model side-effects as monadic sets, where the type constructor becomes a set of 'effect flags'. This means function types effectively list the 'types' of side effects they can produce in their return types. Even if you can model effects as monads its the wrong idea. Functional programming is an incomplete model. It's great for calculating things but incompetent at doing them. The right approach is to meld calculations with actions in a symmetric way as hinted by Andrzej Filinski in his master thesis and later papers. As it turns out my Felix programming language is ahead of him, it already implements a system which combines values, functions, and continuations using fibres and synchronous channels. (Similar to Hoare's CSP but without concurrency: fibres are coroutines not processes). This system is desperately in need of theoretical analysis to make it easier to reason about. The key is probably a type system, but not the kind you're used to: active programming is all about control so we need type systems to approximate control models. The simplest constructions is a pipeline which looks like: src -> tr1 -> tr2 -> tr3 -> sink where src plays the role of a value, trx are transducers which are like functions, and sink is the final continuation. Pipe formation is composition and so associative. It's no accident the arrows look categorical! By adding parens you can see: (src -> tr1) -> tr2 -> (tr3 ->sink) that the first group, value + function is a value, and the last group, function plus continuation is a continuation (you already know function plus function is a function, right? :) So in this model, the boundary between values, function, and continuation is notional: its wherever you want it to be (just slide the parens about). A simple pipeline therefore subsumes both applicative functional programming and procedural programming. And if you go to more complex flow arrangements it transcends both. A pipeline of continuously running (or one shot) fibres is an example of a control model. This one is easy to work with and clearly "correct" whatever that means. A more difficult model involves a fibre that writes its result to its own input. That can be easily proven to be equivalent to suicide: an extra fibre acting as a buffer is required and then you have a model of tail recursion. (The picture is a bit hard to draw with ascii art). We all know you can do any procedural code in a functional system, and any functional code in a procedural one. They're known to be equivalent. What has been lacking until now is a way to do BOTH in the same program with unified model. This is interesting, but lets first address effects, as what you propose has nothing really to do with effects as far as I can see, although maybe you can correct me. I came across several examples in Rust where effects would be necessary. One example is if I take a value out of a data structure I have to replace it with another. Due to Rusts safety constraints I cannot leave the value undefined for even a microsecond. It is an atomic swap or nothing at all. The problem is that if any operation causes a panic (Rust's version of an exception) and Rust unwinds the stack, there could be a crash as there is data missing which is not allowed. If we could guarantee no exceptions, we could allow a function to run and then replace the data, which overall would result in a neater and better performing solution. Other examples would be interrupt handlers that are not allowed to allocate memory, using effects the caller could ensure that constraint is enforced. So the purpose of effects is to expose side-effects to the type system in a way that function signatures can impose constraints on those side-effects. In your examples I have no way of knowing if "tr1" allocates stack or heap memory, opens a file, reads or writes data to message ports, throws exceptions, takes longer than "N" clock-ticks to run, etc. What is missing in your 'pipelines' is the type of the data that is being transferred, but it would seem trivial to have a constructor for a Pipe, which is effectively a lazy list, you would then have the following signatures, assuming the data passed along the pipe is a stream of integers: src : Pipe Int tr1 : Pipe Int -> Pipe Int tr2 : Pipe Int -> Pipe Int tr3 : Pipe Int -> Pipe Int sink : Pipe Int -> () That would of course be for functions with no side-effects. Lets assume that tr1, tr2 and tr3 have no side effects, and src reads from a file and sink writes to a file. The type signatures of trN do not have to change, but src and sink might become: src : [FileRead] (Pipe Int) sink : Pipe Int -> [File Write] (Pipe Int) and the code would simply be: sink(tr3(tr2(tr1(src)))) or perhaps nicer: sink ((tr1 . tr2 . tr3) src) or using Haskell's arrow notation: sink ((tr1 >>> tr2 >>> tr3) src) Edit: Even better would be to have a pipe as a type-class, so that a pipe can define an interface. Then you would have: src : Pipe a => a -> [ReadFile] a tr1 : Pipe a => a -> a tr2 : Pipe a => a -> a tr3 : Pipe a => a -> a sink : Pipe a => a -> [WriteFile] () Functional programming can model those pipelines, no problem. Cf. presentation by Rúnar Bjarnason on machines and the associated library by Bjarnason and Kmett. FP is a 'complete' programming model in the sense that it can express both arbitrary programs (with arbitrary effects models) and the arbitrary machines to interpret them. For 'competence' the main question is whether we can achieve competitive performance. Can we leverage a GPGPU to accelerate graphics and vector processing and machine learning? Can we leverage multiple CPUs? How about massive clouds and mesh networks? Can we model incremental inputs and reactions to an input? Can we work effectively with 'big data', e.g. multi-terabyte log-structured merge trees as first-class values? Pure functions can do these things. For example, accelerate and lambda cube support GPGPU processing. However, such features require either special support from a compiler/runtime (which is absent with unfortunate regularity) or a library hiding unsafePerformIO under the hood to integrate external resources (which is ugly, and frequently involves painful configuration issues). Despite those caveats, I believe FP languages will gradually bridge all relevant performance gaps. (edited for clarity:) Separating 'performance' features from 'effects' models seems worthwhile even outside a purely functional contexts that would force the issue. Like any separation of concerns, this separation can improve simplicity, security, and accessibility. Examples: If accelerated graphics processing is available as a pure function, we could easily have spreadsheets that present ad-hoc images in cells without worries about side-effects. If databases are first class values rather than requiring sophisticated interactions with a network or filesystem, we can more directly model experiments, tests, and forking/backtracking whole databases. I am not sure I get your comment about separating effects models. Personally I want to write imperative code for readability, but have the same advantages as functional languages for type safety and composability. I want to be able to write an efficient string manipulation module that is imperative internally and explicitly manipulates memory for performance, but presents a functional API to the rest of the program, ideally with meta-level proofs of soundness. Functional languages will never bridge the performance gap in my opinion because optimisations are domain specific. The fastest way to manage memory for a matrix library is different from the fastest way to manage memory for strings. Each application domain needs low level access to write efficient code and optimisations specific to that domain. Hence my objective of a language that lets you write precise imperative code for expert written libraries, but let's the library user operate in a safe functional way that doesnt need to manage memory. I understand your opinion on FP performance is a common one. But I've never seen a good argument for that belief. I just see pessimism or post-hoc rationalization for one's commitment to another programming paradigm. The argument you present above is no exception. There is nothing about functional languages that prevents domain-specific optimizations. I can support any specific domain I please, e.g. optimize matrix structures and functions to manipulate them. If I want to model efficient imperative-style mutation and explicit memory management, I can introduce a notion of unique/linear vectors. If I need to optimize a wide variety of domains, I can develop a general system of performance annotations to mark types and functions, and support a modular compiler. There is more than one way to "low level access" and optimize new domains. Conversely, there is nothing about imperative languages that guarantees precise control over representations, memory management, or ability to usefully hand-implement domain specific optimizations. This is aptly demonstrated by languages such as Basic, Python, and Ruby. AFAICT, you're conflating too many concerns to present a coherent argument about the potential future limits of performance in functional languages. That said, I won't discourage you from pursuing your vision of functional-imperative programming. It is certainly a low risk approach, depending only on decades old well proven techniques. You are right, you could provide a library of domain specific optimisations by perhaps allowing new rewrite rules to be added to the compiler. Let's think about this, now instead of writing in one language you are writing in two, a functional implementation in one, and a bunch of rewrite rules in another. This seems a more complex and worse solution than a simple language that provides access to memory layout and mutable bits. It also seems harder to debug because you cannot see the final code as you cannot write the result of the optimisations in the source language. This means you also have to understand the target language. This approach seems worse the longer I think about it. Performance annotations are similar, why not write what you want to do directly and simply instead of writing what you want and then tweaking it with magic compiler tweaks to control how it is implemented. This seems like trying to drive a car by shouting instructions to a blind man at the wheel. The argument about Ruby and Python is a straw man, as I am sure you realise. What you see as conflation, I see as a web of interconnected reasons. That you see it as conflation may be because you don't understand the problem, although it's more likely I am just not explaining myself very well. In practice, performance features tend to cover a wide variety of domains. Like the GPU style of computing is good for a lot more than graphics, and has been extended to cover machine learning and physics simulations. Even your own position is essentially that "we can hand-implement a lot of domain optimizations given an efficient model for mutable vectors of bits". (Of which there are several suitable for FP.) Ultimately, it doesn't take tweaks specific to every little domain to get competitive performance. As far as "writing in two languages" goes, that's not a significant issue. It is not at all uncommon for functional programmers to model a wide variety of mini languages for specific problems. Separating the program from its implementation is convenient outside of performance reasons. I do not consider this separation inherently a "more complex or worse solution" than programming in a more direct style. This seems like trying to drive a car by shouting instructions to a blind man at the wheel. Performance annotations can be robust, precise, and predictable. In the sense of not merely being "suggestions", but instead being closer to "language extensions" oriented around performance. In any case, with regards to whether FP will gradually bridge the performance gaps, concerns of convenience or complexity seem much less critical than simply having a straightforward approach that is known to be workable. Integrating features like par/seq parallelism or GPGPU acceleration of vector math into the language IS straightforward and known to be workable. Let's not shift goal posts too much here. The argument about Ruby and Python is a straw man It's a fine, constructive counter to: "imperative programming gives me performance". I grant that might not be your argument. You seem to be tossing a lot of features under the 'imperative' banner that have nothing to do with expressing programs in the imperative mode. Including efficient models for update-able bit vectors, precise control of representation, and avoidance of GC. Indeed, but then what is the difference between functional and imperative programming? I think functional programming has several desirable features, but when you include monads and mutable references you have an imperative embedded DSL in any case. It is possible to write pure functions in an imperative language too. So functional languages can close the gap, but the code will either look like imperative code, or a functional description will get transformed into imperative code by annotations or rewrite rules. In the latter cases what you have is an obfuscated imperative program. Imperative programming is differentiated from purely functional programming, in a technical sense, primarily by aliasing of state. One procedure can update state and another can observe this update without any explicit communication on a call-return path. This becomes the usual basis for side-effects. And a source of implicit entanglement with the environment. FP can, of course, model imperative aliasing. But must do so explicitly, e.g. using a reference model within a state monad. OTOH, if what you want is just efficient mutation, you don't need aliasing or effects. You could use affine types or unique representations so your compiler/interpreter can update a representation of data in place without risk of another function observing the change. Regarding "a functional description will get transformed into imperative code (...) what you have is an obfuscated imperative program", I think by that logic one should conclude all high level programs are ultimately obfuscated machine code. I nonetheless enjoy the properties of pure language during the bulk of software development and maintenance. "One procedure can update state and another can observe this update without any explicit communication on a call-return path" Yes, good definition, and explanation of what's wrong with it (traditional imperative programming), except your statement is too specialised saying "call return path" since others exist than the master/slave model. But FP is just as bad. Remember lambda doesn't specify order of evaluation! But with fibres, there IS explicit communication. As mentioned earlier, consider a fibre that reads, acts, then reads again in a loop. You can make a logical statement: the action occurs *between the reads* and this is well defined. It's not lambda calculus: the control flow is explicit. But wait! We were listening to Wadler talk about Curry-Howard? Isn't a proposition such as the one I just made about read/then act/read again .. isn't that (isomorphic to) a TYPE? It's a CONTROL TYPE. chip tr[D,C] (f:D->C) connector io pin inp: %<D pin out: %>C { while true do var x = read io.inp; var y = f x; write (io.out, y); done } This is a function adaptor transducer that converts a function of type D->C into a fibre which reads a D on the inp channel and writes a C on the out channel, then goes back, the channels are typed, but this is only the data type. I do not know how to specify the control type. (Yes, that's real working Felix code) D->C The endpoints of control types are EVENTS such as "read on io.inp", "write on op.out", loop. What's important is that if you join two of these in a pipe, the CONTROL types have to agree somehow, not just the data types. If you consider a loop which writes first, then reads, and try to plug it into a read then write chip in a pipeline fashion, it deadlocks, and which causes both fibres to suicide provided the connecting channels are otherwise unreachable (due to garbage collector). So in some sense the combined types equal the proposition "false". So, the fibre above: its a function, its pure, it has a datatype. Its also a procedure, and it has definite control type type as well, although I do not know how to express it notationally. The key to the model is that matching reads and writes are synchronisation events. Order of operation is only defined between such events. The events are totally ordered. In Felix the order is deterministic, but in a more abstract model it is not (on synchronisation which of the two meeting fibres goes first?) If you throw effects into the loop above, or some more complex chip with multiple I/O channels, you can still reason about the chip and how it can be composed with others. The Felix compiler actually automates one such reasoning, it gives a warning if all the channels connected together are input ends, or all output ends. A 'call return path' may be implemented in a wide variety of ways: tail calls as gotos, continuation passing styles, pipelines, even physical hardware. When I say "call return path", I'm not referring to any call return implementation so much the simple dataflow path it represents. In a pure style, all effects are modeled on this path as values. Even something simple like state is modeled by including a representation for the 'next' state among the return values.. Pure data flow can represent control flow without loss of expressiveness or generality. For example, by expressing a conditional result, you can know the condition is computed and observed before the result. Further, in absence of side effects, order of evaluation is not relevant outside of performance considerations. (Consequently, controlling evaluation order is a convenient target for performance annotations in pure languages - laziness, parallelism, sequencing.) AFAICT, you seem to be assessing pure FP as "bad" under a lens that doesn't apply. The whole "reads, acts, reads" loop and "action between reads" discussion is only sensible in a context where you have side effects, actions outside of returning some data. I understand you want to promote Felix-like fibers, but misrepresenting the alternatives isn't the right way to go about doing so. with fibres, there IS explicit communication The presence of explicit communication does not imply there is no implicit or aliased communication. If you model fibres in a purely functional system, you'll make explicit all the communications involved. Primarily, this would require making explicit the communication with 'scheduler'. For example, a fibre awaiting input on a given pin might be modeled by a value of form: `(In pinId, data → fibre')` where `fibre'` represents the state for the fibre after reading. I'm confused. You're saying a call return path can be "implemented in a number of ways" and say you're not interested in that but in the simple data flow it represents. But channel I/O is unlike function calls. With functions you send an argument along with control, and get back a result with control. It's a master/slave (or client/server) system. With channels, you never get back a result. It's not functional. It's procedural. Meaning, the computational unit is a continuation. Synchronous channels and fibres are a special case of CSP (basically CSP without concurrency). In which I see no lambdas floating about. And so talk of "side effects" is in some sense insane. Procedures have effects. They're not "side effects". Side effects are evil things that confuse functions. Fibres aren't functions. Procedures sequence effects. That's what they're FOR. You do get the idea of duality? I say FP is incomplete, not bad! It is not symmetrical. A good PL must be symmetrical. You have to have peer/peer operations. Functions are slaves so they are not enough. (I'm not against functions!) With functions you send an argument along with control, and get back a result with control. It's a master/slave (or client/server) system. In the presence of parallel evaluation, call by need, etc.. the idea of control flow doesn't really fit. Instead you might immediately get back a placeholder for a 'future' result, whose computed value you may later wait upon when you need to observe it. This doesn't change the dataflow, however. talk of "side effects" is in some sense insane. Procedures have effects. They're not "side effects". Side effects are evil things The phrase "side effects" in computation doesn't mean the same thing as "side effects" in medicine. It isn't about 'intended' vs. 'unintended' effects. I like to think of it this way: if I draw a diagram representing a computation, I might represent a dataflow or a control flow or a state machine. For many programs, I will still have state or communication effects that do not fit within the framework of the chart and instead are annotated to the side of it. Hence, "side" effects. I would not call side effects 'evil'. (Moral capacity for evil seems to be well beyond any computing primitives.) But regardless of whether the side effects are intended or not, obvious or hidden, they can greatly hinder reasoning and reusability and a number of other nice things. In context of your fibres, you might model your channel-based communications as a dataflow (if it's simple enough). But you'll still have plenty of effects outside this flow, e.g. to integrate your sources and sinks. Those are side-effects. You have to have peer/peer operations. And FP can 'have' them. Via modeling. The phrase "side effects" in computation doesn't mean the same thing as "side effects" in medicine. It isn't about 'intended' vs. 'unintended' effects. On consideration, I don't altogether agree. There really is a normative implication in the computational terminology "side effects". The terminology is based on a normative assumption that certain kinds of structure are the primary way things should be understood, and things that don't fit that model are therefore "to the side". It's remarkably easy to decide to look at the world in a certain way and then become gradually so acclimated to it that you're no longer able to see anything peculiar about your perspective on things, and start to think your perspective is obviously the most natural. I recall, once upon a time, coming across remarks by someone who had become so acclimated to W-grammars that they seemed genuinely baffled why anyone would think W-grammars difficult to work with. IMO, the name 'functional programming' really puts to much emphasis on functions, when the more important idea is focusing on immutable values. Functions are certainly important because parameterization is fundamental, and a function is just a parameterized value. But on the other hand it's not so important (IMO) that every value be defined in terms of functions. You can take a value-oriented approach to procedures without representing them as functions. Similarly concurrent procedures can be modeled as values that produce one of a number of possible outcomes. Is that really the case? If you program only with immutable values, all your code will have side-effects, namely out-of-memory due to exhaustion of stack or heap space. With procedures that return results by mutable reference you can have 'pure' side-effect free code that cannot fail at runtime. For me the important property is 'regularity' that is call the procedure or function with the same arguments, and you get the same results. The calling convention by which results are returned should not matter. Input arguments can be copied or passed as immutable reference, in/out arguments as mutable references, and out arguments as uninitialised mutable references, as long as you get the same result for the same input. If you program only with immutable values, all your code will have side-effects, namely out-of-memory due to exhaustion of stack or heap space. That's simply untrue. First, 'immutable value' doesn't mean the memory for representation of that value cannot be recycled, whether by GC or update-in-place when we know the last reference to a value's representation in memory has been lost. Second, bounded memory is a logical property of programs or algorithms. It isn't really affected by the whole GC vs. manual memory thing. GC bounds generally won't be as tight, as some allocation buffer is needed for GC efficiency. But it's still bounded. For example, if you can bound 'live' data to 100MB, then a Cheney collector with 600MB address space can trivially make a hard real-time guarantee of 66% recovery of memory on every pass, and 200MB of allocation 'work' per pass (and zero risk of memory fragmentation). I think it's clear. Consider the machine code for a function that adds two values. If the arguments are immutable the function must allocate space for the return value. If there is no memory left it will have to fail. I don't see your argument countering this. Consider an interrupt service routine that must not fail. If we pre-allocate the space for the arguments, return values, and working space and pass this into the routine by reference then we are safe. This can only be done with mutable references. Your argument becomes circular upon the phrase: "if there is no memory left". Yes, if we're out of memory, we're out of memory. While circular arguments are certainly 'clear', they're also pointless. Adding two numbers only requires space for three numbers. Thus, we can bound how much memory is required: three number slots. If you want, you can allocate the third slot ahead of time and pass it to the machine code for 'add'. (That's a common case for return values anyway.) If not, you can allocate the third slot as needed. The bound doesn't change either way. If you have ISRs with bounded memory, you can include the worst-case for ISRs with the program's memory bound. You may preallocate space for the ISR activation records, or not, either way won't change the bound. So long as we have bounded memory requirements - whether it's three fixed-width numbers or three hundred megabytes - we can simply provide that much memory and henceforth make a strong guarantee against out-of-memory errors. An implementation language might make a difference for space efficiency (e.g. 200MB vs. 300MB for a program) and in some contexts that matters. But language, even use of mutable references, won't change whether an algorithm or program is fundamentally bounded space or not. Your belief that "this can only be done with mutable references" is simply wrong. Maybe you should take a look at the work on statically allocated systems by Mycroft and Sharp, and their functional language in particular to get a better grasp on the nature of bounded memory and how the whole 'immutable value' thing is irrelevant. That's an interesting paper, however, your argument about bounds is also circular. You are saying if there is enough memory you don't have to worry (because there is enough memory). This neglects multi-processing systems where more than one program is running at once. Another program making similar bounds assumptions may have just used all the free memory. So we are looking for the guarantee that a block of code does not heap allocate, or if we want stronger guarantees does not stack allocate, as that is the only guarantee in a multi-processing system that can prevent an out-of-memory condition in a block of code (with interrupts we may not know how much stack is left, and need to avoid a double bus fault). So I think we can agree that the only way to prevent this is to pre-allocate the storage needed before the critical section. So you have to pre allocate mutable storage for the results and intermediate values, and you still have to pass a mutable reference to the memory into the function that is doing the work. The version is very different from what I responded to above. It isn't a duplicate. Edit: And now I'm also annoyed with whomever deleted my other response. My argument about bounds isn't equivalent to "if there is enough memory, don't worry". There are plenty of computations that DON'T have bounded memory requirements, but for which you might have enough memory in practice. For the class of bounded memory computations, we can prevent "out of memory". For computations that we cannot place an upper bound on memory use, we generally cannot prevent "out of memory". Mutable refs don't make a relevant difference to determining which class a computation is in. Multi-processing doesn't change this. (Just allocate and memlock a sufficient arena up front, e.g. as a runtime heap configuration option. Or just control the set of processes on your system.) Efficiency/waste doesn't matter in context of this specific issue, either, so long as it's bounded (though, memory fragmentation can be unbounded). Your assumption that you need to prevent allocation is wrong - to prevent "out of memory" it is sufficient that the allocation succeed. Your repeated attentions to interrupts and such seems irrelevant to the general case. Whether or not you agree or even understand, I'm done arguing for now. I edited my response as I wanted to keep more on the topic of this sub-thread, and not introduce distractions. Due to an error in LtU earlier versions of my post were left behind, however I don't have permission to delete anything. I apologise for mentioning interrupts I don't think it affects the main argument, and it is distracting from the key points. I agree with this statement 'For computations that we cannot place an upper bound on memory use, we generally cannot prevent "out of memory"'. So the first requirement is that pure code must have bounded memory use. I agree with this statement too "to prevent "out of memory" it is sufficient that the allocation succeed." However you cannot guarantee that the allocation will succeed. There may be sufficient memory when you start the program, but some other process may do a large allocation meaning that the program can fail in the middle when it tries to allocate. This is clearly a side-effect, and as the memory allocation can always fail (which is a side effect) then pure code must not allocate. Its that simple (and the functional language you linked to does exactly that). If memory allocation could never fail then 'malloc' would not ever return a null. So it is clear the second requirement is that pure code must not allocate. Put another way, memory-allocation is a side effect. You could argue this another way, in that measurable free memory is the side effect. So if a function allocates memory and we can measure memory then it is 'leaking' information be the side-effect of changing the amount of free memory. So the final step is purely one of logic. If pure code has no side-effects, then pure code must use bounded memory and not allocate. If a block of pure code cannot allocate then it must be passed a reference for is working space and its results, and by necessity this reference must be to mutable memory, or the pure function will not be able to store its intermediate values or results at all. When you refer to pre-allocating an 'Arena' you seem to be admitting as much? How can you pass the arena to a function without mutable reference? The result of a pure function must only depend on the values of its arguments, so if we do not pass the arena by mutable reference, we have no way of accessing the arena from within the pure function. Evaluation of pure code always has side-effects. It consumes space, takes time and energy and generates heat during evaluation, etc.. Potential for allocation failure is not too different from failure on a time quota, battery failure, CPU temp alarm, nor from an impatient human using Ctrl+C to kill an evaluation that takes too long. But pure code does not express or observe these physical computation side effects. This is an important difference from effectful code, where something like printing to console is an essential (and generally explicit) part of the program's behavior. Elimination of evaluation effects is NOT generally considered a prerequisite for purity of 'the code' being evaluated. Though such effects do limit the scope of equational reasoning. We reason about equivalence between values or behaviors of expressions as observable within the program, not equivalence in heat profile. (While 'purity' is somewhat informally defined, the simple laws for local reasoning is why we care about it. One could formally define purity in terms of such laws.) The arena I mentioned above can be configurably allocated by the runtime, which subsequently allocates from the arena. You seem to be assuming that runtime allocation is subject to the whims of the OS, and hence affected by multi-processing. But this isn't always the case. Even 'malloc' can work from preallocated arenas if you choose to implement it that way. In any case, I wasn't implying the arena needs be exposed as a first class object within the program. If code has side-effects it is not pure. So I guess we have to stop being black and white, and admit that no code is ever pure. I guess we need to talk about more or less pure. So code that does not have a memory-allocation side-effect is more pure than code which has such a side-effect (if all other side-effects are the same). If the arena is not a first class object then the result of the function is depending on something that is not an argument, and that doesn't seem functional at all. I guess you could consider the arena an implicit reference to mutable memory? Its still a reference to mutable memory whether implicit or explicit. If a function fails, e.g. due to exhausting a time or space quota, you don't get a different result. You just don't get a result. The result of a pure function does not depend on anything but the arguments. But whether you manage to compute the result ultimately depends on a mechanical, physical computation process with all that entails. If you argued 'bounded memory' computations to be more pure in some useful sense, controlling against a particular divergence 'effect', I could agree with that. But since you insist on 'does not use allocation' as your metric, I instead just think you're confusing essential semantic properties with specific implementation details. Surely failure is a different result? If I try and add 3 and 4, and get "out of memory exception" instead of "7" it is a very different outcome. I don't think out of memory is a specific implementation detail. Infact I think "implementation" is part of the problem. You don't implement a function, a function is what it is. You can change it I to a different function, but then it's a different function. This is what category theory says, you have objects and morphisms (values and functions) and you can have functors that map those to objects and morphisms in another category. So there is a category of "computer programs" which has functions and those have to deal with side effects like memory use. You are working in the category of "hypothetical programs" or something like that. Now whist you could automate the mapping, the problem is you cannot specify what to do in the case of failure. In the category of hypothetical programs memory cannot be exhausted, so how can you say how to recover from such a condition? Personally I want to write computer programs, that run well on computers, and can cope with the full range of behaviours in the category of "computer programs". Purity would seem to be those functions that can be mapped from the category of "hypothetical programs" to the category of "computer programs" with no change in behaviour. So a function that cannot run out of memory (as it is passed a mutable reference for its results) is more pure than one which allocates, as it is changed less by the functor (no allocations need to be inserted by the functor). Surely failure is a different result? If I try and add 3 and 4, and get "out of memory exception" instead of "7" it is a very different outcome. Calling that outcome a result of the `(3 + 4)` expression would be misleading. E.g. we don't evaluate `(6 * (3 + 4))` to `(6 * Exception:out-of-memory)`. Further, even attributing an out of memory condition to a specific sub-computation is incorrect. Rather like attributing the camel's broken back to the final straw. I don't think out of memory is a specific implementation detail. To clarify, it's your specific approach of avoiding an out-of-memory condition BY MEANS OF "not allocating" that I call an implementation detail. You don't implement a function, a function is what it is. There are many ways to 'express' any given function. Even something trivial like the identity function on integers: λx.x λx.((λx.x) x) λx.((x * 1) + 0) λx.((x + 1) - 1) λx.if (x == 1) then 1 else x etc.. I believe a specific expression of a function can reasonably be described as an 'implementation' for that function. Purity would seem to be those functions that can be mapped from the category of "hypothetical programs" to the category of "computer programs" with no change in behaviour. That is not how functional programmers define purity. Also, it seems you're attempting to re-define "computer programs" to fit your argument and agenda. I can't be bothered to argue definitions with you. I want to write computer programs, that run well on computers, and can cope with the full range of behaviours in the category of "computer programs". For effectful programs, non-localized errors like exhausting a time or space quota generally do not admit reasonable coping behavior. If the quota can be localized to a specific subprogram, that can help, but even then one must be concerned about incomplete interactions with other subprograms through any shared state or environment. Coping in the absence of effects is relatively straightforward. Provide more resources (or optimize code) and recompute. Cache/snapshot long-running computations to continue them more efficiently. Etc.. But this does come at the cost of an indirection, since we cannot directly express the coping within the code. I am not inclined to assume either approach is superior to the other. But I personally enjoy not having to write bunches of code outside the happy path to deal with potential non-local errors in my functional programming. In Haskell you can handle the exception by performing the computation in the error monad. Then you really do have "6 * OOM = OOM". So your reductio ad absurdum argument fails, because it is not an absurd thing to do at all. For your definitions of "identity" I would say you have many different functions. You are relying on the data type being an integer ring, there are types for which these are not identities, for example the type of negative numbers. Only the first function is identity for all types. Therefore these are different functions. I think I am providing clarity of definition in the context of category theory. What well defined definition of purity would you give? Using a common definition: A pure function is a function where the return value is only determined by its input values, without observable side effects. In Haskell you can handle the exception by performing the computation in the error monad. Then you really do have "6 * OOM = OOM". Nope. Potentially excepting the `IO` monad (which is able to reflect on the runtime), you cannot catch an 'out of memory' error in an error monad. there are types for which these are not identities I did specify "identity function on integers". Noting that some expressions of that function might better generalize to other data types is irrelevant. I could just as easily have made my point using multiple expressions of Fibonacci function or something else with obviously specific data types. I would say you have many different functions. In context of functional programming, the word 'function' describes the more or less mathematical mapping from a domain of values to a codomain. There are many ways to represent such a mapping, and hence to express a function. If it is your goal for people to misunderstand, you are of course free to use 'function' to mean whatever you want. So as I can observe free memory, that is an observable side effect, therefore any function that allocates is not pure. I wouldn't be surprised if, on occasion, mathematicians have argued that mathematics is impure because mathematicians need to eat and poop and write on dead trees and so on. Purely functional programming can only ever be as 'pure' as mathematics. I think the standard response is to clarify a distinction between the math and the physical/social/economic process of computation. The math is pure because it does not observe or interact with the world. There is no "out of dead trees" or "too hungry, gone home" exception within mathematical expressions. Likewise, a runtime's "out of memory" exception is not properly part of our purely functional program. I did touch on this distinction earlier. In any case, I made some effort to clarify my terminology. But it seems to me that this has only lead to arguing about terminology. At this point I'm just calling our discussion a wasted effort. Good luck with your project. Yes, it seems you don't even agree with the standard definition of 'Pure', so there is no point in continuing. Your point about mathematics is "pointless" as all mathematical functions are pure, so why even bother having a definition. The same function can be pure in the category of mathematical functions which are all pure and have no side effects by your own explanation above, or can be impure in the category of computer programs. The problem is you are arbitrarily shifting to the category of mathematical functions when the function is being interpreted by a computer and hence in the category of computer programs. So as I can observe free memory, that is an observable side effect Observing the free memory is the effectful function because it's non-deterministic. Allocating memory in languages with GC is not effectful. Allocating is only an effect in languages which aim to explicitly track resources. Similarly, observing the clock is a non-deterministic/effectful function, even though using CPU time to execute code is not an effect. It dont think something is a side effect only if you can observe it in the language itself. In any case you can observe memory by having a function that uses more and more memory until it is exhausted, and you can do this differentially, with the function whose memory use you want to observe included or not. Effectively this is the programming equivalent if the philosophical question "does a tree falling make any sound even if there us nobody there to hear it". Also observation is the opposite of an effect. An effect is an output from a function, not an input. In any case you can observe memory by having a function that uses more and more memory until it is exhausted Except you can't observe this within the program because it aborts with an OOM error, so the side-effect doesn't exist as far as the program is concerned. Only in languages in which you can recover from this error might this be a meaningful effect. Exactly, it's the non-deterministic output of a function. An aliased mutable cell can change at any point, making the getter non-deterministic. You've long advocated for local mutable variables, but since those mutations aren't visible to callers or callees, there should be no effect annotation on the function signature, so it's pure. Effects must be observable to be relevant. If all effects are encapsulated in a way that isn't observable, then your program is pure. What other possible meaning could we ascribe to a program in Haskell that runs on imperative hardware? Clearly the runtime performs all sorts of effects, but the effects are not observable to Haskell programs, so Haskell programs are pure (modulo modelling effects via monads of course). Effectively this is the programming equivalent if the philosophical question "does a tree falling make any sound even if there us nobody there to hear it". No one disputes that it makes a sound, just like no one disputes that mutation is an effect, but the only relevant question is whether anyone sees the effect (or hears the sound). If no one will ever see the effect, then it's indistinguishable from a pure computation that produced the same result, and so you might as well treat is as pure. e.g. "we programmers" tend to be able to not think too often about things like cpu cache, memory access patterns, tcp/ip flow control and sliding window retries, tunneling of electrons in gallium arsenide, how much our computer is heating up the world and advancing the heat death of the universe, on-cpu reordering of instructions, maintenance backdoors on our cpus that give other's underlying access and control of what we thought was "ours", how many trees it took to print out that gmail note, how many photons it took to print out that gmail note, etc. by which i am agreeing in that if it isn't something we can or actually bother to really observe, then at some level we are saying it doesn't matter. or we are desperately trying to assume we can say it doesn't matter. Then the Ariane rocket explodes because an error in a pure function causes bad data to be fed into the guidance computer because everyone forgot about side effects. The large fireball would seem to be easily observable, despite protestations that the language does not allow side effects. (Edit: this isn't quite what happened, but its similar, and I am sure you get my point). Who or what is the "Observer"? If I run a Haskell program and it crashes because it runs out of memory, I can easily observe that side effect. Other programs running on the same computer can observe the side-effect. Like the tree-falling, it still happens whether Haskell acknowledges or not. There's a reason why our axioms for the real numbers don't attempt to model "calculator out of memory". It would be absurd to insist that all rocket scientists use some updated math that accounted for the possibility of overflow. It's a similarly bad idea to code in a style that requires attention to memory concerns in every line of code. This discussion is evidently at the boundary where functional programming meets error-handling. But error handling seems to be a yawning gap in our ability to express programs. I recall a conference keynote talk years back where the speaker (best guess, Kiczales) said the vision inspiring AOP was about how much more cleanly an algorithm could be described if only you could separate out the error handling so you didn't have to muddy the central description of the algorithm with it; the nowhere that AOP has gone seems a commentary on that. I tangled with error-handling myself when I devised guarded continuations for Kernel, inspired by facets of Java exception handling and Scheme continuations — and the lesson I took away from the experience was that we don't have a clue how to handle errors. Actually l, I think that is exactly what they should do. For example Rust accounts for overflow, and you have to use 'wrapping' operators (which are not the normal mathematical symbols) if you want to allow overflow/underflow. Then the Ariane rocket explodes because an error in a pure function causes bad data to be fed into the guidance computer because everyone forgot about side effects. Type soundness for a type system ensures that an expression returns the correct type, or it diverges. If you agree that type soundness is useful despite admitting divergence, I don't see how non-observability of mostly benign effects is much different. Certainly high assurance domains may require tracking and controlling more effects, like overflows and bound checks, but that doesn't mean ignoring effects is necessarily wrong for general software. This misses the point, which was that the side effects are observable, by other programs, or the user of the computer. Your point seems to be the user may not care about failure? This seems an odd position to take? I could understand an engineering argument (the cost to fix the bugs is greater than the cost of failure). My point was that a pure function cannot fail, as failure is an observable (by the user or other programs) side effect (for example in maths itself functions do not fail). So any function that can fail is not pure. I think a computer program cannot ever be a pure function, it can just be more or less pure than some other computer program. Edit: Trying to summarise, I don't agree that somehow the implementation of a function is separable from the function itself. Addition is a function, it has certain rules, and is a pure function. If a language has an approximation to addition (for example it may sometimes fail due to out-of-memory) it is neither pure nor addition, but a useful approximation of addition. It is however still a function, just a different one from the mathematical definition of 'addition'. To pretend that this 'different' function actually is addition within certain limitations seems reasonable, but to call it a pure function seems to be claiming too much. Just because you pretend it is addition when reading the program code, does not change the fact that it is not addition, and it can fail. Edit2: You could think of it like this? What is the specification of the programming language? If the language specification does not allow for things to fail, then I guess you could consider the addition function pure, but this language specification could not be implemented on any real computer in the universe ever. It's not just a limitation of current technology, an infinite computer is impossible. If on the other hand the language specification deals with the realities of computation then addition cannot be pure and is only an approximation of mathematical addition. If the language specification does not allow for things to fail, then I guess you could consider the addition function pure, but this language specification could not be implemented on any real computer in the universe ever. Right, and everyone knows this. Without explicit resource tracking, treating arbitrary precision integers as proper integers is perfectly sensible even if some programs fail due to resource constraints. The equational reasoning we expect of "pure" functions holds, modulo resource constraints, but "modulo resource constraints" is a caveat that's understood to apply to every physical incarnation of abstract computing. Languages that don't track resources then require empirical validation for every application if failure tolerance must be high, but this will probably be true anyway, even for programs written with theorem provers. If your language has an abstraction for separate tasks that can fail (like concurrent futures), then you can model purity failures of those tasks and recover via fail-fast techniques, but that's fairly coarse-grained failure handling. "Pure" functions that have such failure modes can still be treated as pure within that task though. I'm not sure what better balance you think is easily achievable. Annotating most functions with allocation effects is just line noise for probably 99.9% of programs in existence. The type and effects research has concluded that you can't automatically infer optimal resource allocation (see section 6), so what better balance do you think is achievable? I was really trying to point out that pure computer programs don't exist and that functions that return results by mutable references can be considered purer than those that return them by value. I think the argument that you cannot observe the out of memory condition is wrong, as it mistakes the language itself for the observer. A language cannot observe anything. My point about the Ariane rocket is that the explosion is clearly observable whether the language spec allows for out-of-memory or not. I don't see how any argument that a function is pure because 'something' cannot observe the error can be correct, because 'something else' can still observe it. As to what I think a solution looks like, I think resource allocation should be explicit, or predictably implicit (like stack allocation), and that effects can be inferred. If you read above I pointed out that you could take a simple imperative language like 'C' and give all the functions the appropriate monadic types, and obviously expressions could be given functional types (although it would be better to even have addition in an 'overflow' monad, and allocation in a 'alloc' monad). Despite this language effectively being imperative, what you would end up with would be as purely functional as Haskell. After the language has been type checked, you could compile in a similar way to 'gcc', thus getting all the performance of 'C'. Rust gets close to this, but does not have any effect control. Edit: This is also an answer to the original question, the ability to get the best of both worlds, imperative performance, readability and understandability with functional safety, aliasing and effect control is why people should be interested in type theory, category theory and logic. Duplicate. I am trying out NixOS for fun and learning. What is the very first serious UX problem I encounter? Yeah, running out of memory. Ha hah! You can't do that in Rust, having a mutable reference imposes exclusive access to the referenced object. You can have many immutable references though. Rust has statements and mutation. It has for and while loops. Is Rust imperative? By your definition it is not. By the classical definition (imperative = a command or a sequence of commands) it is. Rust still has aliasing of state, e.g. via the Cell (edit: oops! that should be Mutex/RwLock) types. The fact that you must temporarily obtain exclusive write access is not relevant. Additionally, like most imperative languages, rust has plenty of implicit aliasing of state through external resources (like the filesystem). With imperative code, an infinite loop can be productive via manipulations of aliased state. Hence one might say a loop is a sequence of 'commands' affecting an external environment. For and while loops are easy to model in purely functional languages. However, one can't use them outside of local manipulations of data. E.g. for 'while : (s->bool) -> (s->s) -> s -> s' we can pass in a whole World as 's' but we still can't do anything but eventually return our updated World. Of course, monadic variants of loops do include ability to return to caller to produce intermediate outputs or await some inputs, so can model imperative code. If Rust removed aliasing of state, then I would not call it imperative. It would become a purely functional language. Albeit, one with a lot of support for affine (or uniqueness) types to support efficient in place mutation. Rust does not allow aliasing of state as far as I can see. Only one mutable reference can be held anywhere, so if a function takes a mutable reference as an argument you are guaranteed only local changes. Yes Cell types exist to allow runtime exclusive access, but I am not sure how this differs from say a mutable reference in Rust. Without Cells you cannot create graphs, so the normal references only allow the creation of DAGs, that seems more "functional" than references in many functional languages. Is ML a functional language? ML allows side effects anywhere in functions? While it is true that Rust only allows one 'mut' reference to data to exist at a given time, it is possible in Rust to alias shared data then acquire a 'mut' reference temporarily when one needs it. This can be expressed, for example, through use of locks. By use of locks, multiple threads may both reference the data and modify it statefully in a manner observable to the other threads. Consequently, you have stateful aliasing. I'm not a rust programmer. It seems I found `Cell` when what I was looking for was `RwLock<T>` or `Mutex<T>`. Regardless, I had read enough about rust to know that shared memory can be directly modeled wherever you want it. Similarly, actors model has aliasing (two actors share a reference to a third). Actors model has state (an actor may behave differently based on past messages). These two conditions may coexist for a single actor. Hence actors model has stateful aliasing. The fact that each message is handled exclusively is irrelevant. The fact that you don't have direct access to the aliased actor's state is irrelevant. I have been using 'functional' to mean 'purely functional' for this discussion. ML is certainly not a purely functional language. I think even Haskell can have aliased mutability. Take a function that accepts two state monads and does something like copy the contents of the fist to the second reversing the order. Now create a single state and pass is as both arguments to the reverse function. I think Haskell will allow this, and go wrong. Rust will not allow this whether a plain reference (statically checked for a single mutable reference), or a cell (dynamically checked for a single mutable reference). Note that a single mutable reference means no immutable references can be held at the same time, it is totally exclusive. Here's an example of Haskell going wrong due to aliasing of mutable data: import Control.Monad.ST import qualified Data.Vector.Mutable as VM rev :: VM.MVector s Int -> VM.MVector s Int -> ST s () rev u v = do let l = min (VM.length u) (VM.length v) in rev' l l return () where rev' i l | i < 1 = return () rev' i l | i > 0 = do x <- VM.read u (i - 1) VM.write v (l - i) x rev' (i - 1) l test1 :: ST s String test1 = do u <- VM.new 3 VM.write u 0 1 VM.write u 1 2 VM.write u 2 3 rev u u a <- VM.read u 0 b <- VM.read u 1 c <- VM.read u 2 return $ show a ++ "," ++ show b ++ "," ++ show c test :: String test = runST test1 Which outputs: "3,2,3" So due to aliasing the 'rev' reverse function has gone wrong. This cannot happen in Rust, as to pass two mutable references to 'u' into 'rev' would not be allowed. As I stated above, "FP can, of course, model imperative aliasing. But must do so explicitly, e.g. using a reference model within a state monad." Use of the ST monad is one such scenario. Rust uses 'ownership' types to constrain aliasing by default, but also supports use of aliasing. You could model the above scenario in Rust. You'd need to pass in a pair of `Mutex<Vector>`s instead of a `mut` reference. And you'd grab the mutex independently for each read and update. This is unlikely to happen by accident if you're working directly with mutexes. OTOH, it might happen by accident if you first wrap your `Mutex<Vector>` behind a `SharedVector` class so you aren't wrestling with all the mutex line noise. Rust's ownership types are a variant of substructural type. In particular, they are related to the `affine` type which prevents replication. Support for substructural types is a more or less orthogonal feature to purity or paradigm. I know of several pure languages that have used them (e.g. Mercury, Clean, the DDC Haskell dialect) and I also know of several imperative languages (e.g. Rust, ATS, and Plaid). Rust is perhaps the first language to bring this feature under the lens of mainstream developers, which I find encouraging. (I am fond of substructural types.) Anyhow, it is true that ownership types enable Rust to constrain code aliasing of references in a manner that (normal) Haskell cannot. Haskell allows `∀v. v→(v,v)` as a function, and hence cannot restrict aliasing of references upon modeling references. Perhaps you would be happier if I said that Rust makes aliasing explicit, so you have to choose the datatype to enable this? Using a 'Cell' is not the normal way to pass a reference in Rust. So to take your statement: "FP can, of course, model imperative aliasing. But must do so explicitly, e.g. using a reference model within a state monad". We can say the same about Rust, it does not normally allow mutable aliasing, but it can model it explicitly, by using a Cell. Due to strong typing, you cannot pass a Cell into a function that does not expect one, nor can you return one where it is not expected. This seems as strong a restriction as a reference in a monad to me. Note the Haskell example above is using the pure functional 'ST' monad, so the whole thing us pure and does not need to be in the IO monad. The result of runST is not in a monad. I'd say that Rust does a lot to discourage aliasing. It's certainly not on the `path of least resistance`. Hence, it's a lot less likely that a Rust programmer is going to make aliasing-related errors than would a C programmer. This is a good thing. OTOH, nothing prevents a Rust developer from modeling shared mutable maps, multi-writer channels, etc.. Aliasing can quickly become implicit if anyone bothers to write libraries that make it so. The "you cannot pass a Cell into a function that does not expect one" argument seems weak in the presence of traits, trait objects, implementation hiding, etc.. Regardless, it isn't nearly as strong a restriction as using a reference within a monad. Aliasing within a monad is limited to the scope of the monadic effects interpreter (e.g. a `run` function), and is represented in the type of the computation rather than the available values. As someone who has programmed both Haskell and Rust, it seems Rust has better control over aliasing than Haskell. You really cannot subvert Rust's aliasing control in the way that you seem to think. Aliasing cannot become implicit because it always requires a different kind of reference, and even then it is dynamically checked via a mutex. For example a rust function like "fn f(&mut x) -> int32" cannot be passed a 'Cell' so within the function you know that 'x' cannot be aliased. Yes you probably could use 'unsafe' code to subvert this, but Haskell has 'unsafePerformIO' as well, so I see no practical difference. By your definition Rust would seem to be a functional language as it does not suffer from the aliasing problems of imperative languages (this is actually one of the major design features of Rust, aliasing safety), and you should be happy about that because it would contradict my original point. If Rust is a functional language, it shows how functional languages can match imperative language performance. Putting that aside, what Rust lacks that Haskell has is a split between pure and impure functions. But what is a pure function. Haskell pure code can fail with out-of-memory errors at runtime, so it is not really pure at all. I think you have to look at this as shades of grey, not black and white. So personally I would add an effect system to Rust (actually it used to have one, but they abandoned it). Really the difference is in the type-system, you could keep the Rust compiler working exactly as it does now, producing efficient 'C' like code, but by adding monadic effects to the type system, you would have the same degree of control as Haskell. code using monadic effects. Maybe monads are not necessary either and simpler effect system would be better. I think you're underestimating Rust's expressiveness. Given you didn't even seem to be aware of mutex before today, I have my doubts about the strength of your experience with Rust concurrency. What else might you have missed? (glances at the first page of mpsc documentation). Ah, look, it seems Sender<T> is 'cloneable', enabling multi-writer single-reader channels. Hence, actors model style stateful aliasing is effectively a feature of Rust. Oh, and those atomic types seem to be all about aliasing. Aliasing might need a 'different kind of reference'. But that's still subject to implementation hiding. you probably could use 'unsafe' code to subvert this, but Haskell has 'unsafePerformIO' as well, so I see no practical difference. Use of unsafePerformIO to perform actual IO (as opposed to debugging or performance features) would be a subversion of Haskell's purity. Support for aliasing in Rust, however, does not require subverting any semantics of Rust or its reference model. By your definition Rust would seem to be a functional language as it does not suffer from the aliasing problems of imperative languages Imperative is characterized by aliasing of state. Mitigating the problems of aliasing is admirable. But unless you achieved it by eliminating aliasing of state (with a corresponding loss of expressiveness in the direct style), it's still imperative. And not just local state, either. As I mentioned early on, aliasing through the filesystem or FFI also counts. If Rust is a functional language, it shows how functional languages can match imperative language performance. Rust is not a functional programming language. But consider a hypothetical language, Rust--. Rust-- is just Rust minus stateful aliasing and FFI. No more Mutex. No Channels. Forking a thread and communicating with it would be tweaked, e.g. based on a process functions concept. Etc.. Rust-- would still be high performance - it could even use the Rust compiler. But it is little more expressive than a purely functional computation. Channels normally alias a shared message buffer between a writer and a reader. But you could maybe add them or a variant back in. Carefully. In restricted form. No cloneable sender. No 'try_recv'. Even this highly constrained use of stateful aliasing would increase expressiveness beyond that of direct-style pure functions, to something closer to Oz with its logic variables - single-assignment futures. (You might model channels as an effect, of course.) I think for a lot of the problems you're personally concerned with, Rust-- would probably work fine. But other Rust programmers that use a different subset of Rust's features would be quick to notice the differences and wonder what the hell the Rust-- designer was thinking that made them take away those precious shared mutable bits. effects. I agree with this overall point. Starting with something like Rust and subtracting/controlling the problematic 'effects' would be a simple and effective approach to high performance functional programming. I encourage you to pursue the idea. Okay, this is a good conclusion. I was aware of Cell, and RefCell, but I personally don't use them, as I try to use the static tools (so & and &mut). I am not convinced that the existence of Cell and RefCell is a problem if none can ever be passed to my code or returned from it without my permission (due to type signatures). I think your point is that I could use some code that internally has a Cell or RefCell and does not expose it in its API, and I agree Rust has this problem, but I don't think it causes many issues in practice (so the Rust browser components shipped so far do seem to be free of exploitable bugs). I think there are two solutions to this, one is that code that uses a cell internally needs to be proved safe, rust does this by forcing runtime dynamic checking on the Cell and RefCell, however you can do worse with 'unsafe' code and basically have a plain 'C' pointer. My approach to this would be some kind of proof carrying code that if you can prove the code is safe to the compiler, you should be able to use in 'pure' code. The second as we have discussed is an effect system. Real pure code will look like an imperative procedure where return arguments are passed by mutable reference and it has no local variables, and no division or other operation that can cause a runtime exception, as this will not fail at runtime due to out-of-memory errors etc. I think ATS does a lot of what you're envisioning, e.g. including proof carrying code and types to control aliasing and effects, and might be a closer fit than Rust. It has an atrocious syntax, unfortunately. But I do recommend you experiment with and learn from it. So, what about building a language on serious alias control? Rather than taking Rust's approach of rationalizing C-style semantics, you could view this as starting with a pure-functional/linear typed semantics, and building it into a practical engineering tool. First, distinguish between pure-functional values/functions, and imperative-type resources/operations. (Operations may destructively update resources passed as arguments, but are otherwise composable pure values, like functions). Then, add the default assumption that resources used by a given operation may not alias (unless so specified by the type interface). In most situations, this could be seen as simply systematizing good practice. However, I worry about cases where mutable references really are a natural way to express things... I think it's a fine idea to control aliasing. Substructural types are awesome. Everyone should use them. OTOH, it isn't a new idea. There's a lot of experience with these things going back over 30 years that you can review and learn from. Look at Clean, Mercury, DDC Haskell, Plaid, ATS, etc.. An interesting feature with full substructural types is that you can easily enforce protocols (do X at least once, or at most once, or X before Y). This can be simple stuff like making sure you close your open files. Or it can be sophisticated stuff like multi-step handshakes. Structured programming is a lot less relevant because 'structure' is now represented in a set of available data objects. I admit to frustration in reading this thread. It seems to have started out reaching for big, sweeping ideas, and somehow lost track of them as it degenerated into fine details. As I see it: We live in a world where things actually happen. There's an agenda in play to write programs, to be embedded in this "impure" world, using a "pure" mathematical model where things don't happen. Some people reckon it's inevitably clumsy to describe a changing world using an unchanging model. Other people reckon the elegance of the mathematical model is more valuable than matching the model to the "change" aspect of the world in which the program is embedded. I suppose this could get somewhat subtle, as one considers different consequences of using a pure model to describe a program embedded in (not just interacting with) a changeful world. But still, the moment the big ideas are no longer visible, the details are likely to stray from the point. I appreciate pure FP with awareness of the side effects it does permit. It does permit computations that consume some nonzero amount of time and other resources. It does permit taking on the nondeterministic risk that cosmic rays, language implementation bugs, or interactive debuggers will interfere in the computation. It does permit code snippet A to make use of the implementation details of code snippet A, even though code snippet B has no access to them. In some situations I'm interested in, it's actually pretty interesting to imagine the use of implementation details as a side effect, in which case pure programs are not quite pure enough: With all this in mind, pure FP does permit quite a few things that could be considered side effects. However, for all that it permits, including a limited form of nondeterminism, it manages to keep programs deterministic up to their own implementation details. Determinism makes it easier to talk about two subprograms being "the same" after a refactor. Since a (successful) program deterministically results in a value, we can pretty much treat the value space as the semantics, rather than resorting to some more heavyweight denotational semantics like store-passing style or core dumps. If pure FP is not pure enough for some purpose, that's a good reason to pursue models of computing that are purer in some ways. Maybe they do need to be less pure in other ways, but it's easy to give up too soon, and there seems to be a lot of potential to stay within the bounds. For instance, linear typing's prohibition of aliasing "effects" does nothing to stop us from reading its programs as pure FP programs to discuss their semantics, but it makes it possible to represent first-class outside worlds so that we can do mutation and concurrency without the continuation-passing style of the monadic approach. If a resource-conscious language needs to have mutation, my gut reaction is that the language might be sticking too close to its predecessors. Mutation threatens to sequentialize the programs that heavily use it, and a single act of mutation can generate garbage and do aliasing at the same time. It seems almost antithetical to efficient use of resources; would a resource-conscious language really use it? I don't really know enough to seriously discuss alternatives, but speaking casually, I imagine a system of regions that can toggle between modes: A region can be readable, writable, or a container for a resource-bounded, typed computation in progress. The mode-toggling action itself and any other sychronization between computations would occur in the style of transactional writes. I haven't implemented this, and there really are huge gaps in the design when I try to formalize it, like how much space it takes up to store the transactions before they're processed, or how much scratch area the typechecker needs when we toggle a region from the writable mode to the computation mode. :) This seems a balanced response to me. I would point out that the refactoring comment is not always true, as with lazy languages like Haskell small changes can move you from bounded memory (consuming a stream in bounded finite space) to unbounded (creating an unbounded heap if thunks for later evaluation). Further all programs use mutation. Even the purest functional language I have seen uses a stack, which relies on mutation to work. Languages like Rust avoid aliasing during mutation by using affine types. Would resource conscious languages use mutation? When writing for very small memory use if assembly is still common, and yes use of mutation results in a much smaller program. A single byte can act as an event counter, geo-coordinates get updated in-place by interrupts etc. Pure functional languages model mutation (like the ST monad in Haskell). I see no reason you cannot translate that monadic code into an imperative language like 'C', and then compile it. In which case what advantage do you get from modelling mutation rather than implementing it directly. The difference seems to me to be simply in the type system, where the monad let's you constrain where mutation can happen. Imagine we take 'C' and implement a type system which gives monadic types to impure 'C' programs, and pure types to pure 'C' fragments like expressions. How is this any different from a pure functional language? isn't that what some commercial / ivory tower projects claim to do with regular old C? either statically check extra cruft, or let you add annotations for static checking, or move it into a C+++ with such features, and then compile down to C. e.g. i dunno ATS or something for random example? "simply in the type system, where the monad let's [sic] you constrain where mutation can happen" --> errr, yes, would that not be the whole point of how FPs can suck infinitely less than C?! :-) A state monad can be implemented in various ways under the covers I guess. Anything with a loop can split the available memory in half (2 regions) and then on every loop the current state is passed in readonly and the next state is passed in writeable. At the end of the loop you have your new state; clone and swap back and forth on each loop. No extra allocations happen and nothing gets freed so you avoid spending extra time on memory but you get to do mutation, at least if you e.g. are writing a video game where you decide bduf how many particles maximum you are going to allow but i am probably talking out of my ass. Functional programming is the only reasonable way to make use of scalable multiprocessing, parallel processing, and vector processing. Whatever language we use in the future, multiprocessing, parallel processing, and vector processing are going to continue to scale bigger and bigger and bigger. Therefore I expect that many if not most of the dominant programming languages in another ten years or so will make functional programming easy. I do not claim they're going to be purely functional like Haskell; I claim that they're going to make functional programming easy, like Scheme or Clojure. I once implemented a Pascal-subset compiler using Scheme lisp as the implementation language. Scheme is not purely functional. It can mutate variables. It can do direct I/O. But it's constructed so that ordinarily there's just no need to do those things. I realized after the fact that I hadn't used mutation even once in the whole project, that there were no operations affecting output that were done before the whole input was read, and there was no output that was done except as the last step before program exit. A pure functional program just came about naturally by the interaction of my normal, ordinary straightforward programming style and a language that makes functional programming easy. Screw stateful objects. They are confusing and don't parallelize. Compilers are one of those areas where the program-is-a-function philosophy is an obvious fit. For better or worse, that experience doesn't generalize to problems such as robotics control or multi-player video games. For general systems programming, a functional program must model effects. These effects are modeled explicitly in the path of normal call-return dataflow, rather than to the side of it. Nonetheless, use of effects with incremental computations does introduce challenges for reasoning about whole-program behavior. State isn't really avoided, either. State machines might be modeled with the general form `type M i o = i → (o, M i o)`. Our program functions may fold a very large stream of inputs over time, and understanding that state isn't necessarily easy. type M i o = i → (o, M i o) If FP dominates, it won't be due to avoiding effects or state, but rather due to simplifying and controlling the problems of testing in presence of effects and state, and reducing barriers for reuse of programs in new contexts (e.g. ability to wrap a program that internally uses message passing within an entirely different effects system). Screw stateful objects. They are confusing and don't parallelize. Sure, but traditional bang-on-records-in-place databases parallelize just fine and somehow manage to remain far less confusing than typical ravioli code. Some problems/solutions are more easily modeled imperatively, even parallel ones! Don't conflate "imperative" with the historical failings of languages centered around mutation & global memory pointers. There's a separate argument around whether or not forcing all logically-imperative operations through the monad pinhole is a good idea or not. Hang on there! You mean "at this time its the only well understood way" do you not? And I would question that. The fact is most people doing low level high performance programming use C or Fortran or assembler and do not, in fact, understand FP. Furthermore current FP compilers rely on optimisations such as self-tail-rec which are incompatible with concurrent performance GC due to the need for write barriers (at this time though that seems about to change) You may be right, but it is definitely not well understood. Ocaml, for example, cannot even do pre-emptive multi-tasking at this time. (You can have threads but they interleave via a global lock). Furthermore, for better or worse, CPUs are built for performance of existing languages like C and Java. Ugghh... I do agree however in this day and age any language that does not support the common themes of FP is badly broken: pure functions possible, GC, higher order functions, parametric polymorphism, variant types .. to name a few essentials. +1 to Apple for Swift. Given all the work done on FPLs, it would be mad not to actually USE that research. It just doesn't have to be the end of it. I think the idea that cpus are designed for 'C' and Java is a bit backwards. CPUs are designed to maximise instruction throughput, and ALUs are designed to maximise operations for a given gate count. CPUs for functional language gave been tried before, but the architecture just does not work as well. In the end a CPU operates by mutating memory very quickly. The idea that there is some kind of functional CPU that could be competitive with modern super-scalar out-of-order speculative CPUs seems to be pie in the sky to me. I would be happy to be proved wrong, but my opinion is its not possible due fundamental architectural issues. FP being the only thing that reasonably scales any single process to unspecified numbers of CPUs or cores available isn't just a matter of it being well studied. It's because pure FP can proceed without locking overhead. Nothing that relies on access to variables or objects between unsynchronized processing nodes scales without locking overhead unless all those variables are write-once. In fact I should have said bindings then because they don't vary. Any non-FP thing that parallelizes, parallelizes solely because whatever parts of it are non-FP, are not fighting over variables. Meaning, it's relatively easy to handle a thousand interactive sessions using non-FP threads, where each session has its own set of variables which it doesn't need locks for and doesn't need access to any other session's variables. But if there's any single thing, or any universal realtime-shared things, that all those sessions have to get a lock for and read and write, then there is a scale at which that system breaks. It is simply a fact of physics that locking overhead scales with the square of interprocess bandwidth. So yeah, you can go non-FP at the program's leaf nodes, if there's nothing that has to be shared around and modified by all those leaf nodes. But at some scale, where you have to do anything big that requires lots of theads to access the "same" thing, you have to either accept losses, or go FP. It simply isn't possible to write and scale without limit any huge application with globally shared bindings, unless those bindings are immutable. Databases absolutely push the limit on this just as hard as they possibly can, but it's still true - at some scale either the database program breaks, or you absolutely require the data that the different threads access to be disjoint. The indicia that tell sessions where to find this disjoint data, can be widely shared but the wider they are shared through the distributed application, the more rarely they must be written, or the application melts down at some scale. The core of any app that's big enough, has to use immutable bindings. subjectively agreed, and I feel like the non-ACID distributed data structure stuff is where the future lies. Yes, of course FP can model it, it can model anything (modellable, if that's a word). That isn't the point. You can use Haskell to write a program that "models" any C program. And you can write a C program that "models" any Haskell program: on the latter point one may say, more precisely, Haskell can be "modelled" in x86 assembler, and there's a weird tool that does that, called a compiler. The point is you don't want to. If you want to do something, use a language that is designed to do things .. I hesitate to say "C" but it is a language which emphasises control flow and mutation. If you want to calculate stuff, use an FPL. If you want to do BOTH what do you do? If you use C, you will find functional code hard to write. If you use Haskell you may have a bit of trouble with array modifications, and you'll need a lot of housekeeping crud to model imperative operations. What you want is a language that can do BOTH well, and allow you to "swap" between techniques "seamlessly". The issue is about expressiveness, not capability. Look at Ocaml. It has a functional base but throws in a mutable record field and some mutable data structures in the library. It can do both, but the integration is very bad. If you dare use mutable fields or hashtables your ability to reason about the code with functional arguments is gone. I do understand your opinion on 'doing' vs 'calculating'. I remember expressing a similar opinion on this site not too many years ago, back when I still was trying to grasp FP from a mental framework of imperative experience. But modeling effects is superior in many respects compared to reaching out and just 'doing' effects during computation. Superior for testing, reasoning, reuse, control, security, etc.. Maybe not superior for performance, but maybe not much worse. For example, I might model a program that interacts with a filesystem as producing a series of 'Read Filename (Range)' and 'Write Filename (Range) (Data)' requests (perhaps simpler than we'd really want, but sufficient for discussion). By modeling this explicitly: I can test my program in pure, ad-hoc mockup environments. I can control which effects my program uses. I can wrap my program to compute bytes read and written. I can write a trivial adapter to use a database or web service instead. I could limit my program to use specific files. I do want to model effects in a pure style. Even when my program is mostly expressing effects or awaiting responses rather than calculating. Perhaps especially then. Thus rather than 'switching' styles, I'd be more interested in languages that make it easy to model effects easily, efficiently, transparently, and compositionally. Haskell is not the ideal example here, since the nicer effects models (algebraic effects and handlers, freer monads with extensible effects, etc.) weren't developed until more recently and Haskell is dealing with weight of its opaque IO legacy. FP is only superior for reasoning because that is where the most theoretical research has been done. This is natural due to the connection between mathematics and functional programming. Now you said "I do want to model effects in a pure style." I agree, but FP does not do that. In the Felix system, we have an "Algol like" combination of functional and procedural programming. The functional component by Felix base rules may observe effects but may not cause any (which is not an entirely satisfactory situation). If you want to, say, modify the file system, you can't use a function, you have to use a procedure. Functions may call procedures *provided* their effects are mutations local to the function (i.e. not escaping it). Except for debugging. Yet, ordinary procedures alone are like gotos: they're open ended, they can do have any effects. Felix has an effects management system (in user space only) based on row polymorphism. It's not clear how useful this can be. So we must fix the procedural system. Enter coroutines. Actually fibres. A fibre can be pure or not. The important thing is that you have a unit of modularity with documented effects, and *hopefully* a way of calculating the effect of compositions of fibres. With fibres communicating synchronously using channels, the problem of calculating possible control flows (and thus effects) is basically reduced to calculating ordering of synchronisation events on schannels, which is constrained by the connection topology, so there is a definite model of things to reason about. I can do this for simple models like pipelines. Now I want a more comprehensive theory. Example of reasoning: A fibre reads (on a synchronous channel) a piece of data, modifies a file, reads again. Deduction: the file got changed between two reads. Knowing the effect isn't the issue. The issue is: when did it happen? I have no exact answer but I DO have an approximation. So, I have a TYPE. Give me more! An ordering protocol is a type. To me channels are the important abstraction. I don't see why it matters whether concurrency is achieved by fibres or processes. Haskell's Channels which communicate between processes seem to offer all the language properties you want. Note, I am not saying fibres are a bad idea, I appreciate the performance advantage of a stackless model with systems that process many requests in parallel, but that the programmer model is the same as with processes, except you need to worry about not relinquishing the CPU with fibres. The point of fibres is that they are NOT concurrent. With functions (and traditional procedures) you have a single thread of control and a method of decomposition of code into subroutines activated by a master/slave operation (call/return). Many languages have enhancements because this model is very hard to use: Scheme has call/cc, C++ has exceptions, Felix has non-local gotos. Unfortunately none of these modifications are any good. Fibres are coroutines, and use a peer/peer control exchange, and I claim this enhancement has more promise because it is simple and appears even more fundamental than call/return. The core control flow is given by the branch and link instruction, in which you jump to an address stored in register A, saving the current continuation in B. If you load A with a constant, this is precisely a subroutine call. Return then jumps to B (the continuation) without saving anything (more precisely the continuation stored in A is ignored). So basically C was a design error from the start. The machine it was designed for (PDP-11 basically) had a branch and link but they didn't use it. Function calls (and procedure calls) and both subobtimal concepts. Exchange of control subsumes it. In principle synchronous channel I/O is higher level and more abstract, because a rendezvous does not specify which continuation runs next, but despite the indeterminacy, it does specify exactly *one* of them runs next. My current experiments seem to indicate, paradoxically perhaps, that the indeterminacy is actually essential to reasoning, it actually simplifies things. Anyhow my point is, coroutines provide a way to decompose *sequential* code into smaller units which do not require making arbitrary choices about which code is master and which is slave. Slaves are hard to write. So coroutines are often better than functions. A good example: fold. Folds are easy to write, but the user processing function (the argument) is very hard to write. Control invert that into code that calls an iterator so the user processing is easy to write, and then the iterator (cofold) is hard to write. Write two coroutines connected by a channel, and BOTH parts are masters and so easy to write. Surprisingly, Higher Order Functions are a good example of what's wrong with functional programming. Of course traditional imperative code (eg C++) just has the dual problem instead. Coroutines solve the problem. Ideally, you use functional code when it is convenient, procedural code when that is good, and coroutines when that is the best. Procedures are the dual of functions, but coroutines are self dual. I agree with all your points. I don't like that loops can prevent prevent context switching, and I don't know if there is a solution to this. In some ways the process model, where no memory is shared between processes and all data has to go over channels is cleaner, and can be implemented using fibres without changing the semantics. I think all the above points are true for processes and channels too. I have not read all of skaller's post. (I tend not to be interested in channels per se. I think about messages, streams via pipes or sockets, and cond vars with fibers running in the same local vat. The last must be local, but the other two can also have remote endpoints.) The point of fibres is that they are NOT concurrent. They are not parallel in the sense of running simultaneously on more than one CPU, but they are indeed concurrent in the sense of interleaved execution, if one yields to another before exiting. (We need a better word than concurrent, since it means interleaved, whether or not parallel, and thus conveys no information about parallelism beyond hinting it may be present.) I don't like that loops can prevent prevent context switching, and I don't know if there is a solution to this. You cannot let a fiber loop without yielding longer than it's target fiber timeslice, perhaps approximated by only p partial iterations of N total loop iterations. For performance you want to let a loop run without yielding a short while. But eventually you need to construct a continuation that resumes the loop where where it yields via park, so it can resume later when unparked. Letting a user do that is error prone. So I prefer to have code rewriting do it, at the time continuations are represented. I would annotate a fiber with a profile that indicates how many iterations can go uninterrupted before a yield. In this sense a loop cannot prevent context switching longer than some small time span. (It really only matters in "tight loops" calling no async functions, which would yield anyway on timeslice exhaustion.) Edit: of course, fibers running in another thread can run in parallel, but that is hidden inside the other thread. That just looks like other threads can run in parallel with the thread hosting fibers. Whether they have more fibers inside is irrelevant. I think having the compiler do the transformation into fibres would work for me. In this case the programmer will be using the process model or thread model in the code they see. Personally I think mutable shared memory should be avoided, so I would go for the process model where no memory is shared, and you can only communicate by message passing over pipes/streams/channels. I want tools to offer affordances which let me do things when I want, but catch me breaking rules I adopt (as indicated by things I do in code). So I like immutable data many places, but sometimes I need to instantiate a model of something that has local mutable memory, like cloning a debugged C tool as a lightweight process. There I want mutation. But if that ported code steps on memory others think is immutable, I want it detected. More below. I think having the compiler do the transformation into fibres would work for me. I want a model of lightweight threads (aka fibers) to be first class, so code can know they exist and manipulate them, via grouping and spawning, etc. But I want the compiler to manage the messy details involved in what a fiber actually has to be in the runtime. I want to write code that looks like it runs alone, and looks natural. So I want the compiler to do anything I don't want to see unless I review intermediary forms. One transformation might be to turn it into an actual native thread; here making APIs used compatible is hard without an abstraction that looks the same for fibers and threads, even when there are system calls involved for threads. In this case the programmer will be using the process model or thread model in the code they see. Yes, you want things to look overtly like processes and threads, but presented as abstractions that might be native or lightweight. Personally I think mutable shared memory should be avoided, so I would go for the process model where no memory is shared, I like shared in a process, but normally not shared between (lightweight) processes, unless immutable and therefore not subject to sync issues. As an exception, sometimes you want to model something complex as multiple processes, for organization sake, despite them representing one tightly integrated "program" taken all together. You can think if this as an "app", that could have been just one process, except that would have made things more complex than breaking it up into sub-processes devoted to different things. For example, you might want some of them killable, where others can recover at less cost than restarting the app. Where processes are not part of one app, you want them to interact only in terms of immutable data: messages, streams, etc. and you can only communicate by message passing over pipes/streams/channels. That's the model I like between apps, where an app might be a collection of mutually dependent processes. I like a fiber runtime to allocate large contiguous blocks of memory from the host environment, from which it sub-allocates to meet both runtime and fiber demand. This makes it easier to associate metainfo with every block of memory allocated, such as refcount, generation number, optional checksum, and immutable status. (Ideally, this is somewhere else in the same large contiguous block, not in the same cache line as the usable memory start. It's better for alignment and makes it hard to step on by accident.) When a piece of memory becomes immutable, and marked as such, you can take a checksum then. You would always do this when debugging, but might also do so in release builds if you want a high standard of quality. When you free memory, you verify the checksum is right when it was captured for immutable data. Any time it's wrong you signal "the world is on fire" in a suitable way. I agree that coroutines or fibres can be a useful abstraction. Though, I think it isn't the specific abstraction that matters so much as supporting both 'push' and 'pull' of data. Fibres are pushing data on output channels and pulling it from input channels. But publish/subscribe models, tuple spaces, behavioral programming, etc. offer similar benefits to expressiveness. Such abstractions can be conveniently expressed in FP assuming a lightweight notation for sequencing small step computations (e.g. do-notation or a sugar for continuation passing style). FP is only superior for reasoning because that is where the most theoretical research has been done. I think it's superior for reasoning mostly because it makes explicit a lot of what is implicit in other models. E.g. in actors model, some implicit things include: actor names, messages in flight, routing. To model actors within a functional computation, you would need to represent these things. With your fibres, implicit things include: scheduling, and any effects outside of reading/writing on pins (such as a filesystem interaction). you said "I do want to model effects in a pure style." I agree, but FP does not do that You might take my meaning as more or less equivalent to "model effects in a purely functional style". So pure FP does that pretty much by definition. Though, I'm not totally on board with the 'opaque' effects models (like Haskell's current IO implementation). Opaque should certainly be an option (data hiding is a thing). But transparent values that I can intercept, rewrite, observe, etc.. offer greater utility. ordinary procedures alone are like gotos (Aside) In context of functional languages, I like to think of 'tailcalls' as the equivalent to 'goto'. Better, it's a parameterized goto. :D The issue is: when did it happen? I have no exact answer but I DO have an approximation. I hope you have some luck with that. Consider trying to predict which pins a fiber will next read or write. You might need dependent types in general, but you can probably cover a lot of common cases without dependency. I'd be more interested in languages that make it easy to model effects easily, efficiently, transparently, and compositionally Me too. I do want to model effects in a pure style. We might agree here, but I want to clarify: I don't want to have to model effects in a pure style myself, I want to be able to recover a pure modeling when it is convenient to do so. This turns out to be pretty tricky, but I think quite doable in practice. One challenge with effects is that they have dynamic extent, so if you model them explicitly, you get viral monads in function signatures. If you make effects implicit, then you wind up with accidental effects. It's hard to tell what is an accidental effect because hidden effects are useful. Consider an Eff style effects/handlers model where you have some data that represents an effectual operation and a special form to "raise" that operation for handling. If you have operation Outbound(stdout, "foo") you want to be able to call it Print("foo") and have that implicitly perform Raise(Outbound(stdout, "foo")). You can always do something like CaptureOutput{ ...Print("foo")...} to recover a string, but what you really want is something like captured = CaptureOperation{...Print("foo")...} so that you can reraise that effect: Raise(captured) Being forced to explicitly model everything 100% of the time as data has lots of benefits, but it is very verbose. I want to be able to explicitly model things with effects and recover an implicit, pure model when it suits me. Further, I had a hard time coming up the name "Outbound" for the operation (noun) to differentiate from the function (verb). Names like "Print", "Write", etc don't immediately tell you operation data vs effectful function easily. A more implicit modeling of effects would enable greater economy of taxonomy. I don't have any problem whatsoever with notational sugars or type systems being optimized to keep effects out of one's way during normal programming. Abstraction and composition of effects should certainly be feasible (if not, that's a PL failure). But I don't think of this as "recovering" a pure modeling. From what would I be recovering it? The model was pure all along. hard time coming up the name "Outbound" for the operation (noun) to differentiate from the function (verb). Names like "Print", "Write", etc don't immediately tell you operation data vs effectful function easily. Well, you can always take the Haskell route: capitalized is data, lower case is verb. Or you could take the Forth route and just skip the use of nouns entirely. :D As a Regular Joe day job programmer, I see lots of ways things can go wrong in code. I have only ever more wanted pure functional style over the years, never less. I want all the stuff to be first class and higher order as much as possible. DCC indicated that the explicitness can quickly go wrong. I dunno about ATS, et. al. If there were inference or something, or a way to pull out the big gun tools if/when needed, instead of having them required/on all the time, that'd be cool. I think ATS can do this. The precise typing and proofs are not required. See the original tutorials where you can write things without bothering with proofs. Exactly how seamless this is (migrating from no proofs to adding them to parts of your code) is not clear to me but I asked Hongwei Xi about this and he was quite definite that the intent is to allow using crude types and then refining them. I would rather have a type system based on logic than something ad-hoc and random. At least you can reason about types in languages like Haskell without falling immediately into unsoundness. I agree that the limitations of mathematics should not limit programming, and I tend to favour imperative constructs for their inherant readability and understandability. Having spent some time with both Rust and Python recently, I really miss type signatures in Python, especially for return types when the type is a collection. In Python I have to look at the source file (and which import and where in the filesystem the definition is, is not obvious either) when a simple type signature like: "Dictionary<String, Int> heights = get_people()" would normally avoid the need to even look. I can do without the Category theory, but due to the computational trinity, you can view types as logic or categories. I would like to say I get category theory but every time I try and understand it my large intestine leaps through my neck and tries to strangle my brain. I have no such problems with the logic interpretation. I can only conclude that category theory is the mathematical equivalent to Vogon poetry. Any type system can be understood as a logic. The surprise in Curry-Howard is that basic typing constructions correspond so very closely to familiar basic logical principles. In particular, function application corresponds perfectly to modus ponens: Given an expression with type A->B, and an expression with type A, you can put them together to get an expression with type B. Given a proof that A implies B, and a proof of A, you can put them together to get a proof of B. Despite my criticisms of category theory (and despite my lol at the Vogon reference), I've found that on occasion, looking at ordinary things through the lens of category theory can provide glimpses of beauty that was invisibly there all along. (I feel inspired to write a blog post, if I can find time and somehow overcome my uncertainty over how to generate and embed 3D animations; not everyone could visualize the twisted hourglass of an adjunction with less than a 3D animation.) My problem with category theory is probably one of presentation. It is normally presented in a very abstract way, and I am a kind of 'learn by doing' sort if person. I can re-read the same chapter of a book several times and still not get it. I either need someone to discuss it with (and by that I mean someone I can explain what I think, and have them correct me) or I need to do it (use it in a meaningful context). I think category theory is interesting, but I find logic more intuitive, hence my joke about Vogon poetry (and for and purists out there, it was of course Grunthos the Flatulent's small intestine that saved civilisation by strangling his brain before he could recite his 12 book epic, nothing to do with Vogons, except of course the bad poetry). i think this would be a true contribution to the development of humanity. no joke at all. it would be awesome. I expect my best efforts will fall far short of expectations; but even so it's encouraging to know someone else sees the potential in the idea. As somebody who worked with logical-inference systems and the unification algorithm right out of college, the logic of type systems has always been familiar from that. You know the way horned clauses work in prolog? Where you have something like (parent, ?A, ?B) ^ (male, ?A) :- (father, ?A, ?B) (parent, ?A, ?B) ^ (female, ?B) :- (daughter, ?B, ?A) (parent, ?A, ?B) ^ (parent, ?A, ?C) :- (sibling, ?B, ?C) (sibling, ?A, ?B) :- (sibling, ?B, ?A) (sibling, ?A, ?B) ^ (male, ?A) :- (brother, ?A, ?B) And so on, with the more-or-less obvious meanings. Anyway, the basic Curry-Howard logic seems to me to be exactly the same Prolog-ish unification algorithm, and you could write it in exactly the same way as a production system. (ReturnsType, ?PROCA, ?TYPEA) ^ (Args, ?PROCA, ?B) ^ (IsType, ?B, ?TYPEB) :- (IsType, ?TYPEA, ?PROCA(?TYPEB)) (Arg, +, ?A) :- (IsType, Numeric_Type, ?A) (Returns, +, ?B) :- (IsType, Numeric_Type, ?B) (IsType, Integer_Type, ?A) :- (IsType, Numeric_Type, ?A) (IsType, Float_Type, ?A) :- (Istype, Numeric_Type, ?A) (IsType, Numeric_Type, ?A) ^ (~ IsType, Float_Type, ?A) ^ (~ IsType, Integer_Type, ?A) :- falsum and so on are its basic laws, and all the stuff we did for inference production systems-as-expert-systems back in the day (including hyperoptimizations of implementation like the RETE algorithm and shortcuts like backward-chaining plus forward-chaining to meet in the middle, etc) is applicable to type inference. That which can be deduced about type is simply the transitive closure of all the facts under the set of production rules. The ability to derive a contradiction (or falsum) corresponds to a type error. I can confirm it is the same algorithm, having written a Prolog interpreter and an HM type inferencer. Also interesting is that type classes operate exactly like Horn clauses, although in Haskell they are closest match with no backtracking. Rust traits have backtracking so the type system is effectively an interpreter for the positive subset of pure Prolog. In my language project I am using a Prolog dialect as the type system, so the inference algorithm is written in the embedded Prolog, and it is user extensible. There is no specific mechanism for type classes, they are just Horn clauses with associated code (it's very much a work in progress). Shen has a build in prolog that is used to define new types.
http://lambda-the-ultimate.org/node/5366
CC-MAIN-2018-09
refinedweb
19,512
62.58
03 September 2012 07:24 [Source: ICIS news] By Judith Wang SINGAPORE (ICIS)--Spot propylene (C3) prices in Asia increased to a four-month high, and may continue rising in the coming weeks on the back of higher crude and derivative product values, as well as concerns about tight supply, industry sources said on Monday. On 31 August, propylene prices were assessed at $1,380-1,415/tonne (€1,090-1,118/tonne) CFR (cost and freight) ?xml:namespace> Crude prices at above $90/bbl, accompanied by rising naphtha prices boosted sentiment in the olefins market, buyers and sellers said. Rising prices in downstream derivative products also lent support to propylene prices. Polypropylene (PP) flat yarn values increased by $10-20/tonne week on week to $1,380-1,420/tonne CFR China on 31 August, while propylene oxide (PO) edged up by $20-30/tonne to $1,670-1,750/tonne CFR China over the same period, according to ICIS. “I think propylene will increase in [the] coming weeks as this round [of] price growth [for] downstream products since late July and early August will probably sustain till September, which is usually peak chemical manufacturing season,” said an end-user in south Concerns about a possible tightening of propylene supply may also drive up prices, market sources said. The unit can produce 400,000-450,000 tonnes/year of propylene, which will be supplied to its domestic customers, with any excess supply likely to be exported. “If CPC could not start up its RFCC in October, then the market will [be] tight again as some new downstream plants, including phenol-acetone and oxo-alchohols [units], will start up in October and November in China. By then, the demand for propylene will rise, and prices may increase again,” a trader said. Industry players, however, said that the propylene’s price gains may be limited if actual demand from downstream markets failed to pick up significantly. “Currently, the general demand for PP is not strong enough amid ($1=€0
http://www.icis.com/Articles/2012/09/03/9591950/asia-c3-hits-four-month-high-on-firm-crude-derivatives-prices.html
CC-MAIN-2014-35
refinedweb
338
51.92
Understanding XML and JSON Parsing in iOS Programming One quite common nowadays for them to exchange data with web applications. In such cases, the way that data is expressed may vary, but usually is preferred either the JSON or the XML format. iOS SDK provides classes for handling both of them. For managing JSON data, there is the NSJSONSerialization class. This one allows to easily convert a JSON data into a Foundation object (NSArray, NSDictionary), and the other way round. For parsing XML data, iOS offers the NSXMLParser class, which takes charge of doing all the hard work, and through some useful delegate methods gives us the tools we need for handling each step of the parsing. Focusing a bit on each class separately, there’s not much to say about the NSJSONSerialization class, except for the fact that is very simple and straightforward to be used. There are some simple rules that should follow, but further than that it takes all the hassle away from us when some JSON conversion is needed. In order to convert a JSON value into a Foundation form, it has to be a NSData object. The returned converted object is either an array (NSArray), or a dictionary (NSDictionary). Their contained objects however can be instances of NSString, NSNumber, NSNull, and of course NSArray and NSDictionary. The NSJSONSerialization class provides ways for checking if a JSON data is valid before doing any conversion, so you can use it in order to make sure before performing any conversion. On the other hand now, when you need to turn a Foundation object into JSON, you should have in mind that the produced object is always of NSData type. As you assume from what I said until now, it looks like managing JSON as a string doesn’t seem to be an option, but that’s not true. As you’ll find out later in this tutorial, we can have the JSON expressed as a NSString object, simply by doing a small kind of trick. Going to NSXMLParser class now, I have to say that is a very convenient one and makes the parsing of XML data a piece of cake. It’s responsible for doing the actual parsing work, and it lets us know about each item that is found during parsing through delegate methods. It provides a great number of such methods, but that doesn’t mean that all of them must be implemented to an app. The ones that will be selected for implementation depend on how the parsed data should be handled. So, as you guess my goal in this tutorial is to teach you how to work with JSON and XML data, and how to handle it so you can use it in your applications. At this point, I should point out two facts: At first, I presume that you know what JSON and XML is, and how data is formed in both formats. If you don’t feel very confident about any of them, then this is a good time to find and read a bit more about them. At second, even though I’m going to show you the basics on both of them, be sure that what you’ll learn is going to be more than enough to help you in your apps and to put you on the right track when you’ll need to find extra support or assistance. Furthermore, in this tutorial you’ll see a couple of other interesting things too: How to easily fetch data from the web using the NSURLSession class, and how to use the MFMailComposeViewController class to present the standard mail view controller of iOS for sending e-mails. In the rest of this tutorial you will find out why and how we will use them. Lastly, as always I recommend and encourage you to visit the official documentation by Apple to get more info on every topic we’ll discuss here. Having said that, let’s go to see an overview of the demo app that we’ll implement in this tutorial, as we have a lot of stuff to do next. Demo App Overview While I was trying to decide where I should get JSON and XML data from for the purpose of this tutorial, I ended up to a website that could provide me with both kind of data, so I considered it as the best option. That is the GeoNames website. It contains an enormous geographical database, an API for accessing its web services, and all that for free. Personally, I think of it as the #1 source when dealing with geographical data, so we’ll work with it. If you are not aware about it yet, then take a few minutes and pay a visit to it. From this website we’ll get two different kind of data. The first one, is detailed information about a country. Not for a specific country, but for any country we’ll set in our app (we’ll talk more about that in a while). The data we’ll fetch will be in JSON format. The second, is the neighbour countries of the one we pick for getting its details, but this time the data will be in XML format. Both cases is what exactly we need for this tutorial. Examples of the JSON and XML data we’ll get through our demo app you can find here (country details) and here (neighbour countries). Let me say a couple of things now regarding the app itself. First of all, we won’t create a new project from scratch. Instead, you’ll download a starter app where I’ve done some basic implementation. That app contains two view controllers, plus the standard iOS email view controller which we’ll present it through code. In the first one we will display the details of a country, while in the second we will list the neighbour countries. We will use the mail view controller (MFMailComposeViewController class) just to make our application more complete, but no e-mail is required to be actually sent. More specifically now, in the first view controller (named ViewController) already exists a textfield, in which you’ll write the name of the country you want to get information for. I already have implemented the functionality of the textfield, so our work will begin by the time you want to download data after having tapped the Search button on the keyboard. Because the URL we’ll use for downloading the data regarding the typed country requires a two-letter country code parameter and not the whole name of the country, I’ve added to the project two text files. In the first one you’ll find all country names, while in the second one you’ll see the respective two-letter country code (for example, country name=ITALY, country code=IT). When tapping on the Search button, in the textFieldShouldReturn: delegate method of the textfield I have already added the logic for looking up the country code based on the given country. In case that no country matching to the typed one is found, then an alert view with a respective message appears. Beyond all that, there are also two more subviews in the first view controller: A label (UILabel) in which we’ll display the country name and its code after having retrieved and converted the data, and a table view for showing some details regarding the country. The last cell of the above table view won’t contain any piece of information regarding the selected country, but it will be used to take us to the second view controller. Before loading it, we will pass a unique id value regarding the country, and using that id we will get the neighbour countries. The second view controller (named NeighboursViewController) contains just a table view which we’ll use to list the fetched data. In the first view controller the data we’ll download will be in JSON format. Using the NSJSONSerialization class we’ll convert and add it to a dictionary (NSDictionary) object, and also we will convert some data back to JSON that we will set as the e-mail body in the mail view controller. In the second view controller we will get the data in XML format, and using the NSXMLParser class of the iOS SDK we will parse them and we will add them into an array. As I have already said in the beginning of the tutorial, through the next parts you will be acquainted with both classes and you’ll see how to handle both JSON and XML data. Register an Account on GeoNames Let’s get started by paying a visit to the GeoNames website for creating a new account. If you want to know more about that, feel free to navigate yourself around and see what it offers. A very interesting part of it, is the Web Services Overview where you can find a list all of the provided services. By clicking on a service you can see details about it and how to use it, while you can have live examples of JSON and XML data returned to you by clicking on the respective links. Anyway, after having seen the website, go and click on the Login link at the top-right side of the index page: In the next page you’ll find two forms, one for logging in and one for creating a new account. The second one is what we need. Fill the form in, and then click on the create account button. Make sure to remember the user name you provide, as we’ll need it in a while. A confirmation e-mail will be sent to your e-mail address. Wait a couple of minutes until you receive it, and then open it to activate your account. A page similar to the next one will open: There’s one more step required before you’re finished here. That is to enable your account for using the free web services, and in order to do that, you must login to your GeoNames account. So, log yourself in, locate the respective link and just click it. You can now log out and go straight ahead to the project. In order to do any call on the GeoNames API, it’s necessary to provide a valid username, such as the one you just created. Without it, no results will be returned when querying the GeoNames database, instead you’ll receive just an error message back from the server. To avoid that, simply open the AppDelegate.m file, and at the top of it locate the next lines: Remove or comment my custom warning that exists there, and set your username in place of the “YOUR_USERNAME_HERE” value. After doing so, you’re ready to use the GeoNames services properly. A Convienient Class Method The data that will be displayed in our sample app are going to be downloaded in real time using the GeoNames web services. To perform all downloads, we’ll use the NSURLSession class, which was first introduced on iOS 7 and tends to replace the NSURLConnection class. The downloading process is going to be repeated in two different view controllers, and it would be a really bad programming practice if we would write the same code twice. Instead, we’ll create a small, class method, in which we’ll add all the code needed to fetch the data we want, and we’ll call it every time we need it. We are going to make it a class method, so we can instantly call it without initializing extra objects. I should note that I purposely didn’t include this method in the starter app, as I believe that working with the NSURLSession class is a very important task, and always beneficial, even if we won’t focus on it too much. So, let’s get started by going to the AppDelegate.h file first, and by declaring the method as shown below: There are three noticeable things here. The first one is that we begin with the plus (+) symbol instead of the minus, as this is a class method. Next, as you can see it accepts two parameters: The first one is the URL that we’ll get the data from. The second one, is a completion handler that the method will invoke after having fetched the desired data. In order to get the data we need, we’ll use a NSURLSessionDataTask task. That class, which is a child of the NSURLSessionTask abstract class, it requires two preliminary steps before putting it in action: To instantiate a NSURLSessionConfiguration and a NSURLSession object. In that task, we’ll provide the URL of the method’s parameter. Also, the method we’ll use has a completion handler block which is called after the data has been downloaded or if any error has occurred. In there we’ll handle the error if exists (we’ll simply log it to the console), and we’ll also show the HTTP status code if is other than 200 (meaning that something went wrong). In any case though, we’ll invoke the completion handler of the parameter, and we’ll pass the returned data as a NSData object. Let’s see all that in code now, in the AppDelegate.m file: Even though everything is quite easy to be understood, and the comments help even more on that, I would just like to underline the use of the next couple of lines: The task runs asynchronously in a background thread, but it’s necessary to call our completion handler on the main thread of the app and not on the thread of the task, so as we ensure that any visual updates after having fetched the data will occur on the proper time. Therefore, we add the completion handler call as an operation to the main thread, using the NSOperationQueue class. If you’re curious about what could happen if we wouldn’t use that operation block, then try to make the completion handler call out of that block after we have the app implemented. You’ll find out that the interface doesn’t get updated properly, and unpredictable delays in the app execution occur. Finally, notice that we use this command: for making the task start working. Now that we have this useful method ready, we can see how we can handle JSON data and convert it to a manageable form. Downloading a Country’s Info as JSON Data In this part we are going to do one of the most important tasks in this tutorial: We are going to download the data for a country of which the name we type in the textfield of on the ViewController view controller, and then we are going to convert the returned JSON from a NSData object into to a NSDictionary object. We’ll see everything in details, but first, let’s declare a private method in the ViewController.m file. Go to the private class section and add the next line: Before its implementation, let’s call it. The point that we should do that, is right after the user has tapped on the Search button of the keyboard, and the two-letter country representation has been found. So, go to the textFieldShouldReturn: delegate method, and locate the next line: Then, right below it, add the method call: The if clause that contains the first line should now look like this: Now, let’s move ahead to the implementation of the getCountryInfo method. At first, we must specify the URL that we’ll get the data from. The URL is this: and we’re going to use it for making a GET request. We must provide two parameter values in the above URL, the username of the GeoNames services, and the country we want to look up info for, expressed as a two-letter string (for that we’ll use the countryCode property already existed in the ViewController class). Let’s see that: If you NSLog the above URLString value now, you’ll see something like this: (Where XXXXXXXX is your username) Now, we can call the downloadDataFromURL:withCompletionHandler: class method we previously implemented. In this, we’ll provide the URL we formed in the above code snippet, and we’ll implement the completion handler block: Notice that is always necessary to check if the returned data is other than nil. In case of error, no data will exist and the data object will be nil, so be careful. For first time, we are about to use the NSJSONSerialization class in order to convert the fetched JSON data into a Foundation object, so we can handle it. Usually, a JSON converted object matches either to a NSArray object, or to a NSDictionary object. In the most cases you can know and tell what object the JSON will be converted to, as in almost every app you can find out the form of the JSON data you’ll fetch. In the rare cases you don’t know how the JSON data is formed and what Foundation object to expect after the conversion, see right next how to determine this. Before I show you how to find out the class of the converted JSON, let me introduce the method that does all the magical work. That is the JSONObjectWithData:options:error:. The first parameter of that method, is the NSData data downloaded from the web. What this method returns, is an id Foundation type. Returning to what I was saying before and using this method, simply by writing this (in any app): you can see in the console the actual class of the converted JSON data. In our case, if we run the app using the above NSLog command, we’ll see the following: That means that by converting the returned JSON data we’ll get a NSDictionary object. That’s great and really interesting! There’s one more way to determine the kind of the returned data. We can open a browser (Safari, Chrome or anything else you use), and set the URL in the address line: By pressing the Return key, you’ll see the JSON string right in front of you: The above screenshot might not be so clear, therefore I’m copying-pasting the returned JSON here as well: The initial curly brace ({) indicates a dictionary object. The bracket ([) indicates an array. Next, there’s another curly brace, meaning another dictionary. In simple words, the above JSON says: We have a dictionary, in which there’s an array with one object only, and that object is another dictionary containing all the data we want (dictionary > array > dictionary). So, what we have to do is this: First, we’ll convert the returned JSON data into a NSDictionary object. Then, we will check if any error has occurred during conversion, and if not we’ll extract the array from that dictionary using the key geonames. Finally, we’ll extract the second, desired dictionary from the first index of that array. Speaking in code this time, here’s what I just said: Initially, we convert the JSON data to the returnedDict dictionary. Next, we get the array and the dictionary of the first index of that array, and we assign it to the countryDetailsDictionary property. Regarding the error object in the above implementation, it’s our duty to check if it’s nil or not, and to take the proper actions. For the sake of the simplicity, we just log the description of the error, if any occurs of course. For now, it would be nice if we could see the fetched data even on the console, therefore complete the above method as shown right next: Running the app now, will return something like the next output: So, we’ve successfully managed to download JSON data and to convert it to a NSDictionary object. That was a very important job, but we have more to do. Next, we’ll display all that data. Populating the Converted JSON Data Now that we have the data we want on our hands, it’s time to display it. There are two subviews for showing data: A label for the country title along with its two-letter code, and a table view for the rest of it. As you see, there’s a lot of data that is being returned, but we are not going to use all of it. Actually, we will show only the following (besides the country name): - Capital - Continent - Population - Area in Square Km - Currency - Languages Let’s get started by the easy one, the country name. While being in the getCountryInfo method and in the else case, add the next line to display the country name to the label existing right below the textfield: This will display something like: ITALY (IT). In the same else case, add the next two lines as well, in order to reload the data in the table view and make it appear (initially the table view is hidden): After the above couple of modifications, your else case in the completion handler block should look like this: Our work in this method is over, so let’s focus on the table view. Initially, go to the tableView:numberOfRowsInSection: and change the return 0; command to this: We want 7 rows to exist in our table view. We’ll use the first six rows to display the data I mentioned above, and in the last row we’ll have a cell that will let us get navigated into a new view controller, where we’ll get the neighbour countries of the selected one. Next, we’ll work in the tableView:cellForRowAtIndexPath: method. As you see, there’s the following initial implementation, where the cell is dequeued or created if it does not exist: Notice that both the accessory type and the selection style are set to None for all cells. Our work here is quite easy. We’ll use a switch statement, in which we will check the index of each row. Depending on this value, we will extract the proper data from the countryDetailsDictionary dictionary and we’ll assign it to the cell’s text label. At the same time, we’ll add a short descriptive text as a subtitle on each cell. Let’s see it: Pay special attention to the last case, where we add the cell that will take us to the neighbour countries list. For this cell only, we set the disclosure indicator as the accessory type and the default selection style. That’s because we want it to prompt us to tap it, and to be highlighted when is tapped. Now you can run the app and see it functioning properly for the first time. Type a country’s name in the text field, and wait until you see its details on the table view. Always remember that these details are fetched in real time from a web server as JSON data, and our app is the one that makes it possible to view that data! Creating a JSON Further than just converting JSON data into a Foundation object (NSArray, NSDictionary), the NSJSONSerialization class can also help us convert data stored in Foundation objects to JSON format. In the previous sections we managed to implement the first case and make our app work great. Now, we will see how to produce JSON data. If you look closely in the view controller when running the app, there is a Compose bar button item at the right side of the navigation bar: Using this button we will perform two things: The first one is to create a JSON string using the NSJSONSerialization class. This string will contain just the country data displayed on our view controller, excluding all the data that we don’t use. The second is to send that string via e-mail, so we’ll make the standard iOS mail view controller appear. Our work will take place in the sendJSON: IBAction method. We’ll begin by creating a new dictionary (NSDictionary) that will contain only the values we want: Now the most important part: We’ll convert that dictionary into JSON data. That’s just a matter of one line: The above does all the magical work. However, we have a problem here: The converted object is a NSData object, and if you try to display its contents you’ll get something like that: Of course, this is not readable by humans, so how can we show and send the actual JSON string? Well, we’ll do a small trick, which is shown below: As you see, we simply convert the NSData object into a NSString object using the above way. This is safe to do, as we already know that a JSON value is a string value. If we use a NSLog command at this point, here’s what we’ll see on the console: That’s great! It’s what exactly we want, and by seeing this we can be sure that our dictionary was successfully converted into a JSON string. Now, let’s make our example more complete, by making it capable of sending the above JSON string via e-mail. To make our work easier, I’ve already imported the necessary library (MFMailComposeViewController), and have adopted the respective protocol (MFMailComposeViewControllerDelegate) regarding the e-mail view controller, so we just need to present it here. One basic thing you should always have in mind when using the MFMailComposeViewController class for displaying the e-mail view controller, is that you should check if the device can actually send e-mails. We’ll perform that check here, and then we’ll do these: - We’ll initialize a MFMailComposeViewController object and we’ll make the ViewController class its delegate. - We’ll set the subject of the e-mail. - We’ll set the body of the e-mail, which obviously is the JSON string we earlier produced. - We’ll present the view controller. Let’s see all that: The IBAction method is now ready. Notice that the mailComposeController:didFinishWithResult:error: delegate method of the * MFMailComposeViewControllerDelegate* protocol has already been implemented, so no more action is required from us. Go and test the app once again. You’ll find out that the mail view controller is appeared (modally), and the JSON string is automatically set as the body of the e-mail. Downloading the Neighbour Countries As you have seen up to here, handling JSON data is really easy with the NSJSONSerialization class. Now, it’s time to move to the second part of the app, where we’ll download data regarding the neighbour countries of the selected one, but this time it’s going to be in XML format. Through the next sections you’ll see how you can use the NSXMLParser class for parsing XML data, and you’ll find out how easy it is to end up with the needed logic for extracting the data. In order to download the neighbours of the selected country, it’s necessary to provide to the URL that we’ll call a unique value regarding the country, named geonameId. That value was returned along with the rest of the data, and if you look closely to the dictionary contents we previously logged in the debugger, you’ll find it there. So, first of all, we must make the ViewController class send the geonameId value to the NeighboursViewController, and then proceed to the rest of the work. Open the NeighboursViewController.h and declare the following property: As you assume, in this property we’ll pass the value we want. Now, back to the ViewController.m file, go to the prepareForSegue:sender: method. This one is called before the new view controller actually gets loaded, so it’s the best place to set the geonameId value to the geonameID property. Add the next code segment: Having this property set, we are able to proceed to our work. Let’s continue by downloading the neighbour countries data, as we previously did with the country’s details data. Go to the NeighboursViewController.m file, in the private class section, and declare the next method: We want the neighbour countries data to be downloaded when the view controller gets loaded, so go to the viewDidLoad method and call it: Now, let’s see its implementation. The first thing we have to do is to specify the URL that we’ll get the data from. Once we have it formed, we’ll call the downloadDataFromURL:withCompletionHandler: class method to perform the actual download. Let’s see everything up to this point: Simple as that! In the next part we are going to begin parsing the data in the above if clause, and we’ll implement all the necessary delegate methods of the parser that will help us to extract the exact data we need. Parsing the XML Data In order to parse an XML file or XML data in general, iOS SDK provides the NSXMLParser class. This one performs all the hard work on the background by going through all the data (by parsing them), and it provides us with some really useful delegate methods. Using them, we can have full control over parsing and handle any data found, in any way we want. In this example, we’ll use some of those delegate methods, and we’ll add all the data we are interested in to an array. Being more specific, let me introduce you the delegate methods of the NSXMLParser class we’ll use, and what each of them is for. For clarification reasons only, I need to say that every XML data that’s about to be parsed, is considered as an XML document by iOS. Keep that in mind when reading next. The delegate methods now: - parserDidStartDocument: This one is called when the parsing actually starts. It’s obvious that is called just once per XML document. - parserDidEndDocument: This one is the complement of the first one, and is called when the parser reaches the end of the XML data. - parser:parseErrorOccurred: This delegate method is called when an error occurs during the parsing. The method contains an error object, which you can use to define the actual error. - parser:didStartElement:namespaceURI:qualifiedName:attributes: This one is called when the opening tag of an element is found. - parser:didEndElement:namespaceURI:qName: On the contrary to the above method, this is called when the closing tag of an element is found. - parser:foundCharacters: This method is called during the parsing of the contents of an element. Its second argument is a string value containing the character that was just parsed. Now that you know the delegate methods we’re about to use in our sample app, let’s discuss a bit about the logic that we’ll follow. Well, as it’s quite possible that multiple results will be returned after a call on the GeoNames API, it’s obvious that we’ll have to insert the parsed data into an array. But, what exactly are we going to add to this array? To answer the above question, we just have to pay a visit to the GeoNames website and perform an API call using the browser, so we see what is being returned when asking for neighbour countries. There’s no simpler option than using the example link of the website, which takes us to a page with the following results: Among all the values that been returned, we are going to use just two of them in our app: The toponymName and the name of the neighbour country. With that in mind, we could say that for every neighbour country that will be parsed, we could add the above two values into a dictionary, and then add each dictionary to the array. In order to make this general idea more specific, let me say what we’ll do in each delegate method, in the order they were previously presented: - parserDidStartDocument: In this one we’ll initialize the array that will contain all the data regarding the neighbour countries. - parserDidEndDocument: As this method signals the end of the parsing, we’ll simply reload the table view, and we will display our data. - parser:parseErrorOccurred: This is just a sample app, so we won’t handle the error, we’ll only log it on the console. - parser:didStartElement:namespaceURI:qualifiedName:attributes: A quite important method, as we will initialize the dictionary in which we’ll store the toponym and the country name when the element is equal to the “ ” value. Moreover, we’ll assign the name of the current element to a property, as we’ll need to know it when parsing characters. - parser:didEndElement:namespaceURI:qName: When the closing “” tag is found, the dictionary containing the two values of interest will be added to the array. Besides that, when parsing either the “” or the “” closing tags, the respective found values will be added to the dictionary. - parser:foundCharacters: When the current element is equal to “ ” or to “ ” then we’ll store the found characters into a mutable string. The value of that string is the one we’ll add to the dictionary when the closing tag of the respective element is parsed. Enough with theory though, let’s start writing some code. At the private section of the class, add the following properties: - The xmlParser property is the one that we’ll use to parse the XML data. - The arrNeighboursData property is the array that will contain all of the desired data after the parsing has finished. - The dictTempDataStorage property is the dictionary in which we’ll temporarily store the two values we seek for each neighbour country until we add it to the array. - The foundValue mutable string will be used to store the found characters of the elements of interest. - The currentElement string will be assigned with the name of the element that is parsed at any moment. Now, go to the downloadNeighbourCountries method, and add the code shown below in the completion handler block: With these four lines in the block, we initialize the parser object, we set our class as its delegate, we initialize the mutable string that we’ll use for storing the parsed values and finally we start parsing. Note that I have already adopted a required protocol, the NSXMLParserDelegate. Let’s start working on the delegate methods now, and let’s see them in the order the were presented above. The first one: As I have already said, this delegate method signals the beginning of the parsing, so we initialize our array. The next one: After the parsing has finished, we simply reload the data on the table view. For the time being nothing happens, but we’ll work on that at the next section. Next: Nothing difficult here too, as we simply display the error description on the console. Two things happen here: If the parser is about to start parsing the data of a new country, then we initialize the dictionary. The second is that we store the current element name (you’ll see why in the last delegate method). This delegate method is called when the closing tag of an element has been parsed. If the element is equal to the “geoname” value, then we know that the data of a country was parsed, so we can add the dictionary to the array. Also, if the element is any of the two we care about, then we store the found value to the dictionary. At the end, we clear the mutable string from any contents, so it will be ready for new values to be appended to it. The last one: Here you can see why the currentElement property is needed for. In case that the current element is any of the two we are interested in, then we keep the actual values found between the opening and closing tags. If you notice, you’ll see that I check for the new line string (“\n”), and if the found string is other than that, then I’m appending it to the foundValue property. That’s because after having tested the app, I noticed that a new line string was parsed before the country name, so this is just a workaround to that problem. Our app now is capable to download XML data, and to parse it successfully. What we have only left, is to display it. Populating the Parsed Data In the starter app you downloaded, there’s already a table view with an initial implementation, waiting for us to do the proper modifications and display our data. As you may have guessed, the datasource of the table view is going to be the arrNeighboursData array. We’ll begin working on the data display by going first to the tableView:numberOfRowsInSection: method. In this one, replace this: With this: By doing that, the table view will return as many rows as the neighbour countries are. Next, let’s go to the tableView:cellForRowAtIndexPath: method and let’s display our data. Before I give you the implementation, let me remind you that a dictionary object exists in every single position of the array. Let’s see the method now: As you see, in the text label of the cell we assign the name of the country, and we set the toponym name to the subtitle label. Everything is ready now, so you can go and try the app. After you have typed a country name in the initial view controller, tap on the Neighbour Countries cell to make the app download and parse the neighbour countries of the one you chose. Then, wait until the new data appear on the table view we just set up. Summary Performing simple but crucial operations over JSON and XML data, is proved to be a relatively simple job. NSJSONSerialization and NSXMLParser classes are both very handy and powerful, and once you know how to use them you can work with the two respective data formats fast and painlessly. As you found out while you were reading this tutorial, I didn’t get into many, hard details of each class. I did this on purpose, as my primary target was to give you a way to start working with them, not to turn you into experts at once. In many cases, what I showed you here is just enough to let you handle any data your app is about to manage, but even in the opposite case, you now know the tools you should use. For your reference, you can download the complete Xcode project from here. As always, I hope you found this tutorial useful. Until next time, leave us your thoughts or anything else you wish to share with us!
http://www.appcoda.com/parse-xml-and-json-web-service/
CC-MAIN-2017-17
refinedweb
6,499
65.46
Hi, I am looking for a way to create a conditional z-score in the following context: def make_ml_pipeline(factors, universe): factors_pipe = OrderedDict() for name, f in factors.iteritems(): factors_pipe[name] = f().zscore() pipe = Pipeline(screen=universe, columns=factors_pipe) return pipe Now the z-score substracts the mean and divides by the standard deviation. When the standard deviation is 0 for a particular date, the z-score fills in np.NaNs into the column for all assets for that particular date. I would like to have the condition: If standard deviation == 0 then use original value, else calculate the zscore across all assets for that particular date. For the people who want to know the reason why one would need that... If you do any automated machine learning, where you are creating a nullhandling indicator column with zeros and ones, you have the occational column where no data is missing (i.e. the whole column will be filled with zeros). For that column the standard deviation will be 0 as well and therefore the zscore np.NaN. Since algorithms cannot calculate with np.NaNs, I want it to write 0 instead for that particular situation - in an automated way. Any ideas?
https://www.quantopian.com/posts/conditional-z-score
CC-MAIN-2019-43
refinedweb
201
55.64
The Magic Behind Tensorflow "With great power comes great responsibility", Spider-Man Tensor and Flow? First of all, let's clear out what a tensor is. In short, a tensor is a multi-dimensional matrix which makes computations much faster as we are not calculating values one by one but we compute all the values at once. By doing so in Tensorflow, we gain a significant computational performance boost. In Tensorflow a scalar, a vector and a matrix are all implemented as tensors. Each of them has a specific rank: zero rank means a scalar value, rank 1 means a vector and rank 3 means a matrix. But those are just vectors or matrices represented as tensors. What does a "real tensor" look like? Well, look at the pictures below. one representation of a tensor another representation of a tensor A tensor is the main data structure in Tensorflow A 3 dimensional tensor also has a rank which is rank 3. We can go on and on by saying rank n tensor is a n-dimensional tensor which means we can potentially have a huge amount of dimensions in our tensor. In Tensorflow each numerical object is represented in form of a tensor, be it a n-dimensional vector or matrix. To put it simply, in Tensorflow everything is a tensor. By using tensors we achieve a huge computational efficiency. If we're computing with normal, non-tensor matrices, we receive the result only for once entry at a time. That would mean if we train a neural network with millions of entries, it will take a looooong wile until they are all computed ... The key idea with tensors is: we are able to perform simultaneous computations on all the entries we have in our matrices. In Tensorflow, computations are presented as nodes. More on this later in the article. And what about "flow"? The idea with the flow is that the created tensors are "flowing" through the model's computational graph, consisting of nodes (which are tensors) and connections (weights). Read more on weights in neural networks here and here . Computational graphs: an Overview Computational graphs are also sometimes called "dataflow graphs". Node A computational graph consists of nodes and edges. Each node represents some mathematical operation. The result of the operation is stored in the node in form of some variable and is passed to the next node as a ready-to-be-used calculation. All in all, a node is a way to present some function we need for our further computation. Such architecture allows us to reuse our computations at a later point. In context of Tensorflow we should mention the lazy execution. Despite that this execution type is called "lazy", it gives us a massive advantage in terms of the computational speed. If we make use of the lazy execution, Tensorflow doesn't compute values until we tell it to perform these computations. Tensorflow processes its input values if we request it to do so, otherwise Tensorflow only stores generated information for later use. Such structuring empowers us to parallelize or fuse computations in a more easy way. In lazy execution the idea of a session is crucial to understand. We need to create a session in Tensorflow lazy execution in order to activate our computational graph and compute the values from it. A session is a way to allocate necessary memory for storing variables' values. You can compare a session with some executable file that may be run on your computer. Without a session there is no execution possible. Another important concept of lazy execution is a placeholder. A placeholder is some variable which will receive its value at a later point in time. With placeholders in lazy execution we generate operations for the computational graph without any data in the first place. Through these placeholders we are able to "feed" our data into the computational graph later on. Metaphorically, we can imagine placeholders as parts of an empty shell, we will fill later with some values. Consult the following code, which represents placeholders and sessions in action: import tensorflow as tf p_1 = tf.placeholder(tf.float32, None, name="placeholder_1") # here we store our value later func = p_1**2 # our operation with tf.Session() as sess: res = sess.run(func, feed_dict={p_1: [2,3,5]}) # 'feed_dict' is an input for the 'func', define the placeholder p_1 print(res) Note: there also exists the "eager execution" which computes operations on the fly. This type of execution does not set up a graph or creates any sessions. Eager execution utilizes the concept of imperative programming. We will cover eager execution later on. So, each graph consists of nodes and edges. Each edge represents a weight and each node represents a tensor. Let's start with a simple example, for the function g = ((a * b) + d) / f we can construct the following computational graph: computational graph for the function g This is an introductory example of a computational graph. If we feed it into the Tensorflow framework, we don't get any satisfiable result as we perform only the forward pass. To unwrap the real potential of our neural network we will use the power of differentiation. By that I mean the Chain Rule and by that I mean Backpropagation. If you need a refresher on the Chain Rule and Backpropagation, consult this article Backpropagation. It will provide you with necessary background knowledge. A small recap : we use backpropagation to go backwards in the neural network where we start from the beginning in order to update the weight values. If we do not perform weight update, the neural network won't learn anything, which means, it becomes useless. The chain rule is basically the means by which the backpropagation is implemented. The chain rule is in its core a multiple application of differentiation rules on composite functions. Composite functions are functions with another functions inside. Now we compute partial derivatives of the computational graph from above starting from the end point as we're applying backpropagation: computational graph for partial derivatives of the function g For a quick recap: gradients ( ∇ ) are vectors of partial derivatives. Partial derivatives ( ∂ ) are derivatives taken with respect to one certain variable while other variables are held constant. To review what derivatives and Co. are, consult this article here . As you might notice, we start from the last computation and go backwards in the graph, computing partial derivatives of each node and performing backpropagation. We need partial derivatives to determine the rate of change in our function. For example, if we have something like: ∂g / ∂f we read it as the partial derivative of g with respect to f and we want to find the change in g if we slightly change f . With partial differentiation we find the change of a function with respect to (w.r.t.) some variable, for example, the change of the function g w.r.t. the variable a according to the chain rule would look like this: Same for the b variable: In Tensorflow once we've done with defining the computational graph, we compile the whole model to define the loss function, the optimizer and the metric we want to be used in our model. We can see compile as a method to create connections between the nodes in a graph. We compile our model before training to set parameters such as an optimizer, a loss function and metrics. Look at an example of training and evaluating a model here. There is a pre-implemented compile method in Tensorflow we can use. compile( optimizer='rmsprop', loss=None, metrics=None, loss_weights=None, sample_weight_mode=None, weighted_metrics=None, target_tensors=None, distribute=None, **kwargs ) Why do we use compile if we can program in python? Python is a non-compiled language, right? Yes, that's right. The thing is the Tensorflow idea is that we can use some programming language (often it's python) to compute our model. Tensorflow itself is not intrinsically bound to python. In fact the backend of Tensorflow is written in C++ and CUDA. We don't really express the python code in the end. Instead the code is being translated into a computational graph and computed further, so we gain the maximum optimization. Computational Graph: More Details Let's analyze computational graphs in detail. What does a computational algorithm look like with a simple neural network? Starting with an example: imagine we have an input vector x with n values in it, a weight vector w with n values in it and a bias b, which is a scalar. We have a function of the form: σ((x n * wTn) + b) where the small Greek sigma is the sigmoid function, which serves as our activation function. This whole equation is called prediction and we denote it with Å· . We also need a loss function for our neural network in order to be able to analyze the error of the outputted prediction. Let's say that we have a regression task, so we can take the Mean Square Error (MSE) function which has the following form: MSE = (ΣNi=1 (yi - Å·i)2) / N where N is the total number of samples. Now we want to produce a computational graph for the following equation: As we already know, Tensorflow needs to perform partial differentiation on the graph starting from the very end, so the graph will look like this: Tensorflow will do the differentiation part for you automatically. So you don't have to differentiate anything on the paper which becomes less and less feasible for bigger and more complex neural networks :( . The automatic differentiation in Tensorflow does exactly what we just saw ourselves: - create a computational graph - calculate derivatives from the computational graph - to calculate derivatives use the chain rule - take a node and its corresponding gradient operation - calculate the derivative of the input w.r.t the output - backpropagate by calculating the gradients w.r.t. each network's parameter to use the chain rule and to backpropagate: A short summary for computational graphs: one of the main concepts behind computational graphs lies in code portability. We can actually export any created graph from Tensorflow and use it on any other architecture. GradientTape Tensorflow GradientTape is an automatic differentiation API. The "Tape" part denotes that each operation will be "written down on a tape", aka stored. Then we can compute the gradients from the stored computation. The stored computation consists of operations and again previous gradients. But aren't the gradients stored automatically all the time? Well, read further ... GradientTape is very useful when we utilize eager execution. With eager execution Tensorflow won't build a computational graph for us, neither create a session as it is usual in the case of lazy execution. If Tensorflow provides no graph, it also won't store gradients for us explicitly. But it's still necessary to record the gradients to be able to apply backpropagation later. For this purpose we use GradientTape as all operations will be recorded. So now, even with the eager execution, we can calculate the gradients of the loss function w.r.t the parameters. Let's summarize some key differences between Lazy and Eager executions: Lazy: - constructs a graph - create a session to activate the graph: Session.run() - utilizes placeholders - gradients are saved in a graph internally - a session is saved as a whole Eager: - doesn't construct a graph - use tf.enable_eager_execution() to enable the eager mode (if you don't use the 2.0 version) - has no placeholders, instead we pass data in form of arguments directly into a function - gradients are saved with the help of GradientTape - the eager saver navigates to variable values and loads them through Checkpoint import tensorflow as tf tf.enable_eager_execution() # activate eager execution c = tf.constant((2.0)) # a Tensorflow constant with value 2.0 with tf.GradientTape() as tape: tape.watch(c) # 'watch' for tape to record c f = 4*c df_dc = tape.gradient(f,c) print(df_dc) the output is: tf.Tensor(4.0, shape=(), dtype=float32) Again we have the function: f = 4*c so consequently we get ∂ f / ∂ c Going through the different Tensorflow versions and their configurations for different purposes may be a pain. Just keep in mind that for Tensorflow 2.0 the eager execution is the default mode. Conclusion In this article we've learned about two types of execution in Tensorflow: lazy and eages ones. We've analyzed the workflow of computational graphs and what is behind it, namely partial differentiation. With computational graphs Tensorflow doesn't have to compute everything from the code but instead it can create a graph and represent our code in it. We have to run a session in order to compute values from the graph. This type of procedure is called lazy execution paradigm. In the Tensorflow 2.0 version, the approach is to get rid of sessions and to execute everything in eager per default. I hope, you could unravel some magic behind one of the most frequently used Machine Learning frameworks at the present time. For further research, consult the official Tensorflow documentation. Further recommended readings: Neural Networks Introduction Partial Derivatives and The Jacobian Matrix
https://siegel.work/blog/MagicTensorflow/
CC-MAIN-2020-34
refinedweb
2,209
55.44
I think this is an issue, or it may just be a quirk of a container I built for deployment via JupyterHub using Kubernetes on Azure to run user containers, but it seems you that SQLite does things with file locks that break can the sqlite3 package… For example, the hacky cross-notebook search engine I built, the PyPi installable nbsearch, (which is not the same as the IBM semantic notebook search of the same name, WatViz/nbsearch) indexes notebooks into a SQLite database saved into a hidden directory in home. The nbsearch UI is published using Jupyter server proxy. When the Jupyter noteobook server starts, the jupyter-server-proxy extension looks for packages with jupyter-server-proxy registered start hooks (code). If the jupyter-server-proxy setup fails for for one registered service, it seems to fail for them all. During testing of a deployment, I noticed none of the jupyter-server-proxy services I expected to be visible from the notebook homepage New menu were there. Checking logs (via @yuvipanda, kubectl logs -n <namespace> jupyter-<username>) it seemed that an initialisation script in nbsearch was failing the whole jupyter-server-proxy setup ( sqlite3.OperationalError: database is locked; related issue). Scanning the JupyterHub docs, I noted that: > The SQLite database should not be used on NFS. SQLite uses reader/writer locks to control access to the database. This locking mechanism might not work correctly if the database file is kept on an NFS filesystem. This is because fcntl() file locking is broken on many NFS implementations. Therefore, you should avoid putting SQLite database files on NFS since it will not handle well multiple processes which might try to access the file at the same time. This relates to setting up the JupyterHub service, but it did put me on the track of various other issues perhaps related to my issue posted variously around the web. For example, this issue — Allow nobrl parameter like docker to use sqlite over network drive — suggests alternative file mountOptions which seemed to fix things…
https://blog.ouseful.info/2021/04/29/running-sqlite-in-a-zero2kubernetes-jupyterhub-spawned-jupyter-notebook-server/?orderby=ID&order=ASC
CC-MAIN-2021-21
refinedweb
340
56.39
Opened 7 years ago Last modified 3 years ago #5902 new bug Cannot tell from an exception handler whether the exception was asynchronous Description Following on from #2558 which was closed (by me) as wontfix, we still don't have a way to reliably tell whether an exception we caught was asynchronous or not. There are some suggestions in #2558, we just need to implement something. The fix for #3997 was defficient due to this, as exposed by the test program in #5866. Change History (29) comment:1 Changed 7 years ago by comment:2 Changed 7 years ago by comment:3 Changed 6 years ago by comment:4 Changed 6 years ago by comment:5 Changed 5 years ago by I think we've been running into problems with this when using the GHC API, with the same async exception being caught multiple times. Here's a small testcase of what I think is going on: import Control.Concurrent import Control.Exception import System.IO.Error import System.IO.Unsafe -- Our code: main = do tid <- myThreadId forkIO $ do threadDelay 1000 throwTo tid UserInterrupt print i `catch` \e -> putStrLn ("Got " ++ show (e :: AsyncException)) print i `catch` \e -> putStrLn ("Got " ++ show (e :: AsyncException)) -- A small simulation of the GHC API: f :: IO Integer f = (return $! sum [1..10000000]) `catchIOError` \_ -> return 3 i :: Integer i = unsafePerformIO f Although we only throw UserInterrupt once, we catch it twice: $ ghc -O --make exc $ ./exc Got user interrupt Got user interrupt Unfortunately, I can't see a workaround if you want to use async exceptions with the GHC API. Once you throw one, there's a chance that an unsafePerformIO thunk somewhere inside the GHC API will end up containing it as a synchronous exception, and then any call to the GHC API that uses that thunk will just throw that exception. comment:6 Changed 5 years ago by Any time there's a catch/rethrow inside an unsafePerformIO we'll have this problem. So in the specific case of the GHC API it would help to know where this is happening, and whether we can avoid it. One way I can think of that might help in general is to have a special kind of catch that doesn't catch asynchronous exceptions. So in cases like your example, catchIOError would use the special sync-only catch internally, and would ignore the async exception. However, this unfortunately doesn't help with bracket and finally, which need to do some cleanup in the exception handler, and I suspect these are more common than catch. comment:7 Changed 5 years ago by For the benefit of people who find this ticket: the SomeAsyncException class and corresponding functions are now in HEAD. comment:8 Changed 5 years ago by Unlikely to happen for 7.8.1; we don't even know what to do! Simon comment:9 follow-up: 10 Changed 5 years ago by If we had newCatch :: Exception e => IO a -> ((e, Bool{- async? -}) -> IO a) -> IO a newCatch = ... primitive ... newThrow :: Exception e => (e, Bool) -> a newThrow (e, async) = if async then do t <- myThreadId throwTo t e else throw e then would using newCatch and newThrow in place of catch and throw solve the problem? (at the expense of having this annoying Bool getting in the way, and making the code less pretty). comment:10 Changed 5 years ago by If we hadnewCatch :: Exception e => IO a -> ((e, Bool{- async? -}) -> IO a) -> IO a newCatch = ... primitive ... newThrow :: Exception e => (e, Bool) -> a newThrow (e, async) = if async then do t <- myThreadId throwTo t e else throw e then would using newCatchand newThrowin place of catchand throwsolve the problem? (at the expense of having this annoying Boolgetting in the way, and making the code less pretty). I've had that design for quite some time now, I'm unsure if there's another sensible solution, except magically tagging the exception values themselves, but that could only complicate things. comment:11 Changed 5 years ago by It doesn't solve the problem, because the programmer has to be prepared for newThrow to return. This is what happens if an async exception is thrown to a thread that is inside newCatch inside unsafePerformIO inside a thunk evaluation, and the thunk is subsequently re-entered. comment:12 Changed 5 years ago by comment:13 Changed 5 years ago by Hmm. If we also had something like newUnsafePerformIO :: IO a -> a newUnsafePerformIO io = unsafePerformIO io' where io' = io `newCatch` (\eb -> (newThrow eb >> io')) so that at the outermost level the unsafePerformIO knows how to continue, then would that suffice? Or would it still be possible for problematic thunks inside io to be reentered? comment:14 Changed 5 years ago by Now I think about it, this isn't such a bad idea. Unfortunately we can't implement newCatch, because the async exception might have been re-thrown (say by a finally) inside the io. So the best you can do is recognise an async exception by its type - i.e. if it is an child of AsyncException then it's async, otherwise not. But that's good, because it means we don't have to change the RTS or primops. Then there's the question of whether restarting the io is safe. It probably is; as Simon pointed out, the io inside unsafePerformIO is supposed to be a benign side-effect, so we ought to be able to repeat it. comment:15 Changed 5 years ago by I don't see why you can't have newCatch, provide you are willing to also have newThrow and to deal with passing the annoying Bools around. But using an AsyncException hierarchy instead might be OK too. comment:16 Changed 5 years ago by newCatch doesn't work for bracket. Consider: bracket before after thing = mask $ \restore -> do a <- before r <- restore (thing a) `onException` after a _ <- after a return r Now, when the async exception is received, onException runs the exception handler ( after a), which cleans up whatever resource was allocated by before. But when this this resumed after the async exception, if onException is using newCatch/ newThrow, it would re-run restore (thing a), which assumes that the resource is present and accessible. So while it might make sense to re-run the whole unsafePerformIO when we resume after an async exception, it certainly doesn't make sense to do it at a finer granularity. We don't want most exception-handlers to be resumable. comment:17 Changed 5 years ago by I'm a bit confused now. If we only use newUnsafePerformIO (and not plain unsafePerformIO), then is it still possible for a bracket to be resumed? comment:18 Changed 5 years ago by If a type-based solution is implemented, I propose for SomeException to be deprecated and split into SomeSyncException and SomeAsyncException. Right now, SomeException and lack of discrimination for asynchronous exceptions pose serious threat to modularity in concurrent applications. Every innocuous catch or try anywhere at any time in any library can make a thread unintentionally uncancelable. I had to write patches for three different libraries because of this recurring problem; what would happen if my project depended on 50 libraries all throwing and catching exceptions? comment:19 follow-up: 20 Changed 5 years ago by @exbb2: we already have SomeAsyncException, and the asynchronous exceptions are children of this in the exception hierarchy. The exception hierarchy needs a single root, so SomeException remains. Every innocuous catch or try anywhere at any time in any library can make a thread unintentionally uncancelable I'm not sure what you mean here. The issue in this ticket only arises when using unsafePerformIO. comment:20 Changed 5 years ago by Every innocuous catch or try anywhere at any time in any library can make a thread unintentionally uncancelable I'm not sure what you mean here. The issue in this ticket only arises when using unsafePerformIO. tryNTimes n | n <= 0 = return () | otherwise = forever (return ()) `catch` \(_::SomeException) -> tryNTimes (n - 1) or try something :: IO (Either SomeException x) Catching SomeException is sometimes reasonable, but it's unreasonable not to provide ability to discriminate against irrelevant asynchronous exceptions which do not directly follow from handled code. comment:21 follow-up: 22 Changed 5 years ago by Just never catch SomeException unless you intend to re-throw it. If you're handling an exception, you always know which exception(s) you're handling, so you can use type-specific handlers. comment:22 Changed 5 years ago by Just never catch SomeExceptionunless you intend to re-throw it. The code in my case quickly grew into monstrosity such as bracket openFile doDangerousStuff close `catches` [\Async -> throw ,\Some -> logFailureAndResume] Even that doesn't work for Timeout, unless we resort to string comparison. If you're handling an exception, you always know which exception(s) you're handling No. All arguments and values in function can throw any exception whatsoever, there can be no knowing of what exceptions you'll receive. e.g. what if the next version of base introduces a hard-to-track division by zero? We shouldn't ever care about what exception we got. If it had arisen from code enclosed by the handler, — there can be no doubt as to its intended recipient — and no danger in catching it. Asynchronous exceptions have only dimmest relation to code being executed or none at all, there can be no modularity when every exception handler is concerned with whole state of the universe. comment:23 Changed 5 years ago by comment:24 Changed 4 years ago by Bumping priority down (these tickets haven't been closely followed or fixed in 7.4), and moving out to 7.10 and out of 7.8.3. comment:25 Changed 4 years ago by Actually dropping priority. :) comment:26 Changed 4 years ago by comment:27 Changed 4 years ago by Moving to 7.12.1 milestone; if you feel this is an error and should be addressed sooner, please move it back to the 7.10.1 milestone. comment:28 Changed 3 years ago by Milestone renamed After playing around with this for a while I'm not sure there's anything sensible we can do. I tried passing a Boolto the handler in the primitive catch#to indicate whether the exception had been thrown asynchronously or not, but in the example I was interested in ( unsafeInterleaveIO getLine, from #5866) it didn't help: the exception is first caught and thrown again by an inner exception handler before being caught by the outer exception handler. The inner exception handler is not in a position to re-throw the exception asynchronously because it has no sensible way to resume, but the outer handler can. In this case, checking whether the exception is one of the designated asynchronous exceptions ( ThreadKilledetc.) works fine. One positive step we could take is to use the exception hierarchy properly and make an AsyncExceptionsub-hierarchy, and put Timeoutunder it. This would fix the specific problem in #5866.
https://ghc.haskell.org/trac/ghc/ticket/5902
CC-MAIN-2018-43
refinedweb
1,845
58.72
Structuring Your Tasks¶ What should be a task?¶ The trade-off is between tasks that are too small (you have too many of them and the overhead of jug will overwhelm your process) or too big (and then you have too few tasks per processor. As a rule of thumb, each task should take at least a few seconds, but you should have enough tasks that your processors are not idle. Task size control¶ Certain mechanisms in jug, for example, jug.mapreduce.map and jug.mapreduce.mapreduce allow the user to tweak the task breakup with a couple of parameters In map for example, jug does, by default, issue a task for each element in the sequence. It rather issues one for each 4 elements. This expects tasks to not take that long so that grouping them gives you a better trade-off between the throughput and latency. You might quibble with the default, but the principle is sound and it is only a default: the setting is there to give you more control. Identifying tasks¶ In the module jug.hash, jug attempts to construct a unique identifier, called a hash, for each of your tasks. For doing that, the name of the function involved invoked in the task together with the parameters that it receives are used. This makes jug easy to use but has some drawbacks: - If your functions take long/big arguments, the hash process will potentially be costly. That’s a common situation when you are processing arrays for example, or if you are using sets/dictionaries, in which case the default handling needs to get a sorted list from the elements of the set/dictionary. - Jug might not know how to handle the types of your arguments, - Arguments might be equivalent, and thus the tasks should be identified in the same way, without jug knowing. As a very contrived example, suppose that a task uses an argument which is an angle and for the purpose of your program all the values are equivalent modulo 2*pi. If you control the types of your arguments, you can add a __jug_hash__ method to your type directly. This method should return a string: class MySpecialThing(object): def __jug_hash__(self): return some_string Alternatively, you can use jug.utils.CustomHash in the case where you cannot (or rather, would not) change the types: from jug.utils import CustomHash def my_hash_function(x): return some_string_based_on_x complex = ... value = CustomHash(complex, my_hash_function) Now, value behaves exactly like complex, but its hash is computed by calling my_hash_function.
http://jug.readthedocs.io/en/latest/tasks.html
CC-MAIN-2017-39
refinedweb
422
68.91
- First of all, as a user app, I think it should not access the root "/" directly. So I assign root to Environment.getExternalStorageDirectory(), it's the Android external storage directory. - Secondly, if a file/directory is hidden or un-readable, it will not be display. Create /res/layout/row.xml, the layout of the rows in the list. <?xml version="1.0" encoding="utf-8"?> <TextView xmlns: The main layout with a ListView. <LinearLayout xmlns: > Main code. package com.example.androidexplorer; import java.io.File; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.os.Environment; import android.app.AlertDialog; import android.app.ListActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends ListActivity { private List<String> item = null; private List<String> path = null; private String root; private TextView myPath; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myPath = (TextView)findViewById(R.id.path); root = Environment.getExternalStorageDirectory().getPath();]; if(!file.isHidden() && file.canRead()){) { // TODO Auto-generated method stub File file = new File(path.get(position)); if (file.isDirectory()) { if(file.canRead()){ getDir(path.get(position)); }else{ new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle("[" + file.getName() + "] folder can't be read!") .setPositiveButton("OK", null).show(); } }else { new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle("[" + file.getName() + "]") .setPositiveButton("OK", null).show(); } } } - Sort directory/file in alphabetical order ignore case 37 comments: can you please post the manifest file as well? I don't seem to be able to run the code even though it shows no error. maybe i forgot to add a line in the manifest. there is nowhere a good tutorial which includes manifest file... Hello Tobias Klein, You can download the files, manifest included. this line gives an error because i extend Activity instead of ListActivity. setListAdapter(fileList); what could i do to fix it? thanks hello tegleg records android, something like this: your_ListView.setAdapter(fileList); You need to add the following permission to your Android Manifest file -- uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" thanks, your_ListView.setAdapter(fileList); fixes the error but now the browser doesnt work, you cant open folders. Hello tegleg records android, I don't know the exact reason of your case. But, if you target for minimum SDK of level 16, Android 4.1, you have to add permission of READ_EXTERNAL_STORAGE. New permission for Android 4.1, API Level: 16. minimum level is 8. for testing i copied your code but changed it to extend Activity. then i changed setadapter.. stuff to your suggestion. it asked to remove the overide on onListItemClick() so i did that. on the phone i get the first level but clicking on anything doesnt bring up the dialog and also folders dont open. must be something to do with onListItemClick but i dont know what. thanks so much for taking the time to answer. Hello tegleg records android, If you extends Activity, instead of ListActivity, tou cannot override onListItemClick() directltly; because there is no onListItemClick() in Activity class. You have to implement OnItemClickListener() and call myListView.setOnItemClickListener(...) to assign it to the ListView. Refer Implement ListView NOT extends ListActivity. awesome, got it working now. thanks for sharing the code and for your support :) I couldn't get this to work until I moved the initializations for the private members(item, path, etc.) to the onCreate method. So in onCreate I have item = null; path = null; , etc. Hi everyone ! I donwloaded your archive and it works ! Thanks ! But now, I want to open files (for example, when I click on jpeg file, I want to display it, I don't know if you understand...) Thanks for your help ;) hello Badboy, Please read Android File Explorer with JPG's Exif & Photo displayed. Thanks for your help ! I did it with jpeg image but if I want to play a music (mp3,wav or mid for example), have you got a idea ? Play "audio/mp3" with MediaPlayer or Start Intent to choice "audio/mp3" using installed app Thank you for your code. I want to add a back button but I don't know how to program it to do wht the "../" button does. This is what i have: @Override public boolean onOptionsItemSelected(MenuItem items){ switch(items.getItemId()){ case R.id.home: path.add(root); //myPath.invalidate(); //f.invalidateViews(); return true; case R.id.back: path.add(f.getParent()); return true; default: return super.onOptionsItemSelected(items); } } you can call getDir(root); getDir(f.getParent()); Hello, I've came across this nice example of yours as I am currently working on my diploma project for the university. I would like to ask you if it is ok to use it as i found no specifications regarding a license or so. Thank you, Monica hello Monica Ias, It's only a common approach, and no any license. You can use it. And remind here, as I know, use Environment.getExternalStorageDirectory() in this case cannot access SD Card in Samsung devices. Hey again :) I tried it on a Samsung Galaxy S3 Mini and it worked just fine. Though I don't have an SD card... Anyway, thank you. Have a nice day! Monica. Very nice. It help me with my project. Thank you very much! File closes unexpectedly Hi, could you write tutorial how to add SU permission to this? I would be great because nowhere in the Internet there is such tutorial how to create a simple root file manager. hello kormateusz, I don't know what you means "SU permission"? SU? as a app on un-rooted device, it should have no right as SU, as I know. root file manager? do you means file manager have right of root user? I have no idea. If you want file explorer for root directory, "/", here is another example: SU I mean Super User. Yes, I mean File Manager for rooted device. For example to view directories and files from "/data", "/cache" or "/config". I added such code: Process process; try { process = Runtime.getRuntime().exec(new String[] {"su", "-c", "ls /data"}); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = in.readLine()) != null) { pathleft.add(line); } } catch (IOException e) { e.printStackTrace(); Toast.makeText(getActivity(), "NOT ROOT", Toast.LENGTH_LONG).show(); } And it display files from "/data" but I can't enter to the next directory or open a file from "/data". And even I can't sort these files. Maybe you know how to fix it? And sorry for my english, its not perfect :) Oh, I have found the solution and it works pretty well. Really sorry for the problem. Hello, thak you very much for this file manager tutorial. I made the possibility to select a file and then edit it in another activity of course (and this often requests a file name modification); so when I return to the activity filelist I make a refresh, calling getdir with the previous directory path, but the file name remains the same so I have to move to another directory and re-enter to the original again; have you got an idea to solve this, sir? Hey thanks for the guide :D How would you go about opening a text file though? I looked at your open image guide but I dont think it covers opening a text files content and displaying it. Eric, can you explain why you added a row.xml file and what is its purpose? hello 178º, row.xml is the layout of individual row in ListView. It is passed to ArrayAdapter constructor. Because I want a bigger text in ListView, so I have to create a custom layout. HI, I am trying to use this code inside an activity that is launched after click on the button inside the mainActivity. but i am getting error here when i am calling "getdir(root)" this is throwing the exception " couldn't execute method GETDIR(root)" Thanks Rishav Thank you for your great downloable example! : ) Thank you works! but i cant find downloads folder anywhere in filebrowser. any ideas? Actually, its ok now. Forgot that CCleaner had obliterated my Downloads folder, meaning it doesn't show (when it's empty). This newer code really does work! Now I just need to use the selected file with an Intent... Thanks.
http://android-er.blogspot.com/2012/07/example-of-file-explorer-in-android.html
CC-MAIN-2016-50
refinedweb
1,391
61.02
Hi, the “foreach” function call hangs when the underlying function throw an exception. For example the following code without “print 1/0” part is working fine and prints stack trace and the first “key, bins” pair and exit, but with the “print 1/0” it prints the stack trace and hangs. def print_key((key, meta, bins)): import traceback traceback.print_stack() print 1 / 0 # any code which throws an exception print key[2], bins return False client.scan('some_namespace') client.foreach(print_key) Tried with both concurrent values(True, False). In case of False the process is just hanging, in case of True the process infinitly prints the same stack trace.
https://discuss.aerospike.com/t/foreach-hangs-when-underlying-function-throws-an-error/2535
CC-MAIN-2018-30
refinedweb
109
71.65
This article a detailed guide that'll help you set up your Firebase database and perform simple CRUD operations on it using Python. Firebase, as you might know, is a platform provided by Google to accelerate app development. It offers BaaS or backend as a service, which means that Firebase takes care of cloud infrastructure and all your backend needs. This lets you develop and deploy faster. Firebase offers several amazing products, such as Realtime Database, Cloud Firestore, and Authentication. And it also allows hosting and offers API's for machine learning tasks like text recognition, image labelling and so much more! Head over to their site linked here and drool over the wonderful options available. How to Set Up a Firebase Realtime Database Create a new project on Firebase – let's name it BookStoreProject. Once it has been set up, create a Realtime Database by selecting the Create Database option. When you click on Create Database, you have to specify the location of the database and the security rules. Two rules are available: - locked mode, which denies all reads and writes to the database, and - test mode, which allows read and write access for a default 30 days (after which all read and writes are denied unless the security rules get updated). Since we will be using the database for read, write, and edit, we choose test mode. Once that is done, the database is all ready for our usage! How to Write to Firebase Realtime Database Using Python The immediate next step is to find out how we can connect to our database using Python. We are going to use the Admin Database API. You'll need to install the required library. For more information on using firebase_admin for Python, check out the official docs linked here. pip install firebase_admin To connect to Firebase, we need the following lines of code: import firebase_admin cred_obj = firebase_admin.credentials.Certificate('....path to file') default_app = firebase_admin.initialize_app(cred_object, { 'databaseURL':databaseURL }) To make the code work however, we need some prerequisites. First, we need to specify the path to a Service Account key that will be used for initializing the admin SDK. Firebase will allow access to Firebase server APIs from Google Service Accounts. To authenticate the Service Account, we require a private key in JSON format. The path to this JSON file must be provided to create the credentials object. To generate the key, go to project settings, click Generate new private key, download the file, and place it in your directory structure. For an in-depth explanation of this process, refer to the official docs linked here. Next, we need the databaseURL, which is simply the URL that gives access to our database. It is present on the Realtime Database Firebase Console page itself. How to Write Using the set() Function from firebase_admin import db ref = db.reference("/") We set the reference to the root of the database (or we could also set it to a key value or child key value). The question that naturally arises is what schema is allowed for storing data in Realtime databases? All data to be stored must be in JSON format, that is, a sequence of key value pairs. If you need a system generated key, you could opt for using the push() function which we'll cover shortly. Let's construct a suitable JSON which can be saved in the database. We have information regarding four books as follows: { "Book1": { "Title": "The Fellowship of the Ring", "Author": "J.R.R. Tolkien", "Genre": "Epic fantasy", "Price": 100 }, "Book2": { "Title": "The Two Towers", "Author": "J.R.R. Tolkien", "Genre": "Epic fantasy", "Price": 100 }, "Book3": { "Title": "The Return of the King", "Author": "J.R.R. Tolkien", "Genre": "Epic fantasy", "Price": 100 }, "Book4": { "Title": "Brida", "Author": "Paulo Coelho", "Genre": "Fiction", "Price": 100 } } We load the required JSON file and save data to the database like this: import json with open("book_info.json", "r") as f: file_contents = json.load(f) ref.set(file_contents) The database now looks like this: How to Write Using the push() Function Firebase provides us with the push() function that saves data under a unique system generated key. This method ensures that if multiple writes are being performed to the same key, they do not overwrite themselves. For example, if multiple sources try to make a write at /Books/Best_Sellers/ then whichever source makes the last write, that value will persist in the database. This introduces the possibility that data will be overwritten. push() solves this issue by using unique keys for each new child that's added. ref = db.reference("/") ref.set({ "Books": { "Best_Sellers": -1 } }) ref = db.reference("/Books/Best_Sellers") import json with open("book_info.json", "r") as f: file_contents = json.load(f) for key, value in file_contents.items(): ref.push().set(value) Please note that push() and set() aren't atomic. This means that there is no guarantee that both functions will execute together without interruption as a single indivisible unit. Whilst the database is being updated, if we try to fetch the data, it may happen that push() has finished but set() hasn't – so the JSON we receive will have a system generated key without a value field. How to Update Your Firebase Database Using Python Updating the database is as simple as setting the reference at the required point and using the update() function. Let's say that the price of the books by J. R. R. Tolkien is reduced to 80 units to offer a discount. ref = db.reference("/Books/Best_Sellers/") best_sellers = ref.get() print(best_sellers) for key, value in best_sellers.items(): if(value["Author"] == "J.R.R. Tolkien"): value["Price"] = 90 ref.child(key).update({"Price":80}) How to Retrieve Data from Firebase Using Python We have already retrieved data using the get() method when we were trying to update a particular key. Now we'll see a few more methods and club them together to make complex queries. Let's get all books in order sorted by price using the order_by_child() method. To apply this method, we have to first set the key by which we are ordering as the index field via .indexOn rule in Firebase Security rules. If we want to sort by price, then price must be listed as the index. You can set the value like this: ref = db.reference("/Books/Best_Sellers/") print(ref.order_by_child("Price").get()) The return value of the method is an OrderedDict. To order by key, use order_by_key(). To get the book with maximum price, we use the limit_to_last() method as follows: ref.order_by_child("Price").limit_to_last(1).get() Alternatively, to get the least priced book, we write this: ref.order_by_child("Price").limit_to_first(1).get() To get books that are exactly priced at 80 units, we use this: ref.order_by_child("Price").equal_to(80).get() For more examples and methods to query the database as per your requirements, check out the official documentation here. How to Delete Data from Firebase Using Python Deleting data is pretty simple. Let's delete all best seller books with J.R.R. Tolkien as the author. ref = db.reference("/Books/Best_Sellers") for key, value in best_sellers.items(): if(value["Author"] == "J.R.R. Tolkien"): ref.child(key).set({}) Conclusion In this post, we learned how to create a Firebase Realtime database, populate it with data, and delete, update and query the data using Python. I hope this helps a Python developer out there who's just discovered the beauty of Firebase but is feeling overwhelmed with so many different options and methods to choose from. If you've read this far, thank you so much! Take care, and happy coding!
https://www.freecodecamp.org/news/how-to-get-started-with-firebase-using-python/
CC-MAIN-2021-21
refinedweb
1,276
65.01
The code works for 26 cases but can't pass the rest 2.One failing test: x=104659,y=104677,z=142424 Don't know why.The idea is simple. We're given a small jar and a large jar, we start from filling the larger full, and pour water into smaller until the smaller one gets totally filled.Then we empty the smaller and keep filling it using the water remaining in the larger one;if the remaining water in the larger one isn't enough for totally filling the smaller, we empty the larger one by pouring the remaining water into smaller , then refill the larger until full,and fill the smaller one like above. We use a variable "large" to denote water amount in the larger.For each loop we check if "large" is the amount desired, if it is we return TRUE; if "large" is already in a HashSet, that means we've once come to this point and this it's infinite loop(we'll come to this existing amount again if we keep doing this),so return FALSE; if it's neither TRUE nor FALSE, we save "large" in the HashSet, update "large" in the larger to be ready for next loop. Anyone can help I truly appreciate it!! public class Solution{ public boolean canMeasureWater(int x,int y,int z){ if(x<y){ return canMeasureWater(y,x,z); } //x denote container with larger capacity,y denote the one with smaller capacity if(x+y==z||x==z||y==z){ return true; }else if(x+y<z){ return false; }else{ HashSet<Integer> set=new HashSet<Integer>(); int larger=x; while(true){ if(larger==z){ return true; }else if(set.contains(larger)){ return false; }else{ set.add(larger); if(larger>=y){ larger=larger-y; }else{ larger=x-(y-larger); } } } } } } Sorry I forgot to mention the result.Pretty new to Leetcode. OJ says wrong answer, passed 26 tests and failed 2. The failed on is x=104659,y=104677,z=142424.OJ says this test should've return True while mine return False. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/49169/2-test-cases-can-t-be-passed-was-using-a-hashset-anybody-can-help
CC-MAIN-2017-39
refinedweb
363
61.16
On building with Unity, I am getting an error: trouble writing output: Too many method references: 78849; max is 65536. You may try using --multi-dex option. Similar to this post I am having issues with enabling multidex for android builds. I am extending MultiDexApplication with my own Application as follows: import android.support.multidex.MultiDexApplication; public class MyApplication extends MultiDexApplication { } and referenced from my AndroidManifest as follows <application android:debuggable="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android: But I can't figure out how to explicitly tell Unity to use multi dex. Again referencing this post, Liortal mentioned that Unity is "hard-wired" this way, and it cannot be resolved. I was wondering if this is truly the case? Does it require moving compilation out of Unity into Eclipse? Or can everything be done from inside Unity? If it can be done from Unity, how? Would proguard work better? Does that require moving into Eclipse also? Anyone found a simple solution for this? Is it needed to build the android project, use Eclipse and mess with Gradle-settings etc..? I have the same problem... any solution to this? Has anyone solved this issue yet? Any updates on this topic? Answer by turdann · May 19, 2015 at 01:44 PM No, I finally had to clean the project... taking off some big sdk's. I'd like to know another solution, but for the moment this is the best one. Answer by BigToe · Nov 20, 2015 at 06:57 AM Google changed their native play-game-services plugin to use AAR files instead of one huge .jar. This reduces the method calls and should allow you. Failed to compile Java code to DEX; Invalid command dx 0 Answers Unity project wont build 0 Answers Using Pragma to slit app in two 1 Answer What is Javascript dynamic typing and type inference on initialization? 2 Answers Configuration with name 'compileClasspath' not found - ANDROID 0 Answers
https://answers.unity.com/questions/849776/enable-multidex-for-android-build.html?sort=oldest
CC-MAIN-2020-40
refinedweb
327
59.09
Pavel Machek a écrit :> Can you try cat /proc/acpi/sleep? If there's no difference between S4> and S4bios, than you are probably just using plain S4...puligny:~% cat /proc/acpi/sleepS0 S1 S3 S4 S4bios S5Where am I suppose to see a difference between S4 and S4Bios here ? From what I see in acpi_system_write_sleep in drivers/acpi/sleep/proc.c4 uses software_suspend while 4b uses acpi_suspend(4)(SOFTWARE_SUSPEND is set in my .config)Is this code the right one ? /* Check for S4 bios request */ if (!strcmp(str,"4b")) { error = acpi_suspend(4); goto Done; } state = simple_strtoul(str, NULL, 0);#ifdef CONFIG_SOFTWARE_SUSPEND if (state == 4) { error = software_suspend(); goto Done; }#endif error = acpi_suspend(state);> Yes, but it will take quite long to do it properly. pm_message_t> framework needs to go in, first.Ok, great! I'll be happy to test it soon :)Brice-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2005/3/5/188
CC-MAIN-2017-04
refinedweb
170
66.64
Use of variables in MainWindow.h Under class MainWindow : public QMainWindow, I have : class MainWindow : public QMainWindow { Q_OBJECT // Macro Meta Object Compiler QString Roger = "Roger"; static bool isMeasureCompleted; static bool isCcalibrationFailed; static bool isMeasureWait; static bool isMeasureFailed ; static bool isDisConnect; // static bool bWhiteCalibFlag; and a few other static members. (I tried to put these flags elsewhere to no avail -- I'm open to suggestions!) But I boiled it down to the compiler rejecting ALL my variables OR rejecting ONLY one of them? You see the last flag, bWhiteCalibFlag? As it stands, it gives me this error : But if I remove the comment and Build again, all my flags become "undefined"? I've been at this all day... - Kent-Dorfman last edited by static variables in class declarations are just that...declarations. they are undefined becuase you didn't define them in the cpp file. bool MainWindow::bWhiteCalibFlag = false; The difference between declaration and definition. Suppose I create a brand new GUI Widget project. I inherit a main.cpp, a project.cpp and a project.h. The header is the place where I should declare my static variables, right? Let's stick with the same variable, static bool bWhiteCalibFlag. First of all, where would be the logical place to declare it? I drew an arrow where I believe (I'm only a beginner Qt and c++ programmer) I would logically declare it, in the public section, like this : Does this make any sense, so far? Let's say this is acceptable. Next, as you say, is to define it in the cpp file, right? The question is where? This is my project.cpp : My "intuition" tells me the variable should be defined within the constructor scope, does that make any sense? Like this : So far, so good? Now, suppose I place a pushButton in my interface, like this : And then, "Go to Slot" > Clicked, insert an if statement based on the status of this flag, I get "undefined reference" : - Christian Ehrlicher Lifetime Qt Champion last edited by Christian Ehrlicher Basic C++ - when you declare a static variable you also have to define it somewhere so the memory gets allocated --> Apart from this - why must this variable be static? - RogerBreton last edited by RogerBreton I think I "understand" a little bit of what is going on... I removed the keyword static in the declaration of the variable, in the header file. When I built the application, the error disappeared. I was reading, last night, that, in order to use static member variables inside a function, the function itself HAS to be static also? (it took a lot of google search to figure this one out) That would explain why the error disappeared in this case. The whole reason I wanted to work with static variables lies in the "origin" of this new GUI Widget application I would like to develop? You see, originally, this "project idea" started as a Console application written in c++ under VS2019. It's not even 100 lines, in all? But it is being made complicated by the fact that it "interfaces" to a USB device called a "colorimeter". I was given the SDK (which I'm under NDA for) for this device by the manufacturer. The little console application I wrote successfully interfaced with the device through its various DLL calls. Could not be happier! In QT Creator, I first tried to re-create the same Console application I created in VS2019 but I was not successful, because the Linker could not find the DLL functions ("Unresolved External References" errors)? Which, considering my relative technical ignorance, made me abandon the project and look at C++ Builder and MFC... (there are only so many hours I can throw at this project) But later, I discovered the idea of "Explicit Linking" (to work around the darn Unresolved External References (if you can't beat them, join them!) and started experimenting with Qlibrary. It took a lot of work but I was able to write some typedef in my Qt GUI Widget project that allowed me to gain access to all the DLL functions. That was quite a milestone! The trouble is that there are some "flags" I need to carry with me, in this application, such as bWhiteCalibFlag, which need to be used by various functions and are not part of the DLL, they have to be my implementation? Not knowing Qt at all, naively, I thought about adding all these flags to the MainWindow class, so that, I thought, their values would be accessible from all member functions? But that did not work. Fast forward to many Aspirins later... There is ONE overriding particular DLL function I need to create, in my application, it is the DeviceEventHandler function, called "void EventNotice(params)". In the Console application, it sits below main() and is being called by the device as its various functions complete. It is "registered" at the beginning of the application. I guess it must be supplying the address of the EventNotice function to the DLL? In my GUI Widget application, I tried to locate the declaration / definition of the EventNotive function at different places in the code, and the only place it "worked" was inside the MainWindow class, as a public member function. Since this function only needs to exist "once" in memory, I made it static. (I don't dare post pages and pages of code?) I got to a point, last night, where I was able to fire a button in the interface, and in the slot code, I was able to Load the DLL (Qlibrary), resolved the functions addresses using typefefs and successfully call the EventNotice function. But that's when troubles started... Why? Because I could not situate the "LoadDLL" call independently of any buttons? I could not situate the typedefs that access the DLL functions independently of any buttons and yet they have to be accessible from anywhere in my code, any buttons? I need buttons to Initialize the device, to Calibrate the device and to Take measurements through the device, and each of these functions need access to the DLL functions. I tried to create a 'Device' class from where I would access the device, but I did not get very far because it was not working... I went to bed at 2 am, trying to solve the problem but I'm really not an expert in c++ or OOP, as you can see. I was looking through the Examples and thought, perhaps, that my application resembled the 'Camera Example' since it's got 'Initialization' and other similar functions like 'Take a picture' and so on? I stumbled upon this QscopePointer notion that is used in the 'Camera Example', which, intuitively, tells me may help? Which, possibly, as far as I could see in the Example code, would provide some sort of "central location" for the device, to allow accessing it from anywhere in the code? Please excuse my newbie questions... but it's not easy to find examples from which to build my application... YouTube and the Qt site are full of "basic" GUI Widget examples but nothing which explains the "approach" I need to take in my case.... I thought about going back to my Console application and stick with menu commands but that would be "throwing the towel" :( - Christian Ehrlicher Lifetime Qt Champion last edited by @RogerBreton said in Use of variables in MainWindow.h: the function itself HAS to be static also? (it took a lot of google search to figure this one out) That would explain why the error disappeared in this case. This is completely wrong and I already explained why the error occurs. I would suggest a good c++ book first before starting with Qt. I would have hope you could have offered some suggestions or ask simple fragen zum meine humble projekt, to help, instead of openly criticize me and send me back to read programming books. Know that alles der gut c++ programming books I have had the chance to read nicht cover "Qt" und never cover device interface oder DLL loading mit resolve function names mit typedefs... I have spent a great deal of time BEFORE coming back for more help here. - stretchthebits last edited by @RogerBreton Don't worry, I will tell you what to do. If you still want to use static variables in your class like in your initial post, this is the way to do it. //THIS GOES IN YOUR .H file class SomeClassName { //Making it public, private, protected does not matter. These are just language side concepts. static int variable; static int SuperArray[1000]; void function(); static void function2(); <--------notice the word static }; //THIS GOES IN YOUR .CPP file //Put this after your #include directives. int SomeClassName::variable=0; int SomeClassName::SuperArray[1000]; You can use those variables in function() and function2(). Be careful when making multiple instances of SomeClassName. There would be only one copy of variable and SuperArray that all your instances will share. Anything else? @stretchthebits Thank you for your suggestions :-) I feel I'm making progress. In mainwindow.h, I added : class SomeClassName { static int variable; static int SuperArray[1000]; static bool isMeasureCompleted; static bool isCcalibrationCompleted; static bool isCcalibrationFailed; static bool isMeasureWait; static bool isMeasureFailed; static bool isDisConnect; static uint32_km portCount; <-- mfr typedef static uint8_km StateTable[2][4]; <-- mfr typedef static char input_buf[64]; <-- mfr typedef static uint8_km dev_no; <-- mfr typedef static DDD_PortInfo portInfo[16]; <-- mfr typedef static bool bExitFlag; static bool bSelectExitFlag; static bool bWhiteCalibEndFlag; static bool bIrradianceCalibEndFlag; static bool bRadianceCalibEndFlag; static void EventNotice(DDD_eEventCode outEventCode, uint32_km outRAWDataCount, DD_ERROR_TYPES outError); <-- mfr DeviceEventHandler static void Initialize(); }; Then, in mainwindow.cpp, I added this : #include "mainwindow.h" #include "ui_mainwindow.h" int SomeClassName::variable=0; int SomeClassName::SuperArray[1000]; bool SomeClassName::isMeasureCompleted=false; bool SomeClassName::isCcalibrationCompleted=false; bool SomeClassName::isCcalibrationFailed=false; bool SomeClassName::isMeasureWait=false; bool SomeClassName::isMeasureFailed=false; bool SomeClassName::isDisConnect=false; bool SomeClassName::bExitFlag=true; bool SomeClassName::bSelectExitFlag=true; bool SomeClassName::bWhiteCalibEndFlag=false; bool SomeClassName::bIrradianceCalibEndFlag=false; bool SomeClassName::bRadianceCalibEndFlag=false; uint32_km portCount; char input_buf[64]; uint8_km dev_no; DDD_PortInfo portInfo[16]; uint8_km StateTable[2][4] = { "Eth", "USB" }; When I build the project, I get this "weird" error : The variable is declared in the .H file and defined in the .CPP file, yet, the compiler does not "recognize" it: Yesterday night, at 2 am, as soon as I deleted this variable, ALL HELL BROKE LOOSE. So I don't dare deleting it yet..... Things are slowly sinking in... Experimenting with the above error message... This code is executing inside a "member function" : ... Incidently, I was listening to someone explaining that static variables did NOT need to be instantiated? Slowly... So, I experimented with the SuperArray variable and could was able to conclude that they couldn't be use inside my member function... This is going to be interesting, in terms of "conceptual understanding" -- thank you all for your patience and help. It took me a while but I didn't think it was a "lost cause". I tried first creating a "function" that would allow me to access the variable from outside the member function? I would pass this function the variable and in the body of that function, I would merely assign the value to the 'private" variable. But the compiler did not let me play that game? ... Then I "reasoned" that's what 'getters' and 'setters' are for? But then, looking at some example on the internet, it dawn on me that my SomeClass declaration did not have any 'scope qualifier' (I'm not sure that's how they're called, technically?) but it dawn on me, at that point that, what about adding a public: keyword before the declaration of all those flags? That sounded almost too easy to be true? This is what I did : See? And then, tadam!, the error disappeared : Next step is to try to build and run this "monster" :-) @RogerBreton In C++ class declarations if you do not write any of the public:, protected:, private:access specifiers the following variables/methods default to private. It is good practice to always type the desired specifier from the start. It is good now that you have understood what is required if you declare a member variable as static. ( staticis a bit different in C++ if you are used to it for C.) I don't claim to have read/followed all that you have written about why you are using staticabove. But my natural inclination is surprise that you want to use it. There are times, but not that often, and there has to be a particular reason. In the case of your SomeClass, for example, code can create many separate instances of that class ( SomeClassName instanceor SomeClassName *instance = new SomeClassName). But your code means that there will only be one single instance of variable, SuperArray& isMeasureCompletedshared across all those instances. They won't have their own copies of these. Why do you want that? - Christian Ehrlicher Lifetime Qt Champion last edited by @RogerBreton said in Use of variables in MainWindow.h: instead of openly criticize me and send me back to read programming books. Yes, because you lack basic c++ stuff. Sorry but your question and the strange unneeded use of static functions are c++ basic stuff (and don't even have something to do with Qt). Learn c++ first before starting with Qt since Qt is a c++ library and without basic knowledge it's impossible to use Qt properly. - stretchthebits last edited by @RogerBreton Getters and setters are a thing that C++ books recommend. Personally, I don’t strictly follow that rule because it turns the code very verbose. It’s up to you but OOP people will hate you. Sometimes, I just want to read a variable from one class and give it to another. For example: SomeClass1 a; CubeClass b; a.thing=5; b.chocolate=a.thing; Anyway, that’s up to you. In C++, by default, like JonB said, your member functions and member variable are private. Sounds like you want to declare them as public. For structs, by default, they are public. I think what you want to do is to declare an instance of SomeClassName in your MainWindow class. And then, the code becomes SomeClassName TheObject; if (SUCCESSFUL(sdkError)) { TheObject.bWhiteCalibEndFlag = true; }
https://forum.qt.io/topic/125979/use-of-variables-in-mainwindow-h
CC-MAIN-2022-27
refinedweb
2,383
62.88
Apache Beam stands for B(batch) – EAM(strEAM). Apache Beam is an open source, integrated model for both batch and streaming data-parallel processing pipelines. Using one of the Beam SDK (Java, Python and GO) which are also open source, you create a program that describes the pipeline. The pipeline is then used by one of Beam-based back-end processing systems, including Apache Flink, Apache Spark, and Google Cloud Dataflow. Beam is especially useful for embarrassing data processing tasks, where the problem can be broken down into many small amounts of data that can be processed independently and parallely. You can also use Beam for Extract, Transform, and Load (ETL) functions and pure data integration. These functions are useful for moving data between different storage media and data sources, converting data into the most desirable format, or uploading data to a new system. Apache Beam SDKs Beam SDKs provide an integrated editing model that manages and converts data sets of any size, whether input is a limited data set from a batch data source, or an infinite data set from a streaming data source. Beam SDKs use the same classes to represent both bounded and unbounded data, with the same modifications to work on that data. You can use the Beam SDK of your choice to create a program that defines your data processing pipeline. Beam currently supports : - Java SDK - Python SDK - GO SDK Apache Beam Pipeline Runners Beam Pipeline Runners translates the data processing pipeline that you define into your Beam program into an API that accompanies distributed processing. When you start your Beam program, you will need to specify a runner which suits your needs when you want to use your pipeline. Beam currently supports the following runners: - Direct Runner - Apache Spark Runner - Apache Flink Runner - Google Cloud Dataflow Runner - Apache Flink logo - Google Cloud Dataflow logo - Apache Nemo Runner - Hazelcast Jet logo - Twister2 logo - Apache Samza Runner - Apache Samza logo - Twister2 Runner - Hazelcast Jet Runner - Apache Spark logo Apache Beam Model. Apache Beam Environment Setup Requirements - Java JDK 8, 11 or 17 . - Maven - An IDE such as Intellij or Eclipse. First Apache Beam Project using Java SDK 1) Open an IDE (we would use Intellij), and create a new Project 2) Go to POM.xml file and add dependencies for beam-sdk and beam-runner 3) we will now convert a .txt document to a .docx document using Apache Beam 4) Create a class named BeamDemoRunner , with the following java code import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.values.PCollection; public class BeamDemoRunner { public static void main(String[] args) { //create a Pipeline object Pipeline pipeline=Pipeline.create(); //creating a PCollection object which represents a distributed data set //and reading a text file (.txt) PCollection<String> output=pipeline.apply( TextIO.read().from("/home/prakhar/BeamPOC/input/sample-text-file-input.txt") ); //converting the text file into a word document (.docx) output.apply( TextIO.write().to("/home/prakhar/BeamPOC/output/sample-text-file-output.docx") //if wont use withNumShards , as I told, PCollection is a distibuted set //it will output multiple files instead of 1 single file .withNumShards(1) //to generate a file with extension .docx .withSuffix(".docx") ); pipeline.run(); } } 5) After running the above program , check the output folder 6) Output.docx Github link for the above Demo : Knoldus Blogs : References : Official Apache Beam Github: Official Apache Beam Documentation:
https://blog.knoldus.com/apache-beam-the-java-sdk-way/
CC-MAIN-2022-21
refinedweb
573
53.31
snd_mixer_routes() Get the number of routes in the mixer and their IDs Synopsis: #include <sys/asoundlib.h> int snd_mixer_routes( snd_mixer_t *handle, snd_mixer_routes_t *routes ); Arguments: - handle - The handle for the mixer device. This must have been created by snd_mixer_open() . - routes - A pointer to a snd_mixer_routes_t structure that snd_mixer_routes() fills in with information about the routes. Library: libasound.so Use the -l asound option to qcc to link against this library. Description:. We recommend that you work with mixer groups instead of manipulating the elements directly. Before calling snd_mixer_routes(), set the members of this structure as follows: - proutes - This pointer must be NULL, or point to a valid storage location for the routes (i.e. an array of snd_mixer_eid_t structures). - routes_size - The size of this storage location in sizeof( snd_mixer_eid_t ) units (i.e. the number of entries in the proutes array). On a successful return, the function sets these members: - routes - The total number of routes in the mixer. - routes_over - The number of routes that couldn't be copied to the storage location. - proutes - The list of routes. Returns: Zero on success, or a negative value on error. Errors: - -EINVAL - Invalid handle. Classification: QNX Neutrino
http://developer.blackberry.com/playbook/native/documentation/com.qnx.doc.neutrino.audio/topic/libs/snd_mixer_routes.html
CC-MAIN-2014-15
refinedweb
193
68.06
Time for another Frankenstein post. This time we are going to combine the following: The end result is going to be a Cubic Hermite Rectangle Surface like the below. Note that the curve only passes through the inner four control points, and the outer ring of 12 control points are used to determine the slope. Just like the cubic hermite curve counterpart, a cubic hermite rectangle surface is C1 continuous everywhere, which is great for use as a way of modeling geometry, as well as just for interpolation of multidimensional data. In the image below, each checkerboard square is an individual hermite rectangle. The links section at the bottom has links to the shadertoys I made that I got the screenshots from. Code Here’s some C++ code that does bicubic hermite interpolation #include <stdio.h> #include <array> typedef std::array<float, 4> TFloat4; typedef std::array<TFloat4, 4> TFloat4x4; const TFloat4x4 c_ControlPointsX = { { { 0.7f, 0.8f, 0.9f, 0.3f }, { 0.2f, 0.5f, 0.4f, 0.1f }, { 0.6f, 0.3f, 0.1f, 0.4f }, { 0.8f, 0.4f, 0.2f, 0.7f }, } }; const TFloat4x4 c_ControlPointsY = { { { 0.2f, 0.8f, 0.5f, 0.6f }, { 0.6f, 0.9f, 0.3f, 0.8f }, { 0.7f, 0.1f, 0.4f, 0.9f }, { 0.6f, 0.5f, 0.3f, 0.2f }, } }; const TFloat4x4 c_ControlPointsZ = { { { 0.6f, 0.5f, 0.3f, 0.2f }, { 0.7f, 0.1f, 0.9f, 0.5f }, { 0.8f, 0.4f, 0.2f, 0.7f }, { 0.6f, 0.3f, 0.1f, 0.4f }, } }; void WaitForEnter () { printf("Press Enter to quit"); fflush(stdin); getchar(); } // t is a value that goes from 0 to 1 to interpolate in a C1 continuous way across uniformly sampled data points. // when t is 0, this will return p[1]. When t is 1, this will return p[2]. // p[0] and p[3] are used to calculate slopes at the edges. float CubicHermite(const TFloat4& p, float t) { float a = -p[0] / 2.0f + (3.0f*p[1]) / 2.0f - (3.0f*p[2]) / 2.0f + p[3] / 2.0f; float b = p[0] - (5.0f*p[1]) / 2.0f + 2.0f*p[2] - p[3] / 2.0f; float c = -p[0] / 2.0f + p[2] / 2.0f; float d = p[1]; return a*t*t*t + b*t*t + c*t + d; } float BicubicHermitePatch(const TFloat4x4& p, float u, float v) { TFloat4 uValues; uValues[0] = CubicHermite(p[0], u); uValues[1] = CubicHermite(p[1], u); uValues[2] = CubicHermite(p[2], u); uValues[3] = CubicHermite(p[2], u); return CubicHermite(uValues, v); } int main(int argc, char **argv) { // how many values to display on each axis. Limited by console resolution! const int c_numValues = 4; printf("Cubic Hermite rectangle:n"); for (int i = 0; i < c_numValues; ++i) { float iPercent = ((float)i) / ((float)(c_numValues - 1)); for (int j = 0; j < c_numValues; ++j) { if (j == 0) printf(" "); float jPercent = ((float)j) / ((float)(c_numValues - 1)); float valueX = BicubicHermitePatch(c_ControlPointsX, jPercent, iPercent); float valueY = BicubicHermitePatch(c_ControlPointsY, jPercent, iPercent); float valueZ = BicubicHermitePatch(c_ControlPointsZ, jPercent, iPercent); printf("(%0.2f, %0.2f, %0.2f) ", valueX, valueY, valueZ); } printf("n"); } printf("n"); WaitForEnter(); return 0; } And here’s the output. Note that the four corners of the output correspond to the four inner most points defined in the data! On The GPU / Links While cubic Hermite rectangles pass through all of their control points like Lagrange surfaces do (and like Bezier rectangle’s don’t), they don’t suffer from Runge’s Phenomenon like Lagrange surfaces do. However, just like Lagrange surfaces, Hermite surfaces don’t have the nice property that Bezier surfaces have, where the surface is guaranteed to stay inside of the convex hull defined by the control points. Since Hermite surfaces are just cubic functions though, you could calculate the minimum and maximum value that they can reach using some calculus and come up with a bounding box by going that direction. The same thing is technically true of Lagrange surfaces as well for what it’s worth. Check out the links below to see cubic Hermite rectangles rendered in real time in WebGL using raytracing and raymarching: Shadertoy: Cubic Hermite Rectangle Shadertoy: Infinite Hermite Rectangles
https://blog.demofox.org/2015/08/09/cubic-hermite-rectangles/
CC-MAIN-2021-21
refinedweb
697
60.75
kke (Kimmo Lehto) - Login: kke - Registered on: 05/12/2017 - Last connection: 08/09/2019 Issues Activity 08/22/2019 12:01 PM Ruby master Feature #16115 (Open): Keyword arguments from method calls or ignore extra hash keys in splat - Just a thought, feel free to insta-close as stupid. Currently you can do this: ``` def hello(who:) puts "He... 08/09/2019 07:36 AM Ruby master Bug #16086 (Closed): OpenStruct method access with a block does not raise - 07:36 AM Ruby master Bug #16086: OpenStruct method access with a block does not raise - > That is OpenStruct, an undefined key does not raise an exception. > And an unused block is silently ignored in com... 08/08/2019 08:56 AM Ruby master Bug #16086 (Closed): OpenStruct method access with a block does not raise - This can cause confusion. ```ruby > OpenStruct.new(hello: 'world').each { |k, v| puts k.upcase } # there's no "... 06/14/2019 07:30 AM Ruby master Feature #15899: String#before and String#after - How about `first` and `last`? ```ruby 'hello world'.first(2) => 'he' 'hello world'.last(2) => 'ld' 'hello w... 06/06/2019 07:00 AM Ruby master Feature #15899: String#before and String#after - > Using partition looks reasonable, and it can accept regexes. It also has the problem of creating extra objects t... 06/05/2019 07:27 AM Ruby master Feature #15899 (Open): String#before and String#after - There seems to be no methods for getting a substring before or after a marker. Too often I see and have to resort... 03/06/2019 01:20 PM Ruby master Bug #15644 (Assigned): ThreadsWait problems with Thread#report_on_exception - Using ThreadsWait with Thread.report_on_exception is confusing. ThreadsWait spawns a new thread for waiting on a t... 02/14/2019 08:34 AM Ruby master Feature #15538: Erb indenting / unindenting - Perhaps `<%~` would be good as it resembles the squiggly heredoc `<<~EOB` I'll try to improve on your PoC. It s... 02/08/2019 01:05 PM Ruby master Bug #15596 (Rejected): Kernel.warn without arguments should do the same as Kernel.warn(nil) - Kernel.warn without arguments does not print an empty line to $stderr. This is inconsistent with `Kernel.puts` and...
https://bugs.ruby-lang.org/users/12676
CC-MAIN-2020-10
refinedweb
369
66.13
Mouse position tracking outside HTML5 Canvas Hello, I have some adjustment dials (rotating knobs) which are adjusted by mouse dragging. On HTML5 windowed target mouse position outside Canvas is not updated (reading mouse.x or mouse.screenX). What should I do to get that position? Flash can do it and as far as I can tell pure HTML5 js also can. Is this implemented in HaxeFlixel? To clarify: Compile target: HTML5 fixed size window in a browser on Desktop Problem: After pressing left mouse button in canvas area user drags mouse to position/change certain elements on canvas. It should be done in whole browser window even when mouse pointer leaves canvas element. I did find solution at least for mouse position, not sure yet about onmouseup. And it continues to register events (FlxG.log.add) even when focus of the browserwindow is lost. This should be takencare of. If someone is interested: #if html5 import js.Browser; Browser.document.onmousemove = DOMmouseMove; public function DOMmouseMove(e:Dynamic) { // Here you can register e.screenX, e.pageX, e.clientX ... in whole Browser window // Since I need relative mouse position while dragging, any of these are good for me (some of them change direction on multi monitor setup) } #end
http://forum.haxeflixel.com/topic/408/mouse-position-tracking-outside-html5-canvas/1
CC-MAIN-2019-26
refinedweb
206
58.38
. Here.) To make things really work there, someone needs to take charge and unify everyone, sort of like DBI did for databases and LWP did for many of the net interfaces. What you really care about is the transaction, not the institution, really. If I wanted to interact with four banks (and I do), I want to use the same script. That stuff aside, I think in your case you can't escape having the bank name in the module name, because that's how people think about it. If Citibank disappears, for instance, Finance::...::Citibank probably won't be useful anymore anyway, whereas in my example Netscape lived on in other things. As a PAUSE admin, in these cases I just follow the precedent. This isn't my name, but it is nevertheless regrettable. Often I find CPAN module functionality under module names that I wouldn't immediately have guessed, but as quickly as I stumble across such modules I forget my frustration and just go on using them. But the Base/base issue bugs me. Dave Shouldn't it be Acme::Strangulation::Remote? Seems more in keeping with the general-to-specific idea of name spaces... Take a look at Tie::Static which is one of your "outright badly named" modules. But take a closer look at it and tell me the better name that it should have, noting carefully that it handles scalars, arrays and hashes. And here we see why broadly-offered criticism is risky. On the contrary I specifically mentioned that there would be a few such modules included in the "bad list": And there are probably a few in there that cant be better named because they have some special extra property, but even still I think the namespace is a just a big mess. So I think I preemptively resolved this point. Anyway, IMO that module should be named Tie::Any::Static or something along those lines. In fact, in my eyes the fact you cant tell that module can handle any type of tie just by looking at the name says to me its badly named.... That. It's such a bad name because it assumes it is THE parser for XML, and it's just not. So people download it thinking it's the best interface to parsing XML in perl, and it's not. Still, it was the best at the time, if only because it was the first expat-based parser.. I think you might find that there are some people who disagree with you .
https://www.perlmonks.org/?node_id=371631
CC-MAIN-2019-43
refinedweb
426
70.53
Hi, ive been programming c++ (up from C) for two days now, and i want to use a class in a dll. Right now im just using the skeleton dll provided by dev-cpp with an add function in there, so i hope i havent stuffed up what i did change. and then my executable codeand then my executable codeCode:/* Replace "dll.h" with the name of your header */ #include "dll.h" #include <windows.h> DllClass::DllClass() { } int DllClass::add(int a, int b) { return(a + b); } DllClass::~DllClass () { }; } which i also copied for the most part off the net, so i hope i didnt stuff this up either.which i also copied for the most part off the net, so i hope i didnt stuff this up either.Code:#include <iostream> #include <windows.h> typedef int (*AddFunc)(int,int); using namespace std; int main(int argc, char *argv[]) { AddFunc _AddFunc; HINSTANCE hInstLibrary = LoadLibrary("dllLoadingTestdll.dll"); if (hInstLibrary == NULL) { printf("o o"); FreeLibrary(hInstLibrary); } _AddFunc = (AddFunc)GetProcAddress(hInstLibrary, "DllClass::add"); if ((_AddFunc == NULL)) { printf("O O"); FreeLibrary(hInstLibrary); } //printf("%d\n", _AddFunc(23, 43)); getchar(); FreeLibrary(hInstLibrary); return(0); } anyway, what i want to know is how to get the function address for my add function. _AddFunc == NULL is returning true, and its ouputting "O O" so thats where the problem is.
http://cboard.cprogramming.com/cplusplus-programming/90985-loading-dll-classes.html
CC-MAIN-2015-35
refinedweb
222
62.17
Provided by: maildir-utils_1.0-6_amd64 NAME mu_server - the mu backend for the mu4e e-mail client SYNOPSIS mu server [options] DESCRIPTION mu server starts a simple shell in which one can query and manipulate the mu database. The output of the commands is terms of Lisp symbolic expressions (s-exps). mu server is not meant for use by humans; instead, it is designed specifically for the mu4e e-mail client. In this man-page, we document the commands mu server accepts, as well as their responses. In general, the commands sent to the server are of the form cmd:<command> [<parameters>]* where each of the parameters is prefixed by their name and a colon. For example, to view a certain message, the command would be: cmd:view docid:12345 Parameters can be sent in any order, and parameters not used by a certain command are simply ignored. OUTPUT FORMAT mu). COMMAND AND RESPONSE add Using the add command, we can add a message to the database. -> cmd:add path:<path> maildir:<maildir> <- (:info add :path <path> :docid <docid>) compose Using the compose command, we get the (original) message, and tell what to do with it. The user-interface is then expected to pre-process the message, e.g. set the subject, sender and recipient for a reply message. Messages of type 'new' don't use the docid: parameter, the other ones do. -> cmd:compose type:<reply|forward|edit|new> [docid:<docid>] <- (:compose <reply|forward|edit|new> :original <s-exp> :include (<list-of-attachments)) The <list-of-attachments> is an s-expression describing the attachments to include in the message; this currently only applies to message we are forwarding. This s- expression looks like: (:file-name <filename> :mime-type <mime-type> :disposition <disposition>) contacts Using the compose command, we can retrieve an s-expression with all known contacts (name + e-mail address). For the details, see mu-cfind(1). -> cmd:contacts [personal:true|false] [after:<time_t>] <- (:contacts ((:name abc :mail foo@example.com ...) ...) extract Using the extract command we can save and open attachments. -> cmd:extract action:<save|open|temp> index:<index> [path:<path>] [what:<what> [param:<param>]] If the action is 'save', the path argument is required; the attachment will be saved, and a message <- (:info save :message "... has been saved") is sent. If the action is 'open', the attachment will saved to a temporary file, after which it will be opened with the default handler for this kind of file (see mu- extract(1)), and a message <- (:info open :message "... has been opened") is sent. If the action is 'temp', the arguments 'what' is required. The attachment will saved to a temporary file, and the following message is sent: <- (:temp :what <what> :param <param :docid 12345) The front-end can then take action on the temp file, based on what :what and :param contain. mu4e uses this mechanism e.g. for piping an attachment to a shell command. find Using the find command we can search for messages. -> cmd:find query:"<query>" [threads:true|false] [sortfield:<sortfield>] [reverse:true|false] [maxnum:<maxnum>] The query-parameter provides the search query; the threads-parameter determines whether the results will be returned in threaded fashion or not; the sortfield- parameter (a string, "to", "from", "subject", "date", "size", "prio") sets the search field, the reverse-parameter, if true, set the sorting order Z->A and, finally, the maxnum-parameter limits the number of results to return (<= 0 means 'unlimited'). First, this will return an 'erase'-sexp, to clear the buffer from possible results from a previous query. <- (:erase t) This will return a series of 0 up to <maxnum> s-expression corresponding to each message found (if there's no maxnum, all results will be returned). The information message s-exps this function returns do not contain the message body; the view command is for that. <- (...) and finally, we receive: <- (:found <number-of-matches>) guile The guile command is reserved for future use. index Using the index command, we can (re)index the database, similar to what mu find does. The my-addresses parameter (optionally) registers 'my' email addresses; see the documentation for mu_store_set_my_addresses. -> cmd:index path:<path> [my-addresses:<comma-separated-list-of-email-addresses>] As a response, it will send (for each 1000 messages): (:info index :status running :processed <processed> :updated <updated>) and finally: (:info index :status complete :processed <processed :updated <updated> :cleaned-up <cleaned-up>) mkdir Using the mkdir command, we can create a new maildir. -> cmd:mkdir path:<path> <- (:info mkdir :message "<maildir> has been created") move Using the move command, we can move messages to another maildir or change its flags (which ultimately means it is being move to a different filename), and update the database correspondingly. The function returns an s-exp describing the updated message, so that it can be updated in the user interface. -> cmd:move docid:<docid>|msgid:<msgid> [maildir:<maildir>] [flags:<flags>] <- (:update <s-exp> :move t) One of docid and msgid must be specified to identify the message. At least one of maildir and flags must be specified. ping The ping command provokes a pong response. It is used for the initial handshake between mu4e and mu server. -> cmd:ping <- (:pong "mu" :version <version> :doccount <doccount>) remove Using the remove command, we can remove the message from disk, and update the database accordingly. -> cmd:remove docid:<docid> <- (:remove <docid>) view Using the view command, we can retrieve all information (including the body) of a particular e-mail message. If the optional parameter extract-images is true, extract images to temp files, and include links to them in the returned s-exp. If the optional parameter use-agent is true, try to use gpg-agent when verifying PGP/GPG message parts. If the optional parameter auto-retrieve-key is true, attempt to retrieve public keys online automatically. -> cmd:view docid:<docid>|msgid:<msgid> [extract-images:true] [use-agent:false] [auto-retrieve-key:false] <- (:view <s-exp>) or, alternatively: -> cmd:view path:<path-to-msg> [extract-images:true] [use-agent:false] [auto-retrieve-key:false] <- (:view <s-exp>) AUTHOR Dirk-Jan C. Binnema <djcb@djcbsoftware.nl> SEE ALSO mu(1)
http://manpages.ubuntu.com/manpages/disco/man1/mu-server.1.html
CC-MAIN-2021-31
refinedweb
1,027
52.7
Flask TodoMVC: Login This is the seventh article in the Flask TodoMVC tutorial, a series that creates a Backbone.js backend with Flask for the TodoMVC app. In this article, we will add user authentication using the Flask-Security extension, focusing on setup and login. In doing so, we will define models for users and roles and discuss SQLAlchemy relationships. Previous articles in this series: - Getting Started - Server Side Backbone Sync - Dataset Persistence - Custom Configuration - Testing Todo API - SQLAlchemy Persistence login sqlalchemy Let's get started. Introduction Flask-Security is an extension that quickly adds authentication, authorization, registration and password recovery to your app. It combines several other popular Flask extensions, including: Flask-Login for authentication, Flask-Principal for role based authorization, Flask-WTF for form validation, Flask-Mail for sending registration, confirmation and reset password emails and Flask-Script for command line user management scripts. It also supports password encryption using passlib and secure key generation for token based authentication, optional account activation, and password recovery using itsdangerous. If that weren't enough, it adds a data store abstraction layer to persist and query your users and roles and automatically track user login activity and confirmation. Current supported data stores include Flask-SQLAlchemy, Flask-MongoEngine and Flask-Peewee, but you can easily create a custom store if so desired. (How about dataset?) Flask-Security makes things easy to get started, but may seem too feature rich or opinionated for some use cases. Like all Flask extensions, take what you want and leave the rest. If, at some point, you decide Flask-Security conventions are getting in the way, at the very least it's a good example of how to combine several common extensions and provide security to your app. I've found working with Flask-Security a very pleasant way to add some of the most important features common to many apps. I'd highly recommend it. OK, enough talk. Let's get this thing installed. $ pip install Flask-Security py-bcrypt Flask-Security supports password encryption but requires a backend to define the algorithm. We will use py-bcrypt so we install that as well. Let's also get the imports necessary for this article out of the way. # server.py from flask_security import ( Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required) from flask_security.utils import encrypt_password We will explain all of these imports as we progress through this article. Let's begin by defining models for users and roles. Models Flask-Security requires the addition of two models: users and roles. The user model stores login credential and optional audit information (create time, last login time, IP address, etc.) for all individuals who have access to your app. A role can be thought of as a group of users that may have elevated privileges. A user with the "admin" role would have access to the administration section of an app, a "manager" could view financial reports, etc. Roles are usually defined at the application level. You may need to provide finer grain access control, e.g. allow a manager to track time for personnel within her own department, but not have access to other departments. In this case, you would add additional models that are scoped to your department models and provide authorization with finer control. If you find yourself wanting more granular control, take a closer look at the Flask-Principal extension, the extension that Flask-Security uses to provide role based authorization. We may dive further into authorization in the future, but today we are going to focus on setting up Flask-Security and adding authentication to our todo list page. Roles Let's start with defining the role model. class Role(db.Model, RoleMixin): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True) description = db.Column(db.String) Most of this should look familiar if you followed the previous article. Roles belong to the roles table. We added a primary key id, role name (e.g. 'admin') and a human readable description. We defined the name column as unique as we will identify roles by name in our code. This is one of several options supported by SQLAlchemy when defining columns. We inherit from both db.Model and the RoleMixin we imported from Flask-Security. This may seem a little strange if you haven't seen it before. We won't get into the details, or debate the merits and pitfalls of multiple inheritance, but I do believe that mixins are a valid use case. They allow you to append functionality to an existing class hierarchy. They are also sometimes used as a "marker interface" to identify objects that could, for example, be serialized in a certain way. In this case, consider db.Model your base class and the RoleMixin a mechanism to mixin convenience methods defined outside the model hierarchy. Currently Flask-Security only mixes in __eq__ and __neq__ to define role equality based on the unique role name. Users Now, let's add our user model.')) Again, most of this is familiar. We identify the users table, define an id primary key, add columns for the email address and password and an active flag. When using Flask-Security, users are identified by email address. The email address is the login name. This same email address is used to send forgot password and confirmation emails, if those features are enabled. Only active users that identify the correct email address and password will be allowed to login. Note that you can add custom columns at will to your user model. You may, for example, want to include contact or organization hierarchy details. Flask-Security also supports optional features to confirm or track users. If you would like to enable these features, be sure to include the additional columns. We also inherit the UserMixin imported from Flask-Security. This currently mixes in all methods required by the user class of Flask-Login in addition to has_role for checking whether a user has a role identified by name or instance, and a get_auth_token method to be used for optional token based authentication. The roles attribute warrants further discussion. It is our first encounter with SQLAlchemy relationships. Relationships As we discussed, there is a relationship between users and roles. There may be more than one user with the same role, e.g. you could have multiple ninjas, rockstars and hipsters in your Web 3.0 startup. A user identifies individuals. Each individual could have zero or more roles. You, of course, are a ninja rockstar, but not all that hip (you just know what you're talking about, that's all), so you would have two roles. So a user could have several roles, and a role could be associated with multiple users. This type of relationship is known as a "Many to Many" and requires a join table that includes foreign keys to identify each side of the relationship. Since we don't want to treat this table as its own entity (modeled association), we can define the table directly. roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('role_id', db.Integer, db.ForeignKey('roles.id'))) This creates the join table necessary to create a Many to Many relationship between users and roles. We call it roles_users to reflect the relationship. (We could have called it users_roles as well, but this distinction is mostly arbitrary.) We then identify two integer columns with foreign keys to the appropriate column and table. Notice that here we used the table and column name, not the model name. Other relationships include "Many to One" or "One to Many" (depending on which side you consider holds the relationship). If you wanted to store multiple addresses for your users, and ignore or don't care that two users might share the same address, your address model would have a "Many to One" relationship with your user, and your user model would have a "One to Many" relationship with addresses. A less common relationship is "One to One". You could use this, for example, to associate a user object with a contact model. The contact could contain all contact information that make up an address book. The user could be associated with an existing contact by defining a contact_id on the user model. In this way, you could associate users to your address book, but not require all contacts to have login credentials. Take a look again at the relationship defined in the User model. roles = db.relationship( 'Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) This defines the relationship between users and roles. We are adding a roles attribute to our User model. Accessing this attribute will list all roles associated with the user. The association is to the Role model, which we identify as the first argument. We specify our join table defined above to setup the Many to Many relationship. Finally we specify a backref named users on the Roles model. This will add an attribute to any role instance that retrieves all users with the given role through a users attribute. Since we specify the backref relationship as dynamic, we will not get a list of roles, but a SQLAlchemy query that we can further filter. We could find, for example, all enabled managers by first retrieving the role and then filtering by active, i.e. manager_role.filter_by(active=True).all(). You could also specify the relationship itself as dynamic, not just the backref. See the SQLAlchemy documentation on dynamic relationships for further information. Setup With our models defined, we are finally ready to initialize the Flask-Security extension. The extension requires an app and a data store. Lucky for us, Flask-Security has built in support for Flask-SQLAlchemy. user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) The data store is initialized with our Flask-SQLAlchemy db and the user and role models we defined above. The extension is then initialized with our app and data store. We also have to update our configuration to setup password encryption and secure cookie storage. # config/default.py SECRET_KEY = u'Gh\x00)\xad\x7fQx\xedvx\xfetS-\x9a\xd7\x17$\x08_5\x17F' SECURITY_PASSWORD_HASH = 'bcrypt' SECURITY_PASSWORD_SALT = SECRET_KEY When we login to our app, Flask-Security will store the user id in a session so subsequent requests will not require a login. Flask stores all session data in a signed cookie, which requires SECRET_KEY to be configured. It is a good idea to use a random string for your secret key and change it for different installations. This example used os.urandom(24) to generate a random string. Run on your app to create your own. We also setup password encryption using bcrypt and set the salt to the secret key. We do not want to store the passwords in plain text in our user table. If anyone gains access to our database, we do not want to leak passwords associated with a user email address, especially since too many users reuse the same password across multiple sites. Since passwords are encrypted, we will never know what password the user provided simply by looking at the database. Specifying the password hash algorithm and salt is all we need to setup encryption using Flask-Security. Before we require login, we should setup a user that can login. We will add user registration in a future article, but for now, let's create a single user in init_db. def init_db(): with app.app_context(): db.create_all() if not User.query.first(): user_datastore.create_user( email='kevin@example.com', password=encrypt_password('password')) db.session.commit() Querying the user model for the first entry will return a single user or None if it does not exist. Remember, db.create_all will create any tables that do not exist, so our users and roles tables will be created the first time we start the app. If we don't yet have a user, we create one using a convenience method on the user data store. We need to commit our session since we made changes to the database. We run the method within a Flask application context. We are using encrypt_password from Flask-Security which requires a context to be setup. An application context is created by Flask automatically for each request and proxies are setup to be valid within this context. Since we are calling init_db standalone, we explicitly create an app context. We could alternatively use @app.before_first_request. Requiring login Now that we have Flask-Security initialized, the hard work is done. All we have left to do is enforce login by using the login_required decorator. @app.route('/') @login_required def index(): todos = Todo.query.all() ... Go ahead and start your app and navigate to localhost:8000. You should be redirected to the login page. Login with the credentials you setup in init_db to visit the todo list. At this point we should decorate all API endpoints with @login_required because, without that protection, anyone could still modify our database by requests to the Todo API. This is exactly what our tests are doing. We are going to delay protecting the API and fixing the tests for a future article. Our login page isn't very pretty. If you want to logout, currently you need to visit localhost:8000/logout. We will address these issues in a future article. Conclusion In this article, we added user authentication to our Todo list using Flask-Security. While doing this, we added additional models for users and roles and discussed SQLAlchemy relationships. Our app is getting a little cluttered, in the next article we will clean up a little and focus on modularization. That completes our integration of authentication from Flask-Security. If you made it this far you should follow me on Twitter and GitHub. The code is available on GitHub with tag login or compared to previous article.
http://simplectic.com/blog/2014/flask-todomvc-login/
CC-MAIN-2018-47
refinedweb
2,318
57.06
Hello I have some doubts in listveiw I have a listview with two columns, i want to add items to the first column which are given programmatically and the other column is from database... like column1 column2 abc from database def " hij " can this be done.... can any one help me out with this... I am using C# ,visual studio........ thanks in advance Post:105Points:735 Re: How to add listview items in C# Solution! I'm not sure how you want to match the programmatically added values and the db values, but you could create a new listitem for each of the database values i.e. ListItem item = new ListItem("apple",[database value]); Add the items to a collection ItemCollection.Items.Add(item); Then bind the collection to your control ListView.DataSource = ItemCollection;
https://www.mindstick.com/forum/1303/how-to-add-listview-items-in-c-sharp
CC-MAIN-2018-47
refinedweb
134
72.66
Dagobert Michelsen wrote: > Hi Jim, > > Am 10.11.2011 um 18:09 schrieb Jim Meyering: >> Dagobert Michelsen wrote: >>> I still get failing tests similar to the ones I reported in >>> >>> There doesn't seem to have been any fixing in gnulib for this since. >>> Platform is Solaris 9 Sparc with Sun Studio 12. >> ... >> >> Thanks for reporting that, again. >> If you feel like debugging it, that would be nice. >> I think I've seen the same thing on Solaris 10. >> >>>> FAIL: test-exclude2.sh (exit: 1) >>>> ================================ >>>> >>>> *** excltmp.21000 Thu Nov 10 13:38:53 2011 >>>> --- - Thu Nov 10 13:38:53 2011 >>>> *************** >>>> *** 2,6 **** >>>> foo*: 1 >>>> bar: 1 >>>> foobar: 0 >>>> ! baz: 1 >>>> bar/qux: 0 >>>> --- 2,6 ---- >>>> foo*: 1 >>>> bar: 1 >>>> foobar: 0 >>>> ! baz: 0 >>>> bar/qux: 0 > > This test checks functionality from lib/exclude.c and that file contains > >> /* Non-GNU systems lack these options, so we don't need to check them. */ >> #ifndef FNM_CASEFOLD >> # define FNM_CASEFOLD 0 >> #endif >> #ifndef FNM_EXTMATCH >> # define FNM_EXTMATCH 0 >> #endif >> #ifndef FNM_LEADING_DIR >> # define FNM_LEADING_DIR 0 >> #endif > > in Solaris 9 /usr/include/fnmatch.h does not contain FNM_CASEFOLD and > is therefore set to 0. > > That means test-exclude2.sh should not be run if FNM_CASEFOLD == 0. > >>>> FAIL: test-exclude5.sh (exit: 1) >>>> ================================ >>>> >>>> *** excltmp.21059 Thu Nov 10 13:38:54 2011 >>>> --- - Thu Nov 10 13:38:54 2011 >>>> *************** >>>> *** 1,4 **** >>>> bar: 1 >>>> ! bar/qux: 1 >>>> barz: 0 >>>> foo/bar: 1 >>>> --- 1,4 ---- >>>> bar: 1 >>>> ! bar/qux: 0 >>>> barz: 0 >>>> foo/bar: 1 > > This is similar and should not be run if FNM_LEADING_DIR == 0. > > Could you please forward this to the respective maintainers and ask if they > could adjust the testsuite accordingly? Thanks for investigating. I've pushed the following fix to gnulib; I'll update grep to use it before the release. >From 39a489fa27ab3873e0fc0f65844413f46fcb2117 Mon Sep 17 00:00:00 2001 From: Jim Meyering <address@hidden> Date: Fri, 11 Nov 2011 14:37:59 +0100 Subject: [PATCH] --- ChangeLog | 8 ++++++++ tests/test-exclude.c | 9 +++++++++ 2 files changed, 17 insertions(+), 0 deletions(-) diff --git a/ChangeLog b/ChangeLog index 0c4eff9..d35f6c6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,11 @@ +2011-11-11 Jim Meyering <address@hidden> + + + + 2011-11-10 Bruno Haible <address@hidden> ptsname_r test: Avoid gcc warning on glibc systems. diff --git a/tests/test-exclude.c b/tests/test-exclude.c index 9c7997d..47392d9 100644 --- a/tests/test-exclude.c +++ b/tests/test-exclude.c @@ -104,6 +104,15 @@ main (int argc, char **argv) exclude_options &= ~flag; else exclude_options |= flag; + + /* Skip this test if invoked with -leading-dir on a system that + lacks support for FNM_LEADING_DIR. */ + if (strcmp (s, "leading-dir") == 0 && FNM_LEADING_DIR == 0) + exit (77); + + /* Likewise for -casefold and FNM_CASEFOLD. */ + if (strcmp (s, "casefold") == 0 && FNM_CASEFOLD == 0) + exit (77); } else if (add_exclude_file (add_exclude, exclude, opt, exclude_options, '\n') != 0) -- 1.7.8.rc0.61.g8a042
http://lists.gnu.org/archive/html/platform-testers/2011-11/msg00003.html
CC-MAIN-2016-44
refinedweb
470
67.35
Chris Oliver's Weblog - All - F3 - JavaFX - Programming - Research] I agree JavaFX data binding is awesome, but did you try to write a real application ? How do you draw a table with JavaFX ? Posted by naysayer on December 28, 2008 at 11:37 PM PST # I have to agree with the previous comment. JavaFX is great speaking from a technical viewpoint. At this moment, it's also great for creating "fun" applications that look awesome, do some animations and so on. For "boring" applications that require a lot of data entry and displaying data it lacks support for decent standard components however. Posted by Paul Bakker on December 29, 2008 at 12:06 AM PST # another usefull example of binding my old example of boring office application updated for new SDK version coming soon Posted by surikov on December 29, 2008 at 02:26 AM PST # Just one question: What's so cool with your app? A _picture_ of a slider and two coloured circles? If it at least was interactive so one could move the blue circle around... Posted by Thommy M. on December 29, 2008 at 03:02 AM PST # surikov, your example is very nice, sincerely. is crudFX home made ? I'm impressed because it sizes 5Mb ! Posted by naysayer on December 29, 2008 at 05:31 AM PST # crudfx is a old version for JavaFX interpreter. Look to article date. It incledes application + runtime for old JavaFX. New version coming soon Posted by surikov on December 29, 2008 at 06:39 AM PST # See the JFXtras open-source project that helps fill in some of the gaps of the JavaFX 1.0 Release (to help with the "boring projects"). It includes support for Dialogs, Grid Layouts, Unit Testing, and an Asynchronous Worker class: Regarding how to draw a table with JavaFX, see: That is part of a series (written using JavaFX 1.0 Preview) that is currently being converted to JavaFX SDK 1.0 and is part of a series that teaches how to build custom UI elements in JavaFX: Things are beginning to move fast for the support of "boring" application, which by the way, don't have to be boring if we use the rich 2D capabilities of JavaFX. On a related note, I think that we as software developers/graphic designers should define a set of style guidelines for Enterprise RIAs (analogous to the Web 2.0 guidelines that have evolved). Please feel free to read and respond to the following article that I posted on JavaLobby a few days ago, on December 23, 2008: HTH, Jim Weaver JavaFXpert.com Posted by Jim Weaver on December 29, 2008 at 09:09 AM PST # Uh, I assumed it was clear the above was intended to demonstrate a point about programming that is intelligible to a casual reader - not to demonstrate how to build an application - whether "boring" or "cool" Posted by Chris Oliver on December 29, 2008 at 11:24 AM PST # I'm not clear on how this is better than Silverlight, where you can bind to any Property. Since Properties can act like variables or functions and include aribtrary code, where is the edge that JavaFX has? Posted by Chase Saunders on December 29, 2008 at 11:44 AM PST # I just wanted to say that I too believe that the technology behind JavaFX is superior to Flex and Silverlight at many points. It's just too bad that, even with the great technology there, it's still not usable for all types of applications that it could be usable for. It will just be a matter of time of course. And projects like JFXtras will help a lot in that process :-) Posted by Paul Bakker on December 29, 2008 at 12:48 PM PST # @Chase Saunders Hmm, I thought it was pretty clear.... Well, here's the tip of the iceberg for you: In JavaFX script any variable of any type can be bound by any expression. The binding expression language in Silverlight is degenerate compared to this. Silverlight relies on DataContexts, which must have a structural relationship to the visual scene graph - which is completely wrong. By contrast, in JavaFX script the mapping from a non-visual data model to visual elements is unrestricted. Finally, would you rather write: public static readonly DependencyProperty FillProperty; public Brush Fill { get { return (Brush) this.GetValue(FillProperty); } set { base.SetValue(FillProperty, (DependencyObject) value); } } or simply: public var fill: Paint; Posted by Christopher Oliver on December 29, 2008 at 02:14 PM PST # Simple if you know/took Trig! :) A little googling and I was able to catch up. Honestly, it being pretty simple helped Posted by Mark on December 29, 2008 at 02:42 PM PST # You should embed these examples as JavaFX applets. Posted by KPI on December 29, 2008 at 04:39 PM PST # Simple and Nice example ! Posted by Vaibhav Choudhary on December 29, 2008 at 09:09 PM PST # Tool Posted by Anthony Rogers on December 30, 2008 at 03:56 AM PST # Thanks for the follow up. I'm still not sure you can do anything with JavaFX that you can't do in Silverlight, but the Silverlight syntax sure is ugly. I haven't looked at Silverlight binding in detail, but when looking at other MS data binding solutions I'm usually impressed by their capabilities but scared off by the PITA abstractions. So this would be par for the course. It seems like one could easily write a Silverlight wrapper using lambda expressions that offers roughly equivalent ease and syntax; I wonder why MS didn't do this? Posted by Chase Saunders on December 30, 2008 at 07:51 AM PST # Hi Chris, 10x for blogging again ... It will be interesting to consider to create (and advertise) some JavaFX counterparts for more interesting examples already developed to compare (& vote for) Silverlight & Flex that you can find here: Shine Draw + Shine Draw gallery/examples Posted by El Cy on January 04, 2009 at 01:42 PM PST # How do you unbind or rebind in JavaFX ? Posted by Josselin Lebret on January 05, 2009 at 04:06 AM PST # A common scenario with Flex or JSR295 is to have a a two way binding to an attribute of an attribute of an object. Expressions like {$certainTable.selectedItem.name} allow for quick creation of CRUD interfaces - and quick CRUDs are what made FLEX and Ruby on Rails so popular and loved. As far as I understand (and I really hope to be proven wrong) JavaFX does not support such scenario. If I try and bind like this: SwingTextField { text: bind currentlySelectedPerson.name with inverse } the text will get the reference to the object that was held in currentlySelectedPerson at the time of the binding creation (quite logical, but also quite useless). I was hoping that the effect I had required could be achieved by placing currentlySelectedPerson.name in a block, like so: text: bind {currentlySelectedPerson.name} with inverse but it turns out that inverse binding is not possible for blocks. Which is also logical, but frustrating. Currently it seems to me that there is no way to change the source reference in a binding with an inverse in an elegant way. If this is really the case, JavaFX binding is, sadly, less usable than Flex and JSR295. Realizing the above made me quite depressed a couple of days ago (I'm always too emotionally invested on technology) - but maybe there is some sound workaround? What is the javafxish way to deal with scenarios like "an edit form bound to the selected element of a grid"? Posted by Filip Dreger on January 06, 2009 at 01:51 PM PST # Filip, If that doesn't work, it's a compiler bug. Please report it. F3 didn't have such bugs or limitations, and (in time) JavaFX script won't either. At a minimum any bijective expression should be bindable. Posted by Chris Oliver on January 06, 2009 at 09:28 PM PST # Thanks for the blog, Oliver. Yes, what you show is sweetness. I do wonder about how to incorporate the concept of commit or at least rollback of the binding? Say I have a value in a TextField that was created by binding it to a variable. Say I change the value in the TextField in the GUI, but then want to roll back to the original variable value. As in an undo feature. Is this currently do-able or am I missing something? Or, are we already to far down the current binding path to make that viable? Steve Posted by Steve G. on January 29, 2009 at 10:27 AM PST # depressed a couple of days ago (I'm always too emotionally invested on technology) - but maybe there is some sound workaround? What is the javafxish way to deal with scenarios like Posted by توبيكات on May 02, 2009 at 04:46 AM PDT # Simple and Nice example ! Posted by SGK Prim on May 12, 2009 at 07:43 AM PDT # thank you very Much. very good Page. Posted by çet on May 18, 2009 at 04:19 AM PDT # Posted by matbaa on June 22, 2009 at 09:59 AM PDT # Posted by دردشه on July 03, 2009 at 06:28 PM PDT # Posted by liseli on July 04, 2009 at 03:15 AM PDT #
http://blogs.sun.com/chrisoliver/entry/data_binding_in_silverlight_and
crawl-002
refinedweb
1,567
69.11
I have been a user of VMware with Dell's equallogics. An Isilon was purchased and hooked to a Cisco UCS Blade server. This datacenter where we are renting rack space has a 10 gig connection to another datacenter where we are renting rack space and also 10 gig connections between the datacenters and the Isilon is plugged into a a 10 gig backbone even though our Isilon (and I'm not that familiar with everything) has 4 1 gig connections that are supposed to load balance? The biggest issue is speed. I can transfer a 3 gig iso image to a local drive or a server in the other datacenter and I get about near 1 gig speed at about 100 MBs per second. That I can live with. However if I transfer staff files that are much much smaller in size and I try to transfer 100 gigs of data that has about 145,000 files in it the speed is about 10-20 MBs or about 10% of a standard gig connection. That happend if I tranfer a file from the share on the Isilon to the drive of an ESXi host whose datastore is also on the Isilon. On backup jobs using dedupe from the 2nd datacenter to the 1st datacenter that has the Isilon I can get about 200 MB per minute. On a backup job from a building that only has a 100 MB to the 2nd datacenter that has the Equallogics I can jam the 100 Megabit connection on a backup job. Is there something not configured right on the Isilon or is it just the nature of the beast.? thanks what kind of Isilon nodes do you have ? Load-balancing across multiple NICs works with SyncIQ, but if you're uploading data using standard NFS (including vSphere datastores) or CIFS protocols, you're restricted by the protocol architecture to a single NIC on the storage cluster. Having said that, what you're describing sounds pretty slow to me too. Besides dynamox's question, what protcocol are you using to transfer the data, and are you mounting to a 1Gb or 10Gb interface on the target node? James Walkenhorst Virtualization Solutions Architect Isilon Storage Division james.walkenhorst@emc.com James, did you mean SmartConnect ..not SyncIQ ? What I meant was that SyncIQ will transfer data between the source and target clusters using as many interfaces simultaneously as you specify, because it isn't based on either NFS or CIFS/SMB for data transfers. With NFS datastores, though, SmartConnect will balance new client connections according to whichever policy you specify, and it will rebalance connections in the event of a NIC/path failure (by rebalancing IP addresses) but it won't do a round-robin-style distribution of data streams for existing connections. iSCSI datastores can be configured to do that in vSphere, but the core NFS architecture doesn't allow for multipath connectivity. If you map an NFS datastore using a SmartConnect zone name, you're still mounting an ESXi host to a specific IP address, which in turn maps to a specific node interface on the Isilon cluster. Balancing a single NFS data stream across multiple physical paths requires pNFS, which isn't currently available in either OneFS or vSphere. I do think there might be something misconfigured in the connection between the ESXi host in one data center and the Isilon storage cluster in the other. I just can't tell what it is from the information given in the original post. Sorry for the confusion. Hope this clears things up a bit... jaw are you saying that SyncIQ could be overloading node interfaces and causing performance issues for NFS clients ? I am not following you how SyncIQ is affecting NFS performance ? Thanks I hate to answer a question with a question, but the following part of your post has me scratching my head... "That happend if I tranfer a file from the share on the Isilon to the drive of an ESXi host whose datastore is also on the Isilon." Is the ESXi host in the same datacenter as the Isilon storage cluster? Also, is the vSphere Client connection to the ESXi host also made from the same datacenter, or at least from the same side of the WAN? If not, a copy operation using the vSphere Browse Datastore functions is going to pull all the data across the WAN to the vSphere Client side from the Isilon Share and then send it all back across the WAN again to the ESXi Datastore/Isilon NFS. It also sound like you are processing the name space for 145,000 files for CIFS/SMB and then having the ESXi process the same namespace again for NFS. Finally, I have not double-checked, but I believe vSphere 5 Client connections are SSL-encrypted by default. If this is true, we also have the encapsulation and encryption overhead to account for. This does not address all of your concerns, but if we can confirm the test parameters we may be able to sort more of this out. The one test that I did was from the shared folder on the Isilon to the datastore of an ESXI host also on the same Isilon all hooked up to the same Cisco switch. I should also mention that I get the same slowness when transferring files from a physical drive on an ESXi host (I am on ESXi 5) to the another ESXi host's physical drive at the other datacenter totally bypassing the Isilon and the Dell Equallogic at the other datacenter so maybe the issue is the networking. There is a 40 gigabit connection between both datacenters and inside everything is connected by 10 gig except the Isilon which has 4 1 gig connections and the Equallogic on the other end that has 2 1 gig connections. The Equallogic does multipathing and it evenly distributes the load between both. The Equallogic so far is far superior with its ISCi connections that the nfs type share is. EMC set up the Isilon but we are renting rack space from a provider so maybe there is some slowness to the network connections some how. We are still missing confirmation on the user interface for the WinShare2ESXidatastore transfers and the ESXi2ESXi transfers. CLI versus vSphere Client can make a big difference as to where the transfer traffic actually goes. Also, has anyone checked for a consistent Maximum Transmission Unit (MTU) size end to end in the same datacenter and end to end across datacenters? Isilon will support Jumbo Frames (9000 byte MTU), depending upon the OneFS version you are running. Isilon will also support Link Aggregation Control Protocol (LACP) in a way that can be compatible with Cisco switches. I do not recommend activating both LACP and Jumbo Frames unless you are one OneFS 6.5.5.x or later. THX Someone has changed my password on me so I cannot get into the unit but the version on the login page is v6.5.5.4. The network fellow who set it up didn't seem interested in Link Aggregation which I asked him about or setting the MTUs to 9000. I am used to that on the EqualLogics with its iScsi MTUs set to 9000 both on the switch and in ESXi as well as disabling storm control and port-spanning. We are renting these spaces so we have to go through the provider to make these changes. The way I was told to set up shares for the staff was directly to the Isilon on the nfs shares. Is there ever any issues with that as opposed to building a server and sharing out that way? And thanks for the help so far.
https://www.dell.com/community/VMware/Just-getting-started-with-an-Isilon-and-VMware-and-file/m-p/6889509
CC-MAIN-2019-47
refinedweb
1,299
65.86
30486/does-python-s-time-time-return-the-local-or-utc-timestamp Does time.time() in the Python time module return the system's time or the time in UTC? The print() function is use to write ...READ MORE You can use the following code block: x=range(1,100) len(x) Output: ...READ MORE Use this import os os.path.exists(path) # Returns whether the ...READ MORE The time.time() function returns the number of seconds since ...READ MORE suppose you have a string with a ...READ MORE if you google it you can find. ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE Look carefully at your output: 5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5 ^ ...READ MORE Only in Windows, in the latter case, ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/30486/does-python-s-time-time-return-the-local-or-utc-timestamp
CC-MAIN-2020-10
refinedweb
132
80.99
This action might not be possible to undo. Are you sure you want to continue? Introduction Grammar Practice & Vocabulary is aimed at upper-intermediate / B2 level students. As well as teaching grammar points, the aim of the book is to familiarise students with the format of the Revi sed Use of English Paper of the Cambridge FCE Examination as well as with the Grammar and Vocabulary sections of the University of Michigan ECCE. This book consists of 24 units, 6 revision units and 2 practice tests. Each unit is made up of: • Grammar a thorough review of grammatical structures with clear explanations and examples illustrating every structure • Grammar exercises a variety of exercises, some of which are modelled on either Paper 3 of the Cambridge FCE Examination or the grammar section of the Michigan ECCE, providing general practice on the grammatical structures taught in the unit • Transformation rewording sentences using key words; this exercise tests grammar • Phrasal Verbs clear explanations of a set of phrasal verbs together with an exercise practising them • Prepositions and Prepositional phrases an exercise practising the use of prepositions with verbs, nouns and adjectives as well as their lise in idioms • Derivatives an exercise based on word formation to help students enrich their vocabulary • Words easily confused clear explanations of words that students commonly confuse and an exercise practising them . • Revision units aud Practice FCE and ECCE Tests The Practice Tests are modelled on the Cambridge FCE Use of English Paper and on the Grammar and Vocabulary sections of the University of Michigan Examination for the ECCE. The book includes a dictionary and appendices with: • Prepositions • Prepositional Phrases • Derivatives There is a Teacher's Book available with the answers overprinted on the Student'S Book, Revision Tests, Final FCE Test, Final ECCE Test and Key to tests. Grammar & Vocabulary Practice H.Q. Mitchell Published by: MM Publications. co.uk info@mmpi.net Offices Great Britain - Greece - Poland - France - Cyprus - USA - Turkey Associated companies and representat ives throughout the world. All rights reserved. No part of thi s publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechani cal, photocopying, recording or otherwise, without permi ssion in writing from the publisher s. The publishers have tried to contact all copyright holders, but in cases where they may have failed, they will be pleased to make the necessary arrangements at the first opportunity. Produced in the EU ISBN 10: 960-443- 260-8 Teacher's Bonk ISBN 10: 960-443-261-3 ISBN 13: 978-960-443-260- 5 ISBN J3: N0708011'J2 1 2587 /2588 ___________________________________ pag 3 Co s e Unit I Present Time 4 Unit 2 Pas t Time 8 Unit 3 Present Perfect 12 Unit 4 Future T ime 17 Revision I 2 1 Unit 5 Infinit ive 24 Unit 6 -ing form 29 Unit 7 M odal Ve rbs L 34 Unit 8 Modal Verbs II 39 Revision 2. .' 44 Unit 9 Articl es 47 Unit 10 Nouns 52 Unit 11 Adj ecti ves-Adverbs-Comp arisons 57 Unit 12 Determi ners 64 Revision 69 Unit 13 Pronouns-Possessives 72 Unit 14 Passi ve Vo ice 77 Unit 15 Causative Form 82 Unit 16 Conditionals 86 Revision 4 91 Unit 17 Unreal Past-Would rather-Had better 94 Unit 18 Reported Speech 100 Unit 19 Question Forms 106 Unit 20 Cl auses I 112 Unit 21 Cl auses II 118 R.vision 5 124 Unit 22 Linking W ords 127 Unit 23 Participles 132 Unit 24 Emphatic/Exclamatory Structures -Inv ersion 136 Revision fi 14 1 Final FCE Practice Test 144 Final ECCE Practice Test 148 Dicti onary 153 Verbs, Adj ect ives, N ouns with Prepositi ons 161 Prepositional Phrases 163 Deri vatives 165 Irregular Ve rbs 168 Teacher's Book ontents Revi sion 11>':-; 1 I 170 Revision TC.'i 1 :2 __ __ __ __ . 173 Revision Tc '1 3 __ __ 176 Revision Tes t 4 17( Revis ion TeSI 5 __ __ __ __ 1 ~ 2 Revision Test 6 __ 185 Final FeE 11'1'1 Igg Final ~ C C ' I ' sl __ __ __ __ 192 Key 10 Tes ts __ Ilj7 . I unit Present Time 01 The Present Simple is used: • for habitual or repeated actions and situations. I watch this show once a week. • for general truths and natural phenomena. The earth goes round the sun. Most rivers flow into the sea. • for permanent situations in the present. James lives in Zurich. • for future actions related to timetables and programmes. The train leaves at six o'clock. • for headlines, sports commentaries, story-telling, reviews of films and books, directions and instructions. Three women rob bank. Martin takes the ball and scores. In this episode, Bob marries Julia. You tum left at this junction and you'll find it. • in exclamatory sentences with "Here... !"/"There...!" Here comes the bride! There he goes again! Time Expressions often, usually, always, never, sometimes, seldom, rarely, hardly ever, every day/week, etc. Stative Verbs The Present Progressive is used: • for actions or events happening at or around the time of speaking. Look! That boy is climbing up a tree. • for temporary states in the present. David is doing his military service. I'm studying French/this term. • for situations which are changing or developing around the present. The problem ofpollution is getting more and more serious. • for planned future actions related to personal arrangements. I'm travelling to London tomorrow. • with adverbs of frequency (constantly, always, etc.), for emphasis or to express annoying habits. Susan is very kind; she is always helping the poor. He is always leaving his clothes on the floor! Time Expressions now, at present, at the moment, nowadays, this month, etc. They express a state - not an action - and are not used in the Progressive Tenses: • verbs of the senses: feel, hear, see, smell, taste, notice, etc. • verbs of emotions and preferences: like, dislike, love, hate, fear, mind, want , wish, need, prefer, admire, etc. • verbs of perception, belief, knowledge, ownership: think, believe, know, understand, expect, remember,Jorget, hop e, have , own, belong (to) , etc. • other verbs which describe permanent states: be, cost, weigh, seem, appear, consist (of), etc. Some stative verbs can be used in the progressive forms when they express actions rather than states but with a difference in meaning . St ate They have a wonderful house. I see Mary coming towards us. I think she is clever. Do I smell cigarette smoke? This chewing-gum tastes like strawberry. He is very selfish. (=that is his character.) Action I'm having a bath now. I'm seeing the doctor tomorrow at 11 :00. I'm thinking of buying a new car. Why are you smelling the milk? Do you think it's gone off? She is tasting the soup to see if it needs any more salt. Why is he being selfi sh? (=why is he behaving so selfishly?) Listen, look and watch, though verbs of the senses, can also be used in the progressive tenses because they express voluntary actions. Jane is listening to music. _________________________________________ page 5 Grammar Practice A Read what the following people have to say about learning English in Britain. Complete with the Present Progressive or the Present Simple of the verbs in brackets. As part of my job, I travel (travel) abroad a lot, so I need (need) to improve my English. For this reason, I am attending (attend) a course in Business English at a Language Institute in London. The course last s (last) three weeks. come (come) from Italy but I am studying (study) in England at the moment. I am staying (stay) with a British family. In this way, my English improves/is improving (improve) faster because I don'tjam not just use/using (not use] it in the classroom but in my everyday life as well. visit (visit) England every two or three years, so speak (speak) some English but not much. At present am doing (do) a course at a Language School in London and I am learning (learn) lots of new stuff! Apart from that , in the afternoons I go (go) out with my classmates and we try/ are trying (try) to practise our English as much as possible. B Circle the correct answers. 1. In this story, a is finding a time machine and (tr avels)! is travelling through time. 2. Don't bother me now. I write / (am writing) an important letter. 3. I (am thinking)! think about grandmother. We hardly are visiting her. Let's visit her tomorrow. 4. The minibus, which is taking I(takes)people to the other side of the island, (leaves) 1is leaving at 11:00 a.m. and is returning 6:00 p.m.. 5. I sleep { am sleeping) at my mother's house this week because I(am having)1 have my house painted. 6. "When (ar e you do you leave for Rome?" "Tomorrow at 8:00 a.m.." ff? 7. I (think)! am thinking you should buy him a tie. He is liking dress formally. 8. Flowers (bloomy are blooming in spring. 9. You are turning left at the traffic lights and @I are going up Oxford Street. 10. is coming Kelly. Let's tell her the news. . . . I page 6 C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. John never stops criti cising my friends. always John _ is always criticising 2. We've arranged to meet at 8:00 p.m. tomorrow. are We are meeting at 8:00 p.m. tomorrow. 3. What time is your plane scheduled to arri ve at Heathrow? land What time does your plane land at Heathrow? 4. I have arranged to have dinner with Jerry tonight. am am having dinner 5. The older he gets, the more eccentri c he becomes. is As time goes by, he is getting/becoming more and more eccentric. 6. They don 't like spicy food, so they avoid eating it. never They never eat spicy food as they don 't like it. 7. Jane has found a job at a supermarket for the summer. is Jane is working at a supermarket this summer. 8. How much is that green jacket, please? does that green jacket cost I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. ask for: ask out: blow up: break down: break in: break into: break up: request sth invite sb to go out with you explode (1) stop working (for a piece of ma chinery) (2) lose control of your feelings or emotions enter a building illegally or by force (intran sitive) enter a building illegally or by force (transitive) (1) divide into smaller parts (2) give an end to a meet ing, relati onship, gatheri ng, etc. It was my birthday so I asked out my best friend to celebrate it with me. When we had fini shed having dinner, I asked for the bill. As I was looking out of the window, I saw three masked men trying to break into the bank across the street. Before I could react, there was an explosion. The robbers had blown up a car that was parked near the bank to distract people's attention, so that they could break in without being noticed. Just then, the robbers ran out of the bank and got into a white Fiat. But they were unlucky. Five hundred metres down the street their car broke down and they were caught. After the incident, the police broke up the crowd of people that had gathered and life returned to normal again. - page 7 B Complete using the prepositional phrases given. at the age of : a person's age at the time of on event at the beginning (of): at the start of sth at breakfast/ lunch/dinner: at the end (of): at first: at first sight: at ... km per hour: the ti me of the meal du ring which sth happens at the lost port of sth ini tial ly when fi rst seen the speed at which sth moves 1. Tax forms must be handed in at the beginning of March. After the 10th, you will have to pay a fine . 2. They got married within six month s of their first meeting; it was love at first sight 3. At the age of 35, Mark decided to study engineering. 4. Tom had an accident because he was speeding. He was going at 140 km per hour At the end winner was. 6. At first , I thought she was joking but then I realised that she was serious. 7. We 're having a small surprise party at lunch today, so make sure you' re back at the office by 12:30 p.m.. C Complete using the correct form of the verbs given. rent (v): regularly pay money to the owner of sth in order to have and use it for a lo ng period of time hire (v): (1) pay money to the owner of sth in order to use it for a period of time (2) empl oy sb to do a pa rtic ular jo b for you let (v): a llow the use of yo ur prope rty ate in exchange for money leave (v): forget or del iberately not toke sb o r sth with you (used when ing forget (v) : the place is mentioned) fo il to remember or bring sth ct, wit h you hat ley borrow (v): toke sth f ro m sb with their perm ission, intending to return it in t he future at. lend (v): allow sb to use sth that you ow n fo r a period of time ir Ie 1. My parent s never let thei r country house because they go there every weekend. 2. When she moved to the city , she rented a flat. 3. The school hired a teacher to help the slow learners . 4. We couldn't get into the fashion show since we had left the invitations at home . 5. I couldn' t pay for the shoes I wanted to buy. I had forgotten to take my credit card. 6. If you borrow something from a friend, you should take good care of it. 7. Steve never lends his CDs to anybody. unit 02 Past Time The Past Simple is used to describe : The Past Progressive is used to describe: • completed actions that took place at a definite time in • an action that was in progress at a definite time in the the past. The time is either mentioned or implied. past. Mary visited the British Museum when she was in This time last Friday, I was flying to London. London. • actions happening at the same time in the past. While Helen was watching TV, Nick was studying. Peter won first prize in the art competition. • a lengthy action that was in progress when a shorter • permanent situations in the past. or sudden one interrupted it. The longer action is in John lived in Ireland for 15 years. (He doesn't live the Past Progressive and the shorter one is in the Past there any more.) Simple (usually introduced by when). • completed actions that took place one after the other She was having dinner when the lights went out. in the past (in story-telling or narratives). • background scenes to a story. Sue woke up, washed her face and had breakfast. It was early in the evening and it was beginning to get • past habits or repeated actions in the past; adverbs of dark. She was having a cup of tea.... frequency (always, often, seldom, never, etc .) may • temporary past states or actions. also be used. He was writing a play in those days. When Paul was younger, he often went fishing with his • repeated past actions or annoying past habits (with father. always, continually, etc .). My brother was always getting into trouble in the past. Time Expressions Time Expressions yesterday, then, ago, lost month/night/week, when, while, as, etc. etc. • used to + infinitive expresses permanent states, past habits or repeated actions in the past. My grandfather used to be a librarian. He used to smoke heavily when he was younger. • would + infinitive expresses past habits or describes someone's typical behaviour in the past. Every evening he would do his homework, watch TV and go to bed quite early. The Past Perfect Simple is used: The Past Perfect Progressive is • for an action which was completed before another one in the past. The used: action which happened first is in the Past Perfect Simple while the • to emphasise the duration of an action that action which followed is in the Past Simple (in time clauses introduced had been in progress up to a moment in by before, after, when, by the time). However, when we describe the the past or before another past event. actions in the order that they happened, we often use the Past Simple. By 1987, he had been working in New York By the time we arrived, the film had started. for 5 years. They (had) hung up before I answered the phone. He had been teaching for 35 years when • for a past action that was completed before a definite time in the he retired. past. • for an action whose duration caused Angela had finished cooking by 11:30 a.m.. visible results later on in the past. • with adjecti ves in the superlative degree and expressions such as: When they came backfrom the beach, the first/second. .., the only... , etc. their skin was red. They had been lying in That was thefirst time I had been to Paris. the sun for 5 hours! It was the worst time I had ever had. Time Expressions Time Expressions by--o certain time, by the time, after, before, when, etc. by, for, since, after, before, how long, etc. _________________________________________ page 9 I Grammar Practice A Circle the correct answers. e: 1. As a teenager, r(used)1 would to do things that my parents e weren't approving I(didn't They(Were always had always been complaining about my actions. When had lectured me, I had covered cover)my ears and ignore them. Now, I'm experiencing the same thing with my own children! 2. Today I had had I(had)an awful day. r(arrived)! was arriving at the office,§1was sitting down at my desk and suddenly had discovered that r(had lost a document on my computer because of a virus. I worked / (had it for the past two days. As if thatMIwasn't st. being enough, a colleague get I(was my nerves. While I had been trying I(was trying) to remain calm, she had laughed I(was laughing)at me. B Rephrase the following sentences using the words in brackets. 1. I put on ten kilos and then I decided to go on a diet. (by the time) Bythe time I decided to go on a diet, I 'lad put on ten kilos . or I had put on ten kilos by the time I decided to go on a diet. is 2. First, they washed the car and then they waxed it. (after) at After they (had) washed the car, they waxed it. or They waxed the car after they (had) washed it. rk 3. Lisa made a sandwich and then sat on the sofa to watch TV. (before) Before Lisa sat on the sofa to watch TV, she (had) made a sandwich . or Lisa (had) made a sandwich before she sat on the sofa to watch TV. 4. We packed our suitcases and then left for the airport. (as soon as) As soon as we (had) packed our suitcases, we left for the airport. or We left for the airport as soon as we (had) packed our suitcases. '/1 5. Judy was walking down the street when she saw an accident. (as) As Judy was walking down the street, she saw an accident. or Judy saw an accident as she was walking down the street. c. • • ' ''5 page 10 C Choose the correct answers. 1. When the children home, it was obvious that they had been playing in mud. a. were arriving @ arrived 2. Michael in the queue to buy a ticket for the train when he heard a strange voice. a. waited @ was wai ting c. had wai ted 3. In my youth, I the world and often slept under the stars. @ travelled b. was travelling c. travel 4. The thieves houses for two years before they were fin ally caught. @) had been breakin g into b. are breakin g into c. break into 5. I my studi es by 1990. a. complete b. was completing @ had completed DUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. When he was younger, he went to the cinema every week. used When he was youn ger , he used to go to the cinema every week. 2. r hadn 't tasted Chi nese food before. first first time I had tasted 3. While we were in London, it never stoppe d raining. continuously It was raining continuously/ rained continuous ly while we were in Lond on. 4. I worked at a restaurant in those days. was In those days, I was working at a restaurant. 5. After walking for a mile, they realised that someone was mi ssing. had They had walked/had been walking for a mile when they realised that someone was missing. 6. That was the only science-fiction book he had read. never He had never read a science-fiction book before. 7. When Mark was a student, he was in the habit of forgetting his books. always Mark was always forgetting his books when he was a student. 8. Jake made a speech and then we left the ceremony. until We didn 't leave the ceremony until Jake (had) made a speech. _________________________________________ page 11 I Vocabulary Practice AComplete using the prepositional phrases given. 1. The unemployment rate is high at present at last: finally at least: no less than; the 2. You could at least clean up your room. You don't do minimum that could anything to help me with the housework. be done at night: late in the evening 3. He started working on this report at 8:00 a.m. and stopped at noon: in the middle of the at noon for lunch. day at peace/war: in a state of 4. You shouldn't eat and talk at the same time . harmony/confl ict 5. At last , the bus arrived. We had been waiting for an hour. at present: now at the same time: simultaneously 6. The baby woke up at night and started crying. It was afraid of the dark. 7. In order to be happy, you should always be _ _ at --'-- peace _ with yourself. BComplete using the correct form of the words in bold type. A GARLIC A DAY KEEPS THE DOCTOR AWAY ek. You may know that Asian, Middle Eastern and Mediterranean cultures have traditionally used garlic in their dishes. What you may not know is that garlic was TRADITION also thought of as a valuable medicine by many ancient civilisations. VALUE Today, professionals in the field of nutrition have come up with new PROFESSION information which is indeed quite surprising . Apparently, not only INFORM, SURPRISE is garlic good for you but it also helps you overcome various illnesses ILL The main disadvantage of eating garlic is of course bad breath . Cooking it, ADVANTAGE, BREATHE ne reduces the strong smell and eating parsley, which is a natural deodoriser, also NATURE helps minimise the smell. So, it's time we took the benefits of garlic seriously SERIOUS Why not add it to some of your favourite dishes! FAVOUR CComplete using the correct form of the words given. 1. Don't interrupt me now. I've got a lot of work to do. job (n) : the work sb does in order to earn money; employment 2. Julie found a good job close to where she lives. work (n) : (1) particular tasks sb has to 3. One of my duties as a nurse is to be on time because do in their job (2) the place where sb does their job lives depend on it. duty (n): the work that sb is responsible tasks 4. Our teacher gave us a few _----=..:::=.:...'-=----_ to do during the for getting done task (n): activity sb has to do, usually summer holidays. as part of a larger project look 5. I happened to _----'='"'--_ out of my window when my see (v] : notice, observe, take a look at sb/sth cousin was walking past. watch (v) : look at sb/sth for a period 6. Did you see Mary's costume at the carnival ? It was of time and observe what is happening wonderful! look (at) (v) : turn your eyes to a particular direction, see what is there or 7. I watched the football match before I went to bed. what sb/sth is like unit 03 Present Perfect The Present Perfect Simple is used: • for actions which started in the past and are still happening. I have known him for three years. (I still know him.) • for past actions whose results are connected to the present. The dog has spilt the milk. (The floor is dirty.) • to announce news, changes or events that affect the present. He has lost almost all his hair. • for past actions whose time is not stated, or for recently completed actions. He has travelled to India. I've just finished my homework. • with today, this morning/week etc., if these periods of time are not finished at the time of speaking. He has written two letters this morning. (It is still morning.} • with adjectives in the superlative degree or expressions like: the only/first/second..., etc. This is the most expensive suit I've ever bought. This is the third time Jack has visited the USA. Time Expressions since, for, just, yet, already, how long, ever, never, etc. Differences The Present Perfect Simple is used: • for permanent situations. She has lived in London all her life. • to emphasise the result of an action. I've called him three times this morning. • for actions that are already finished. Look at the car. Sam has washed it. The Present Perfect Simple is used: • for past events which have a connection to the present. The exact time is not mentioned. I've found a new job. • for events that began in the past but are still happening in the present. I have lived in Athens for ten years. (I still live in Athens.) • with today, this morning/week, etc. if these periods of time are not finished at the time of speaking. Helen has called me twice this morning. (the morning is not over yet.) The Present Perfect Progressive is used: • to emphasise the duration of an action which started in the past and is still happening. The action mayor may not be completed. They have been studying French for five years. • for actions that have been going on up to the recent past with obvious results in the present. "Why is the road so slippery?" "It has been raining. " • for actions which are temporary rather than permanent. He has been working overtime this week as there is a lot of work to do at the office. • to show anger, annoyance, irritation or to demand an explanation for a very recent action. Who has been wearing my coat? Have you been drinking again? Time Expressions how long, for, since, all day/morning, etc. The Present Perfect Progressive is used: • for temporary situations. He has been staying with friends for two months, but now he wants to get his own place. • to emphasise the duration of an action . I've been calling him since ten o'clock. • for actions that mayor may not be finished. Sam has been washing the car for an hour. The Past Simple is used: • for completed past events which are not connected to the present. The exact time is mentioned. I found a new job three months ago. • for events that took place for a certain period of time in the past but are over at the time of speaking. Susan lived in Manchester for three years but now she lives in Liverpool. • with today, this morning/week, etc. if these periods > of time are finished . Helen called me twice this morning. (the morning is over.) _________________________________________ page 13 They've been to Italy. (they are back now.) They've gone to Ital y. (they are stil l there .) feel, learn, live, sleep, study, teach, wait, work, etc. can be used in the Present Perfect ad: Simple or the Present Perfect Progressive with no difference in meaning. edin He has worked in that fact ory for three years. He has been working in that factory for three years. may Time Expressions A. for - since for is used when we want to indicate the length of a period of time . since is used when we want to indicate the starting point of a period of time . two hours 2 o' clock a week . July nent. f or . h srnce 1973 SIX mont s isa { { twel ve years I was a child I an for two hours. She's been talking on the phone ---[ . since seven o' clock /she came back from work. since + Past Simple (affirmative) It has been a long time since we saw him. (...since B. yet-already yet is used onl y in interrogati ve and negative senten ces and is placed at the end of the sentence. Have you finished yet? He hasn 't arri ved yet. alrea dy is used in affirmati ve and interrogati ve sentences; it is usually placed between the auxil iary and the main verb, but can also appear at the end of the sentence for emphasis. I have already been to the Science Museum. Have you already seen this film ? You 've fi nished your homework already! Grammar Practice A Choose the correct answers. 1. This is the second time I a. am healing heard that song. c. hear 2. Hello, I a. have been calling about your advertisement in the newspaper. Q am calling c. call ed 3. John has put on a bit of weight lately , and he is trying to lose it. b. is putting c. puts time 4. The new neighbours a. paint their house. It looks nice! b. had painted (f)have painted w 5. Fred @)told me yesterd ay that they're professional athletes. b. has told c. is telling 6. Apparently, he a. is knowing them since he was a child. known c. has been knowing g is page 14 B Put the verbs in brackets into the Present Perfect Simple, the Present Perfect Progressive or the Past Simple. - 1. J ack: I think I have lost (lose) my sunglasses. I have been looking (look) for them since noon, but I can' t find them. And they were (be) very expensive! Amanda: I have lost (lose) three pairs so far and I have learnt (learn) my lesson. I only buy cheap sunglasses now... Maybe you left (leave) them at Harry's house this morning. Jack: No, I have already asked (already, ask) him. 2. Debbie: This is the most interesting book I have ever read (ever, read). Pat: Where did you get (get) that book? I have been trying (try) to find it for months now! Debbie: My brother gave (give) it to me for my birthday. : here. He has been del ivering should be back soon. Peter: He left/Ilas left (leave) three messages on my answering machine but I' m not home, so please tell him to call me at my grandparents' house. I have been staying (stay) with them for the past two weeks, but I forgot (forget) to tell Tom when I last saw (see) him. C Rephrase the following sentences using the word in brackets. 1. Lucy is swimming in the pool. She started swimming half an hour ago. (for) Lucy has been swimming in the pool for half an hour. 2. Dave has had this computer for three weeks. (ago) Dave bought/got this computer three weeks ago. 3. They went to the supermarket at 6:00 p.m. Now, it' s 7:00 p.m.. (for) They have been at the supermarket for an hour. 4. It ' s 10:00 a.m. and I' m about to start writing my fourth letter. (so far) It's 10:00 a.m. and I have written three letters so far. 5. I started training five months ago. Now, it' s August. (since) I have been training since March. __________________________________________ page 15 ast o Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total .) 1. He has never driven another car since he started driving . only This is the only car he has driven since he started drivi ng. 2. The last time I watched TV was a week ago. for I haven't watched TV for a week. 3. When did he start working for this company? been How long has he been working for this company? 4. This is her second visit to the dentist this month. time This is the second time she has visited the dentist this mont h. 5. Let' s not go to a cafe as I had some coffee earli er. already Let's not go to a cafe as I have already had/drunk some coffee. 6. Ray still doesn' t know which car to buy, made Ray (still) hasn't made UP his mind which car to buy. 7. We have never exper ienced such a cold winter in Greece before. ever It's the coldest winter we have ever experienced in Greece. e 8. We bought this house two years ago. had We have had this house for two years . o page 16 Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. Mike has been ill for a week. He will have to work really hard call off: cancel sth carry on: continue doing sth to catch up with his class. carry out: perform a task 2. The match was called off due to bad weather. catch up (with): (1) reach sb by walking/ 3. He will never catch up with me. I'm a far better runner. running faster (2) reach the same level 4. After the earthquake, the islanders had to carryon as sb with their everyday lives. 5. Studies carried out by the World Health Organization indicate that cities are getting much noisier. B Complete using prepositions. .hocked by 2. Children are usually frightened ::JIorO <:In'V1Al1C' about 3. All the students WVlV • U1VU VA.U.111 •......;arl about 771prl by of 7. The writer was surprised 8. The children are afraid of the neighbour's dogs. 9. Tell me more about the country you come from. I'm curious about it. 10. Don't be shy of having your picture taken. 11. She's scared of making the wrong decision. 12. I'm never jealous of people who are wealthy because I'm happy with my life . C Complete using the correct form of the words given. mention (v): refer to or speak about .r\ sth briefly or 2. I can't find the words to incidentally nat') T mentioned H 3. How could you forget" L LV JVU report (v): inform some authority about sth that has happened express [v): show what you think or feel by saying or doing sth 4. Pollution has a very harmful effect on our health. result (n): the outcome of an action or situation 5. If you don't take our advice, you'll have to face the effect (of sth consequences on sth else) (n) : (1) the change that sth PV.,'" results cause s to sth else (2) the power to influence or produce a result . consequence (n) : the result or effect of sth (usually unpleasant) - Jd The Future "Will" is used to express: • a decision one makes at the moment of speaking. It's getting cold; I'll close the windows. • predictions or personal opinions about the future, usually with perhaps or probably, or after the verbs believe, expect, think, be sure, be afraid, etc. I think Arsenal will lose this match. I'm sure John will be very happy to meet you. on • requests and offers. Will you do the ironing for me, please? I'll take you to the airport tomorrow. • promises, threats, warnings, hopes, fears, invitation, refusal, willingness, determination. Stop making so much noise or the neighbours will get angry. Time Expressions unit 04 Future Time The Future Perfect Simple is used: • for actions which will have been completed before a specific point of time in the future or before another action in the future (the verb describing the second action is in the Present Simple). By dinner time I will have written all the letters. I guess John will have stopped working by the time we arrive. ht. Time Expressions by, by the time, before "Be going to" is used to express: • predictions based on evidence. The sun is shining; it's going to be a lovely day. • plans or decisions that have already been made. I'm going to study archaeology this year. She doesn't like Alan, so she is not going to invite him to her party. The Future Progressive is used to express: • actions that will be in progress at a specific time in the future. This time tomorrow I'll be flying to Rome. • future actions which have already been planned or are part of a routine. The president will be visiting Egypt next month. Tom won't come with us on Sunday; he will be playing basketball (=he does so every Saturday). • a polite request about someone's plans, especially if we want to ask for a favour. Will you be using your computer tomorrow? next week/month/year, etc., tomorrow, in a week/month/year, etc. The Future Perfect Progressive is used: • to show the duration of an action up to a certain point of time in the future. The action may continue further. By midnight we will have been flying for seven hours. Time Expressions by After the words after, as long as, as soon as, before, by the time, if, provided, providing, until, while, when, etc. we use the Present Simple, not the Future "Will". Give my regards to her when she calls. We can also use the Present Perfect Simple after the above words to emphasise that an action will be completed in the future. He'll come as soon as he has finished studying. page 18 Phrases with future meaning The following expressions indicate that an event will happen very soon. They are about to leave. be Gust) about to ? be bound to + infinitive You're bound to get there on time. be to We are to meet tomorrow at 10:00. be on the point of + -ing Susan is on the point of collapsing. no matter who/what/which/where/when ] No matter where we go, we' ll have a great time. + present tense whatever/whoever/whenever/wherever Whatever you decide to do, l'll support you. be due to + infinitive is used for schedul es and timetables. The plane is due to land in half an hour. Grammar Practice A Put the verbs in brackets into the Future "Will", the Future Progressive, the Future Perfect Simple or the Future Perfect Progressive. 1. Kathy can't come shopping with us on Saturday morning. She will be having (have) a French lesson. 2. Jenny , Ms Kingsley will contact (contact) you as soon as the documents are ready. Will you let (let ) me know when she does? 3. At lunchtime tomorrow you will be entertaining (entertain) your friends from Mexico, so I will ring (ring) you later on in the evening. 4. Will you be going (go) to the concert by car? I'd really appr eciate a lift. 5. I will have painted (pai nt) the living room by the time Dad comes home. He'll be so surprised! 6. I hope I will have interviewed (interview) all the appl icants by the time the manager arrives. 7. Do you think that they will have completed (complete) the construction of the tunnel by the end of this year? 8. Call David. He will have arrived (arrive) home by now. 9. By the time we reach Gstaad, we will have been driving (drive) for twelve hours. 10. I will have been studying (study) for three hours by 8:00 pm. _________________________________________ page 19 B Choose the corred answers. 1. Don't panic, sir. The doctor due to arrive any minute. @ is b. will be c. had been 2. By the time the train , we will have been waiting here for more than half an hour. a. had arrived b. will arrive @ arrives 3. She the phone no matter who calls her. @ won' t answer b. won't have answered c. hadn't answered 4. They some extra staff next week. a. will have employed b. employed @ are going to employ 5. I on my guitar for an hour and then we can leave. ® am going to practise b. will have practised c. had been practising 6. She can't come to the phone right now, she about to leave for her dancing lesson. m, a. will be ® is c. had been 7. You able to see much better with these new glasses. @ will be b. will have been c. have been 8. Brian, me your camera, please? a. did you lend @ will you lend c. are you lending CUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) ear? 1. The plane takes off in half an hour. is due to take off due The plane in half an hour. 2. Her baby will be born in October. is is going to have a baby in October. She -=----='- 3. He is to take his driving test tomorrow morning. be He will be taking his driving test tomorrow morning. 4. I'll come with you wherever you go on holiday. matter I'll come with you no matte r where you go on holiday. 5. The Tigers are likely to win the Cup Final. probably The Tigers will probably win the Cup Final. 6. Sam will go scuba diving only if the weather is good. provided Sam will go scuba diving provided (that) the weather is good. 7. I will have dinner ready by the time your parents arrive. prepared I will have prepared dinner by the time your parents arrive. 8. She started working here at the end of June, nearly two months ago. been By the end of August, she will have been working here for two months. page 20 Vocabulary Practice A Complete using the correct form of the phrasal verbs given. come across: find sth by chance 1. Come along/on ! We 're going to miss the bus. come along/on: (1) hurry up 2. When did Jane come up with this idea? It's perfect! (2) encourage sb to do 3. If you come across that CD, could you buy it for me? come into: sth inherit (money, property 4. Simon came into a lot of money after his grandfather's or a title) death. come round: (1) to stop by, visit 5. It took the boxer five minutes to corne round after he was (2) recover consciousness knocked out. come up with: think of and suggest sth (plan, idea, etc.) B Complete using the correct form of the words in bold type. MISSING THE HUSTLE AND BUSTLE My father was a police Ins pector , my mother a teacller . Their INSPECT, TEACH decision to move to a small town when I was a child changed my life. It was a DECIDE very peaceful place and of course living there meant that I had much more PEACE freedom to go wherever I pleased. The people were friendly but I FREE, FRIEND missed my close friends, my school and the noisy city I had lived in. NOISE As I grew up, I realised that there wasn't much for a young person to do there, except rush into marriage . When I left, my parents were sad, but they MARRY realised that staying there would only make me miserable MISERY The big city I live in now is not very far away, so I can visit my parents frequently FREQUENT and have the best of both worlds. C Complete using the correct form of the words given. 1. What time do you expect the guests to arrive? wait (for sb/sth) (v]: spend time doing 2. I'm looking forward to visiting Spain. little while expecting sth to 3. Can you wait for me, John ? happen or sb to arrive look forward to (doing) sth (v): anticipate sth to happen expect (v): believe that sth will happen, anticipate boast of/about sth (v): talk about sth in a 4. People who boast about their own achievements way that shows excessive pride aren 't usually popular. praise sb for sth (v) : express approval of 5. The teacher praised her students for their good or admiration for exam results. sb's achievements or qualities units 1-4 Revision 01 IGrammar Practice A Choose the correct answers. 1. The meeting will start when everyone _ a. will arrive @ arrives c. is arriving d. will have arrived 2. We Betty since she moved to our neighbourhood. ® have known b. had known c. are knowing d. knew 3. The students were tired. They hard all morning. ® had been working b. worked c. have been working d. had worked 4. By this time next month, the builders the house. Ii a. will complete b. will be completing @ will have completed d. will have been completing H 5. "This time next week we on the beach!" "I can't wait!" a. are lying @ will be lying c. will have lain d. will have been lying 6. Mark about my cooking! It's so annoying! a. has always complained b. was always complaining @ is always complaining d. had alway s complained 7. Sue TV when she heard a knock on the door. a. watched ® was watching c. has been watching d. has watched 8. By two o'clock, he on the drums for three hours. I hope he stops soon! @ will have been practising b. will be practising c. has been practising d. is practising 9. Yesterday, I met an old school friend who I for years . a. didn't see b. haven't seen c. had seen . hadn 't seen 10. "The phone 's ringing!" "I it!" a. get ® will get c. will be getting d. got 11. Nancy since she came from work. ® has been sleeping b. is sleeping c. slept d. had slept 12. Jack his wallet last week . a. was losing b. had lost c. has lost @ lost 13. You the wine after the meat is cooked. a. are adding b. will add @ add d. have added 14. I two letters so far. ® have written b. wrote c. had written d. have been writing us 15 . When we finally got to the airport, the plane _ a. has already landed b. landed already c. already landed @ had already landed page 22 BUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Lucy first started playing tennis in May. been Lucy has been playing tennis s ince May. 2. I had never read a better book by that author. best It was the best book I had ever read by that author. 3. Scott, is this your wallet? belong Scott, does this wallet belong to you ? 4. This is Pete's third attempt at climbing Mount Everest. time This is the third time Pete has attempted to climb Mount Everest. 5. We've arranged to leave by train tomorrow morning. are We are leaving/a re going to leave by train tomorrow morning. 6. By the time my favourite TV show starts, I will have dinner ready. finished By the time my favourite TV show starts, I will have finished cooking dinner. 7. It's ages since she last ate spaghetti. for She hasn't eaten spaghetti for ages. 8. They realised that they had taken the wrong turning after driving for an hour. had They had driven/had been driving for an hour before they realised that they had taken the wrong turning. Vocabulary Practice A Choose the correct answers. 1. I couldn't her. She is a fast runner. a. come up with @ catch up with c. bring back d. get away 2. When his aunt died, Luke a lot of money. a. came along b. came across @ came into d. came round 3. I'm really worried the boys. They haven't come back yet and it 's almost midnight. a. for @ about c. of d. with 4. Are you afraid the dark? a. with b. by c. at @ of 5. We the theft to the insurance company the following morning. a. replied b. expressed c. mentioned @) reported 6. I had to Jerry some money as he didn't have any to get home. a. let @ lend c. borrow d. gain 7. Samantha is good results in her examination. a. looking forward @ expecting c. waiting d. wanting 8. He a lot about the money he makes. ® boasts b. praises c. says d. mentions 9. I felt awful when I realised that I couldn't pay for the meal because I had my wallet. oforgotten b. left c. let d. lent 10. Do you believe in love first sight? a. with b. from @ at d. by 11. This is a lousy excuse! Couldn't you a. break up @ come up with something better? c. carryon d. ask for 12. She @ called off the wedding at the last minute. b. carried out c. asked out d. came into ________________________________________ page23 13. A thief our house last month and stole all of my mother's jewellery. @ broke into b. broke in c. broke down d. broke up 14. You could drive me to my house . It really isn't that far. a. at last eEl at least c. at present d. at the same time 15. I'm seeing Sally again after two years. a. expecting b. waiting c. looking @ looking forward to BComplete using the correct form of the words in bold type. 1. This is a very valuable grandfather clock. VALUE 2. Katie's illness has kept her away from school for a week. ILL 3. Nowadays most teenagers have the freedom to do whatever they please. FREE 4. A good f riendship will last a lifetime. FRIEND dinner. 5. An inspection of the building was made and it was declared safe. INSPECT 6. Naturally , we are concerned about our son's progress at school. NATURE 7. The children were playing noisily in the garden. NOISE 8. The children looked unhappy and miserable MISERY d taken CChoose the correct answers. Last weekend, my friend Anne and I decided to take a road trip. (l) , we were going to take Anne's car, but it had (2) a couple of days before. As a (3) , we decided to (4) one for 30 dollars a day. We both took Monday off from (5) , so that we could have a full four days. Our goal was to drive from New York to Washington D.C., and back. The trip itself was great. The weather was __ beautiful, and we (6) many interesting places along the way. There was a lot to (7) 10 Washington, so we spent two days there. The sad thing was that I had forgotten my camera, even though Anne had specifically (8) that she didn't have one to bring along. So, we bought lots of postcards to remind us of our trip. Even though we arrived back a bit tired on Monday night, the trip was well worth it! 1. a. At present 4. a. hire @ At first @ rent 7. a. look c. At least c. let b. notice d. At most d. buy @ see d. watch 2. a. broken up 5. a. job b. broken into b. task 8. ® mentioned c. broken in @ work b. reported @ broken down d. duty c. expressed d. told 3.@result 6.@ came across b. consequence b. came along c. effect c. came into d. reason d. came round unit 05 Infinitive Infinit ive Forms Time Reference Forms Active Passive Present Infinitive, simple (to) gi ve (to ) be given Present / Future Present Infinitive, progressive (to) be giving Perfect Infinitive, simple (to) have given (to) have been given Past Perfect Infiniti ve, progressi ve (to) have been giving Negative Form: noH infini tive Full Infinitive (to + infinitive) The full infinitive is used: Examples I. to express purpose She went to the post office to collect heI' parcel. 2. after certain verbs (as their object): She pretended not to have seen him. afford decide hesitate plan remind Unemployment levels tend to rise in Europe. . agree demand hope prepare seem They volunteered to help us. appear deserve learn pretend swear arrange expect manage promise tend ask fail mean refuse threaten beg forget need regret volunteer claim happen offer remember want , etc. 3. after the object of certain verbs: My friend invited me to join them. advise challenge force order teach They persuaded her not to see him again. allow convince hire permit tell ask encourage instruct persuade urge beg expect invite remind want cause forbid need require warn, etc. Hel p + obj ect can take eithe r a f ull or bare infin itive. Could you help me (to) pack my suitcas es ? 4. after verbs followed by a question word (who, what , Have you decided where to go for Christmas ? which , where, how, but not why): Do you remember what to buy ? ask forget remember understand Could you show me how to use your comput er ? decide know show wonder, etc. explain learn tell 5. after certain adjectives: Jack was relieved to hear his son 11'asout of danger. afraid careful lucky relieved surprised You have to be caref ul not to say anything insulting. amazed determined pleased sad upset anxious glad prepared shocked willing, etc. astonished happy ready sony _________________________________________ page25 6. after: would like, would love, would prefer 7. after: the first/second/nextlIastlbest, etc., instead of a relative clause 8. after certain nouns (pleasure, shock, etc.) 9. after some, any, no and their compounds 10. after the following structures: • it + be + adjective ( + of/for + object) • so + adjective + as, in formal or polite requests 11. with too/enough: too + adjective/adverb} negative meaning enough + noun } . . . adjective/adverb + enough positive meamng 12. after only, for emphasis or expressing disappointment 13. at the beginning of the sentence: as a subject or in fixed expressions (to be honest, to tell you the truth, to begin with, etc.) I would prefer to be on holiday instead of working. If anything happens, you'll be the first to know. Joan was the last to hear about the accident. It was a great pleasure to meet you. I'll make you something to eat. He doesn't have anywhere to stay. It's very comforting to listen to your voice. It was very kind of her to call. It is necessary for him to have a rest. Would you be so kind as to help me with these suitcases ? This shirt is too large for me to wear it. This shirt is large enough for me to wear it. He passed the written test only to fail the oral exam. To lend money is a risky business. To be honest, I didn't want to meet him. Bare Infinitive (infinitive without t o) The bare infinitive is used: 1. after most modal verbs (can/could, may/might, willi would, shall/should, must, etc.) 2. after: would rather, would sooner, had better 3. after the verbs hear, let, listen to, make, notice, observe, see, watch, etc. These verbs (except for let) take the full infinitive in the passive voice. 4. In the following structures: Why...?/ Why not•..? (for suggestions and advice) anything 1 do + everything + { but } + infinitive except noth O mg 1 Examples You should wake up earlier in the morning. Jane would rather go to California by plane. You'd better hurry up, we 're late again! Will you let me go to the party tonight? She heard him come in. He was seen to open the door. He was made to do some extra work. Why not have another drink? Why walk when I could give you a lift? My son does nothing all day but watch TV. Perfect Infinitive The perfect infinitive ref ers to actions or events that have al ready finished . The perfect infinitive is used: 1. with modal verbs (could, would, may, might, must, etc.) 2. after verbs such as: appear, claim, expect, hope, happen, pretend, promise, seem, etc. 3. after certain verbs in the passive voice (personal . construction): believe say think consider suppose understand, etc. Examples He could have studied more, but he didn't. He appears to have left the country. She is believed to have secretly met the Prime Minister. page 26 Grammar Practice A Choose the correct answers. 1. Don't hesitate for help if you need it. 1 ®to ask b. ask c. to be asked 2. Why not him and ask him out on a date? 2 a. to call c. to have called 3 c. go 4 c. not to have attended @ to see c. to have seen 5 a. Be 6 7. She claims the Prince. @ to have met b. to be meeting c. to meet 7 8. I must the telephone bill by tomorrow. a. be paying b. to pay @ pay 8 9. The famous actor Jerry Grant was heard to say that he would for President. @ run b. have run c. to run 10. You could Aunt Martha while you were in London. a. visit @ have visited c. be visiting B Circle the correct answers. 1. The Johnsons seem to(be having)! have had a great time at the Wyatt resort , where they are staying this summer. 2. He doesn't need - I@be given any more medication. 3. Jack is willing to be volunteering ( volunteer) his services at the club. 4. I failed to(arrive)t have arrived at the meeting on time. . 5. It was a shock to(learn)! be learning that she had been missing for three months. 6. The robbers were made -I§give themselves up. 7. He was surprised to have awarded I(have been awarded)a medal for bravery. 8. I'm always the last @l- find out about anything in this office. 9. The police warned the fans to not I(not to) approach the rock star. 10. He might to 18be promoted next year. _________________________________________ page 27 C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. It seems that Mike isn't enjoying himself tonight. appears Mike appears not to be enjoying himself tonight. 2. At the wedding, she was constantly gossiping about the other guests. nothing At the wedding, she did nothing but/except gossip about the other guests. 3. Learning that no one was hurt during the fire was a great relief. relieved We were (greatly) relieved to learn that no one was hurt during the fire. 4. When they arrived at the airport, they discovered that they had left their tickets at home. only They arrived at the airport only to discover that they had left their tickets at home. 5. The kidnappers forced the woman to get into the car. made The kidnappers made the woman get into the car. 6. Dr Thompson studied the symptoms of the disease before anyone else did. first Dr Thompson was the first to study the symptoms of the disease. 7. People say that he has travelled the world. said He is said to have t ravelled the world. 8. Neither of them was old enough to have a driving licence. too Both of them were too young to have a driving licence. Vocabulary Practice A Complete using the correct form of the phrasal verbs given. get along/on (with sb): form or have a friendly relationship with sb get away: escape get away with: go unpunished for get by: get off: get on: get on with: get over: doing sth wrong or risky continue to live in spite of difficulties (1) take yourself off a horse or bike (2) leave a plane, train, boat, etc. (1) place yourself on a horse or bike (2) enter a plane, train, boat, etc. continue doing sth, especially after an interruption or in spite of difficulties (1) recover from an illness (2) overcome a problem 1. I find it difficult to get by on the money I earn. 2. Wendy is very easy-going and can get along/on with anyone. 3. The boy got up and kindly offered his seat to an old man. 4. It took Sue two weeks to _ get over ---':lc::..::.....:::...:...:=..:......-_ the flu. 5. If! don't _ get on with -,="""--,,,,!.!...-'.,-,-,,-,--- this work, I'll never finish it. get on 6. Joe ran as fast as he could and managed to __= :"=":-'--_ the bus just before it left. 7. The thief got away before the police arrived. 8. Sue, could you help your little brother get off his bike? He doesn't want to ride it anymore! 9. She always gets away with not doing any housework! It's just not fair! page 28 B Complete using the prepositional phrases given. for ages: for a very long time for a change: doing sth different than usual (take sth/sb) for granted: accept sth as normal without thinking about it for hire/sale: available to be hired, rented/available to be sold for a while: for a short period of time 1. The house was for sale , so we decided to buy it. 2. Red is not a colour I would usually wear, but I think I'll buy that red dress for a change 3. We haven't seen the Johnsons for ages ! More than ten years, I think. 4. I'll be gone for a while . You won't have to wait long for me . 5. Nowadays, many children take everything for granted C Complete using the correct form of the verbs given. THE ART OF ADVERTISING In our life/lives we are constantly bombarded by advertisements whose role is to make products attractive enough so that people will want to buy them immediately There has been a lot of discussion on the powerful effects of advertising. Are ads really useful ? Are they truthful ? Do they give us a realistic idea of the product? People are rarely in agreement on any of these questions, but the fact is that ads are helpful in letting people know the wide variety of goods available. o Complete using the words given. debt (n): loan (n) : donation (n) : fine (n} : charge (n): tip (n): change (n): currency (n): profit (n): income (n): bill (n): receipt (n): amount of money that you owe to a person or a bank money that you borrow (usually from a bank) contribution to a charity or other organisation punishment in which sb has to pay a sum of money because they have done sth wrong or broken a rule amount of money sb has to pay for a service or to buy sth extra money given to sb (e.g. a waiter, porter, etc.) in order to thank them for their service (1) coins (2) money that you receive when you pay for sth with more money than it costs beca use you do not have the exact amount of money the money used in a particular country money sb gains when they are paid more for sth than it costs them to make, get or do money sb earns or receives a written statement of money that you owe for goods or services a piece of paper that you get from sb as confirmation that they have received money or goods from you ::I fInn for throwing litter on the street. LIVE, ADVERTISE ATTRACT IMMEDIATE DISCUSS USE, TRUE, REAL AGREE fine 2. The income Sandra earns allows her to live very comfortably. 3. I like to make ' 1" donations __.. .... . 4. Do you make a large profit out of the jewellery you sell? 5. If I don't get good service in a restaurant, I never leave a tip yUUl change 6. Come back, sir! You corgot 00_" 7. The Jones took out a loan to buy a new car. 8. There's no extra charge for delivery. cu rrency 9. What__ ... . 1::11 debt result the cost of living rises. 11. I must pay this electricity bill by next week. 12. Make sure you get a receipt for the furniture you buy. it. . I'll buy than ten longfor ted ERTISE 'E ,REAL 1 the man every s. vellery 'ave car. and as a week. reyou unit 06 -ing form -ing Forms Form Affirmative Present verb + -ing giving Perfect having + past participle having given Use The -ing form is used: Examples Negative not giving not having given 1. as a noun (subject or object of a verb) Swimming is a very goodform of exercise. I have some shopping to do this afternoon. 2. after a preposition or verb + preposition Touch your toes without bending your knees . Helen is excited about studying abroad. 3. after certain verbs (as their object): admit dislike mention recall appreciate enjoy mind recommend avoid fancy miss resent consider finish postpone resist delay imagine practise risk deny involve prefer suggest discuss keep (on) quit tolerate, etc. • prefer can also take a full infiniti ve. prefer + full infinitive + rather than + bare infinitive • mind can also go with an if-clause. Some of these verbs can also take a that-clause. 4. after verbs or expressions with to: be/get accustomed to look forward to be/get used to object to in addition to take to 5. after certain expressions: as well as it's no good/use be in favour of it's worth can't stand/help there's no chance of feel like there's no point in have difficulty (in) what's the point of...? how about what's the use of.. .? 6. after the verbs need, want, require, etc. with a passive meaning. 7. after the verb go, indicating physical activities catch j 8. after the verbs find + object leave 9. after: be busy spend/waste + expression of money/time Tony dislikes driving small cars. Would you mind waiting for a moment? Have you finished reading that book? He avoided answering my question. I prefer swimming to playing football . (general preference) I prefer to watch TV at night. (specific preference) I prefer to start exercising rather than go on a diet. Would you mind if I opened the door? He never admitted that he was wrong . The children were not used to living in the country. They are looking forward to travelling abroad. As well as going to the cinema, he likes reading science .fiction stories. I don't feel like going out tonight. She can't help crying whenever she peels onions. My car needs repairing. (=My car needs to be repaired.) We are planning to go skiing this weekend. She caught him stealing some money from the drawer. I found her sleeping on the sofa. They left me waiting in the rain for half an hour. She is busy feeding the baby. Every day they spend two hours studying French. You shouldn't waste your time watching soap operas. - page 30 Infinitive or -ing form with no difference in meaning • The verbs like, love, hate, begin, start, continue, intend, prefer, can't bear, etc. can take either a full infinitive or -ing with little or no difference in meaning: Tim loves playing/to play tennis. • like + -ing: we enjoy something. like + full infinitive: we think that something is a good idea. Mary likes reading poetry. Ilike to have my tyres checked whenever I buy petrol. • begin, start : usually the -ing form goes with simple tenses and the infinitive with progressive tenses (to avoid having two -ing forms together) . It started raining on hour ago. Be quiet! The lecturer is beginning to speak! . II . d' [ -ing • a dVise, a ow, encourage, permit, recommen , require + bi t f II . f' if o lee + u In rru rve The manager does not allow smoking in the oHice. The manager does not allow anyone to smoke in the oHiee. Infinitive or -i ng form with different meanings • Some other verbs can take either -ing or infinitive, but the meaning is different. try + -ing: make an experiment. !fyou want to get rid of your sore throat, try drinking something hot. remember j . We refer to somethin that has forget + -mg g already happened. regret I remember visiting Berlin in 1982. go on + -ing: the action continues. He was so fascinated by the book that he went on reading it for hours. stop + -ing: the action was stopped and not repeated. They had a major argument and stopped talking to each other. see hear smell notice watch observe ~ . + -mg for actions which are incomplete or still in feel listen to, etc. progress. I was walking past the reception hall when I saw him playing the piano. (=1 witnessed a part of the action.) smell can take only an -ing form. He could smell something burning. try + full infinitive: make an effort. I'll try to persuade her to come with us, but I don't think she will change her mind. remember j we remember/forget! . . . . forget + full infinitive regret something . . regret before doing It. Don 't forget to go to the supermarket. go on + full infinitive: the action changes. When she finished school, she went on to study Medicine. stop + full infinitive: the action was interrupted, but probably continued afterwards. I was writing a letter, but I stopped to answer the phone. see watch ~ hear feel observe listen to bare i fi . . + are m nitive for complete . actions. notice, etc. We saw him play the piano at a concert. (=1 witnessed the whole action.from the beginning to the end.) • The subject of the -ing form can be different from the subject of the verb. In this case, it can be a noun, an object pronoun, a possessive adjective or a noun in the possessive case. Angelo objected to Michael/him/hi s/Michae/'s going on holiday to Japan. • excuse, forgive, pardon, prevent, understand + possessive adjective + -ing form Forgive my being so fussy, but everything has to be perfect. possessive adjective/case + -ing • prevent + [ . sb + from + doinq sth She tried to prevent his/her son's seeing Jane. She tried to prevent her son from seeing Jane. _________________________________________ page31 Grammar Practice itive A Complete using the -ing form or the infinitive of the verbs in brackets. 1. It was Mr Kent who suggested Mary's studying (study) abroad. 2. You don't expect me to believe (believe) that you actually met Orlando Bloom, do you? idea. 3. The board of directors discussed the project, then went on to discuss (discuss) another topic. 4. Why continue to work/working (work) there if you don't like your job? tenses 5. He regrets not going (not go) to see his grandfather in Paris. 6. It's worth shopping (shop) at Stacey's as it's very cheap. 7. My doctor doesn't permit me to eat (eat) red meat. e 8. Greg would rather spend (spend) the holidays skiing (ski) than sunbathe/sunbathing (sunbathe) on a beach somewhere. 9. I was driving home when I noticed some workers putting up (put up) new traffic lights on Coronation Street. 10. Anyone can get (get) used to living (live) a life of luxury. 11. Will you quit complaining (complain)! It doesn't help (to) solve (solve) the problem. 12. If you ever decide to sell (sell) your car, let me know (know). think 13. I would like you to water (water) the plants for me at the weekend. 14. I clearly remember setting (set) my alarm clock before going (go) to bed last night. rget! 15. These plants require watering (water) every day. 16. I resent you speaking (speak) to me like that! Have some respect! 17. It would be good for the children to play (play) outdoors more often. 18. I promised to take (take) Jill to the party, but I don't feel like going (go) now. dicine. 19. Don't waste your time looking for (look for) the document. Ask Mr Gale. 20. Please, excuse his leaving (leave) so early. He wants to catch up (catch up) with his ut studying (study). hone. B Choose the sentence closest in meaning to the given one. lete 1. Even though the telephone rang, he went on playing his violin. a. He didn't continue to play the violin after the ssed telephone rang. (5)He continued to play the violin despite the fact that the telephone was ringing. c. He played the violin until the telephone rang. 2. Jane forgot to put a stamp on the letter before she sent it. a. Jane doesn't remember whether she put a stamp on eo the letter or not. se. b. Jane put a stamp on the letter but she doesn't remember doing so. @ Jane didn't put a stamp on the letter because she didn't remember to do so. 3. Sue regrets selling her car. a. Sue decided not to sell her car because it would be a mistake. b. Sue may not sell her car. @ Sue sold her car but now thinks it was a mistake. 4. We stopped to buy a bottle of wine before visiting the Johnsons. ® We bought a bottle of wine on our way to the Johnsons. b. We no longer buy a bottle of wine before visiting the Johnsons. c. We didn't buy a bottle of wine before visiting the Johnsons. 5. Charlie couldn't sleep last night, so he tried listening to music but it didn't help. a. Charlie made an effort to listen to music but he couldn't @ Charlie thought listening to music might help but he was wrong. c. Charlie listened to music and fell asleep. page 32 C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. It wasn 't easy for her to find a place to stay on the island. difficulty She Ilad difficulty (in) finding a place to stay on the island. 2. I can 't wait to tell Karen the good news. forward I'm looking forward to telling Karen the good news . 3. When they arrived home, their dog was sleeping in his kennel. found When they arrived home, they found their dog s leeping in his kennel. 4. The teacher doesn't permit eating in the classroom. anyone The teacher doesn't permit anyone to eat in the classroom. 5. She never appeared on TV again after the scandal became known. stopped She stopped appearing on TV after the scandal became known. 6. The boys said that they hadn't broken the window. denied The boys denied breaking/having broken the window. 7. He continued to interrupt me although I had told him to stop. kept He kept (on) interrupting me although I had told him to stop. 8. The poli ce will prevent his leaving the country. from The police will prevent him from leaving the country. Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. At the end of the year, the students had to give away: (1) reveal information or tell a secret (2) give sth to sb free of charge give back all the books they had borrowed from give back: return sth you have borrowed or the library. give in: taken (1) admit that you are defeated 2. Jenny kept annoying her parents until they gave in to her demands. (2) do sth you didn't want to am gave up give out: distribute some things among a number of people give up: (1) quit an effort (2) resign from your job anyone. B Complete using prepositions. 1. You shouldn't laugh 13t other people's misfortunes. 2. My family were very proud of me when I won a scholarship to Oxford. 3. Jenny is keen on Chinese food and cooks it at least twice a week. 4. She is so fond of her dog that if anything happened to it, she'd be devastated. 5. I'm very excited about my new job. 6. Dave is interested In ancient Greek ali, so he' s thinking of taking a course in it. 7. That girl is smiling at us. Do you know her? 8. He has developed an interest in computers lately. 9. Stop joking about such a serious subject! 10. Are you pleased with the service provided by the staff? _________________________________________ page 33 CComplete using the correct form of the words in bold type. SOMEONE TO WATCH US There has been a significant reduct ion in police popularity in the last few years. REDUCE That's why this week a public relations campaign is being launched to make people more sensitive to the role of the police officer. The ads will stress that police SENSE do more than just give motorists speeding tickets. They often act as unofficial MOTOR social workers, visit schools and talk to students, familiarising them with traffic signs and warning them of various dangers. Being a police officer is risky VARY, RISK considering that every day they deal with criminals such as thieves and even CRIME murderers . In conclusion , the campaign wants to make the public realise that MURDER, CONCLUDE even though in some cases the police's approach may seem extreme, they cannot ignore the possibility of injury or even death while on duty. POSSIBLE, DIE o Complete using the correct form of the words given. 1. The hospital staff are crew (n): people who work on a ship or aircraft on strike today . staff (n): people who work for a 2. I work for a law firm which has a company or organisation, lot of business people as employees team (n): group of people who work clients together or playa particular team sport or game together m employee (n): a person who is paid to but we lost the game. work for an organisation or 4. I always buy my groceries from for another person this shop. I am a regular colleague (n): a person you work with (at a professional job) customer here, so I expect client (n): a person or organisation good service. that receives a service from 5. There weren't many people on the a professional person or another organisation in plane; just the ten of us and the crew duct. return for money 6. Whenever I need help at work, I can always rely on my customer (n): a person who buys goods colleagues or services, especially from a shop 7. Employers often complain that they can't find reliable employees/staff . 8. All visitors entering the factory must wear this card. guest (n) : . sb who is visiting you or is at an event because they 9. We had guests/visitors staying with us for ten days. have been invited 10. Our host provided us with a delicious meal. host (n): sb who receives or entertains guests visitor (n): sb who is visiting a person or a place unit 07 Modal Verbs I The modal verbs are: can, could, may, might, must, will, would, shall, should, need, have to, ought to, used to. Need may also be used as a main verb. Modal verbs do not have all tense forms and You shouldn't leave your dog alone at home. • are followed by a bare infinitive (present or perfect) You should have answered the phone. except for need (when it is used as a main verb). He needs to see the doctor. • have the same form in all persons, except have to and She must call the plumber immediately. need (when it is used as a main verb). Your car needs to be repaired/repairing. • form questions and negations without auxiliary verbs, Can he repair his car? except have to , used to and need (when it is used as a He cannot/can't repair his car. main verb). Do you have to see the doctor tomorrow? He doesn't need to get up early every day. Modal verbs have several meanings and uses. A. Ability Modal verbs Use Examples Can Ability in the present or future. Can you play the guitar? Mary will be able to play tennis after she has Be able to Can is more commonly used for the present. had some lessons. Could expresses general ability in the past. He could swim at the age offive. Could Was/were able to express ability in a particular George could swim, so he was able to save the Was/were situation in the past . boy from drowning. able to • Both can be used in negative sentences with no difference in meaning. He had a terrible accident but managed to • If the action was very difficult, we can use survive. managed to instead of was/were able to. Perfect and future tenses are formed only with be able to . Nick hasn't been able to find a iob yet. I think Sandra will be able to pick you up from the airport. B. Possibility Modal verbs Use Examples present Possibility in the present or future. Tina mayleould/might (not) be at home now. infinitive • Can is used when something is only George could be working late tonight. ~ : : l d ~ may + (simple or sometimes possible My brother can be velY rude sometimes. might progressive) perfect Possibility in the past. She could have left her umbrella in the COUld infinitive • In negative sentences only may not classroom. may j + (simple or and might not can be used to express I'm surprised to hear that Jim was not at the might progressive) possibility in the past (not could not) party. He might not have known about it. could] present For an event that was possible in the Be careful! You could have crashed into that might + infinitive past but did not eventually happen. tree! ------------ page35 Possibility can al so be expressed with be likely to. Mary is likely to arrive late. It is likely that Mary will a rrive late. May and might expressing possibil ity cannot introduce interrogative sentences; Do you think...? and Is it likely... ? are used instead. Do you think she might be at home? Is it likely that she is still at home? C. Probability Modal verbs Use Examples present infinitive Probability in the present or future. There are plenty a/fiats available/or (simple or rent in town. It should/ought to be ShOuld] + ought to progressive) easy enough to find a place to live. present infinitive Something was expected to happen in She has been working very efficiently Should] + (simple or the past, but either didn't happen or it is lately; she should/ought to have been ought to progressive) not certain if it happened. promoted. D. Deduction Modal verbs Use Examples as must + present infinitive Positive deduction about the present John must be at the dentist's; he was (simple or or future. (We are fairly sure that complaining about a toothach e. progressive) something is true. ) ethe can't + present infinitive Negative deduction about the present The 6:30 train to Liverpool can't be (simple or or future. (We arc almost certain that leaving yet; it 's only 6:IO. progressive) something is not true.) must + perfect infini tive Positive deduction about the past. I can't find my glasses; I must have (simple or left them at the office. progressive) can't ] perfect infinitive Negative deduction about the past. He can 't/couldn 't have been working couldn't + (simple or yesterday; it was Sunday. progressive) E. Permission Asking for permission Synonymous expressions Can I (possibly)...? Informal I wonder if I could/might... all'. Could 1...? ~ Is it all right iLI...? Formal May I...? Would it be possible for me to...? l. Might 1...? DolWould you mind if!.. .? F. Requests Modal Verbs Examples t tne can Can you help me with the ironing? Informal will Will you please put out your cigarette? othat could, may Could/May I have some coffee, please? Polite/Formal would Would you pass me the salt, pleas; " page 36 Grammar Practice A Complete using can, can't, may, may not or must. 1. Can you lend me your dictionary, please? I really need it. 2. Rebecca is eighteen months old . Now that she can walk, I have to watch out for her all the time! 3. Roger can'tjmay not come to the cinema with us because he has a lot of studying to do. 4. Jane must have bought a car. I saw her driving past my house this morning. 5. "I'rn surprised that John didn't answer the door. I rang the doorbell many times." "He may/must have been sleeping." 6. Can/May I playa game on your computer? 7. They can't have walked all the way to town. It's too far! 8. Can/May I have some more red wine, please? 9. They can't afford to rent a summer house this year, so they've decided to go camping instead. 10. "I've got a temperature and a sore throat." "Oh, you must be feeling awful!" B Choose the correct answers. 1. Samantha asleep because there's no light on in her room. @ must be b. can be c. can't be 2. I might the test but I'm not sure . I haven't received the results yet. a. pass b. have been passed (S) have passed 3. I use your phone? I need to make an urgent phone call. a. Would b. Will 0 Can 4. Tom is a talented musician. He should the competition. a. won Ci2) have won c. to win 5. You have asked me first before you invited them. ocould b. may c. must 6. Don 't make any plans for Tuesday because we leave in the morning. I'Ulet you know tonight. a. can (2) may c. would 7. Martha have left. The lights in her house are on. @ can' t b. shouldn't c. needn't 8. Mike leaves work at 3:00 p.m., so he be home by now. a. can CEl should c. would CUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. There is a possibility that they won't visit us at the weekend. might They might not visit us at the weekend. 2. I'm sure it wasn't Tim who called you because I saw him outside. been It can 't have been Tim who called you because I saw him outside. 3. I think you'll find the house easily, as the directions are quite clear. ought The directions are quite clear, so you ought to fi nd the house easily. 4. I suppose Bruce has gone to the dentist since he had a terrible toothache. have Bruce must have gone to the dentist since he had a terrible toothache. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ page37 5. It's frustrating when you can't communicate with foreigners. able It's frustrating when you aren't able to communicate with foreigners. 6. Perhaps you didn't buy that watch from this shop. could You could have bought that watch from another shop. 7. Gary couldn't remember where he had put his wallet. was Gary was not able to remember/was unable to remember where he had put his wallet. 8. Karen, I'd like you to help me with the washing-up. will Karen, will you help me with the washing-up? I Vocabulary Practice A Complete using the phrasal verbs given. count on: cut down (on): cut oft: cut up: end up: rely on sb reduce the consumption of sth (1) stop providing sth (2) interrupt (e.g. a telephone conversation) cut sth into several smaller pieces eventually arrive somewhere or find yourself in a situation, usually without planning to 1. We hadn't paid the bill, so our water supply was cut off 2. I'm afraid I'll end up failing my exams if I don't study harder. 3. I can never count on my brother for help in times of emergency. 4. The doctor told the diabetic patient to cut down on sugar. 5. The small boy's mother cut up his food into small pieces to enable him to eat it easily. B Complete using the prepositional phrases given. ht. byaccident: by air/rail/ road/sea: by bus/carl plane/boat: by chance: by cheque: by force: by heart: ide. 'e by mistake: by oneself: not intentionally travelling via that route travelling using a particular means of transport unexpectedly, not planning to payment by mea ns of cheque, not using cash using violent action when you learn sth so well that you can remember it without having to read it in error alone; without help by phone/post: using that particular means of communication 1. I don't have any cash on me, so I'll have to pay you by cheque by myself by heart 7. I learnt the poem off ---"- to say at our end-of-year celebrations. 8. Paul found the lost document completely by chance/by accident . 9. When my brother bought his new car, he travelled everywhere by road only. iache. =: page 38 u C Complete using the correct form of the words given. DON'T GIVE UP HOPEl The economic crisis facing many countries today has created serious unemployment problems. Energet ic young people, willing to work, EMPLOY, ENERGY are confronted by many difficulties when tryin g to find a job. Filling in DIFFICULT countless application forms and hearing that they are uns uitable APPLY, SUIT for the job because they don't have the right qualifications can be very QUALIFY disheartening. Finding a job seems just imposs ible . However, POSSIBLE their disa ppointment shouldn't affect them nor make them give up. There is no DISAPPOINT straightforward so lution other than patience and persistence. SOLVE, PATIENT D Complete using the correct form of the words given. travel (v)(n): going from one place to another trip (n): a short journey to a pla ce and back again tour (n) : an organised trip during which you visit different places voyage (n) : a journey by ship or spacecraft cruise (n): a holiday during which you travel on a ship flight (n): a journey by plane journey (n): travelling from one place to another route (n): the way from one place to anot her 1. Our business trip to Brussels was producti ve and very pl easant. 2. What ' s the qui ckest route from your hous e to the city centre? 3. As soo n as they arrived, they went on a tour of the city . 4. At the airport they told us that the flight to Rome had been cancelled. 5. Inst ead of going to an i sland, we decided to go on a luxury cruise around the Mediterranean. 6. Peopl e say that the safest and quickest way to trave l is by aeroplane. 7. The journey from Boston to Montreal by car takes around five hours. 8. The old captain had spent his life making voyages to the Far East. a unit 08 Modal Verbs II GY Modal verbs will Will (you) ...? can could Can 1..? T Could L? ShallL? (= do you want me to...) Would you like} noun prefer + full infinitive Would you rather + bare infinitive Modal verbs can shall could A . Offers Use To be willing to do something for someone else. Informal offers and invitations. To offer to do something for someone else. Polite or formal offers and invitations. B. Suggestions Use Informal suggestions Polite or formal suggestions Examples I'll make you a sandwich if you are hungry. Will you have some tea? I can / could lend you my umbrella. Is there anything 1 could do to help ? Can I take your coat? Shall I post this letterfor you? Would you like a drink? Would you like me to help? Would you prefer to stay here 'with us ? Would you rather have a cheese sandwich? Examples We can go to the cinema, ifyou like. Shall we go shopping on Saturday ? We could go for a swim in the afternoon. Suggestions can also be expressed by: Let's + bare infinitive: Let's play tenni s. Why don't... ?: Why don't we go for a walk? noun: How about some more coffee? How a bout + [ . . . . -mg form: How about having a przzc for dinner? Modal verbs shall should } ought to + present infinitive (simple or progressive) had better + bare infinitive perfect infinitive should } (simple or ought to + progressive) c. Advice Use To ask for advice. To ask for and give advice. To say what is generally right or wrong. To give strong advice; it often expresses a threat or warning and is stronger than should/ought to. Something should have been done but did not eventually happen. Examples Shall I dye my hair? I think you ought to see a doctor. You shouldn't be watching TV now; you should be studying. You'd better not argu e with him. He'd better study harder !f he wants to pass the exam. You shouldn't have lied to your parents. They ought to have informed us earlier. page 40 Modal verbs used to would + present infinitive will Modal verbs must have to have got to noun -ing form need + full i n f i n i ~ i : e E bare infiniti ve ought to D. Habits Use For past habits and situations that are no longer true. • Interrogative and negati ve sentences are formed with did. To describe past habits or a person ' s typical behaviour in the past. To describe a person' s typical behaviour at present. Examples As a child, she used to be very difficult. Did they use to go fishing evelY Sunday ? He didn 't use to be so lazy. My grandmother would give me a bar of choco late whenever I visited her. When John is happy, he will sing all day. E. Obligation - Necessity Use Internal obligation: the speaker feels that he or someone else is obliged to do something. External obligation: it comes from facts, not from the speaker's opinion or feelings. • have (got) to can be used with adverbs of frequency. Necessity • When need is a main verb, interrogati ve and negati ve sentences are formed with do/did. We remind someone of a dut y or obligation . Examples I must repair the roof before winter comes. You must get up early tomorrow. Poli cemen have to wear a uniform. (regulation) I've got to see my dentist tomorrow. (I have an appointment) Do you often have to work at weekends? She needs a new pair ofgloves. This room needs painting. Do I need to take an umbrella ? Need I take an umbrella? You ought to post these letters today. Must is used only for the present; for the past and the future we use the forms of have to, expressing either interna l or external ob ligati on. He had to leave earlier yesterday. They will soon have to tell him the truth. F. Absence of necessity Modal verbs don't have to haven't got to needn 't don't need to needn't + perfect infinitive didn't need to + infiniti ve Modal verbs mustn't can' t Use It is not necessary to do something. Something was not necessary but it was done. Something was not nece ssary, and it is not clear if it was done or not. G. Prohibition Use Prohibition Not being allowed to do something. Examples I don't have to/haven't got to cook dinner tonight; we are going to a restaurant. You needn 't take your jacket. It isn't cold. He doesn 't need to work that hard. You needn 't have bought any magazines; I' ve got plenty. They didn't need to pay anything extrafo r the tour. Examples You mustn 't enter this room. We can't use this equipment. _________________________________________ page41 Grammar Practice AComple t e the sentences using can, should, would, mustn't, have to or don't have to. tit, mustn 't 2. Would you like some more tea? lay? 3. I'm afraid we have to cancel our skiing trip. tr o] 4. Can I get you a drink? 5. You don't have t o do any cooking as I've already prepared something. day. 6. You should have told her the truth earlier. She wouldn't have been so angry. 7. I was a very good student and I would always do my homework. 8. We can go swimming if you like. It's warm today. BCircle the correct answers. 1. Mary: The children must I(need)new sports shoes, but I don't have time to go shopping. Gary: would take them shopping if you want. 2. You@houldn,.)t mustn't have been driving so carelessly! You could have killed someone. 3. Mike: Bill likes computer games. He would I §)sit in front of his computer for hours. Lucy: Yes, but you(ought to)! shall encourage him to take up other activities as well. ? 4. Tom: I need I don't want to miss the bus and keep Sally waiting. Jack: You mustn't by bus. I(couldY should drive you there if you like. 5. Debbie : (Why How about we buy him a silk tie? Steve: No, he doesn't wear ties. We would IE)always get him a nice shirt, though. 6. All the employees in this company had to I(must)work overtime every day next week. 7. With temperature like that, need be in bed. You playing outside! essing 8. I'm sorry, sir, but you mustn't Dr Brown today. You lhave to)! need have an appointment. Is Tuesday afternoon OK? 9. They needn't need)to buy any more bread. There was plenty at home. 10. Angela: I didn't need to I @idn't use to)exercise regularly, but now that I have more free time, I do. Peter: What do you think... Will I start exercising? inner Angela: Sure, but you(had)1 would better consult your doctor first. t. cold. CChoose the correct answers. 1. I buy a present for Mary because her birthday is on Saturday. 'nes; @ need to 2. You rajor @ shouldn' t 3. Ann, you really a. must 4. Tom a. should 5. We a. couldn't b. need c. am needing to have lied to your Dad about taking the car. b. couldn't c. mustn't have studied a bit harder for the exam. b. need to @) ought to to see a doctor. He's been ill for the past weeks. @ needs c. must worry about getting to the airport on time; it's really close by. b. ought not to c. can't d. will need d. can't d. would d. ought to @ needn' t page 42 D Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. You were wrong to drive through the red light. should You should not have driven through the red light. 2. Our children were never in the habit of telling lies. used Our children never used to tell lies . 3. Taking photographs inside the museum is strictly prohibited. not You must not take photographs inside the museum. 4. You are not obliged to come if you have something else to do. have You don 't have to come if you have something else to do. 5. Shall I do the shopping for you? like ._... Won!ti you like me to do - ----rr--o-- J - 6. It wasn't necessary for you to wake up so early. needn't You needn't have woken up so early. 7. If I were you, I wouldn't borrow his camera without asking. better You had better not borrow his camera without asking. 8. It is necessary for her to have an international driving licence. has She has to have an international driving licence. I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. When I went to the bank to ask for a loan, I had to fall behind: not make progress or move forward as fast as you were supposed to fill in hundreds of forms. fall oft: become detached 2. Oh no! The sign has fallen off the wall. fall out: (1) be separated from sb's body 3. I was sick last week and as a result I have fallen behind (e.g. hair, a tooth) (2) have an argument with sb in my work. fill in: complete 4. Did you find out who sent you the package? find out: learn sth you didn't know, usually used to 5. John and Mary fall out _" through deliberate effort eventually split up. B Complete using prepositions. 1. Jenny reminds me of that famous actress we saw on television last night. 2. We have a preference for dry wine. 3. There must be a solution to Jim's problem. 4. The rock band has just arrived at the airport. 5. Did you get an invitation to/for the wedding? 6. I prefer coffee to tea. 7. Do you think mum will mind if I lend her book to Kathy? 8. We must decide on where to go for the long weekend. 9. Paul spends a lot of time on computer games. 10. Unfortunately, I'm working on Saturday, so you can forget about going to the beach. _________________________________________ pilge43 CComplete using the correct form of the words in bold type. WE ARE THE CHAMPIONS! The exciting game between the Dragons and the Tigers is over. The Tigers ' EXCITE fai lure to win of course means that they won' t play in the fina ls. Th e Dragons played a wonderfu l game and earned everyone's admiration WONDER, ADMIRE Their combination of tactics and stre ngth definitel y hel ped them win. Due to the COMBINE continuous development of new strategies by their coach, thi s wi ll be the DEVELOP fifth year in a row that the Dragons will play in the final. Their FIVE popularity has increased over the years and there is no doubt that HillbeU St adiu m POPULAR will be crowded wit h enthusiastic fans on the day of the final. If they play CROWD, ENTHUSE like today, they are sure to be successful SUCCESS o Complete using the words given. 1. Shakespeare is very famou s for game (n): a pa stime or a muse me nt; a contes t based o n rules, whose the many plays he result is determined by skill, wro te. knowledge, stre ngth or chance 2. I beat Tom at a game match (n): a n o rga nised game of foot ba ll, cricket or other sport of chess. - play (n): a piece of work written for the 3. Th e football cup final was the theatre (to be performed on most exciting match of stage) the season. 4. I hope to win beat (v): defeat sb in a competitio n or e lection 5. The op posi tion party win (v): achi eve first pla ce a nd ga in a elections on Sunday. prize in a competition the championship . beat the par ty in office in the earn 6. I _ _ -=:..:.:.:_ _ a good salary which allows me to li ve earn (v) : rece ive mo ney as payment for yo ur wo rk comfortably . gain [v}: acq uire sth (gradua lly) 7. The supermarket chain gave out free gifts to ga in more popular ity. match (v): (1) be in harmony wit h sth (2) have a pleas ing a ppeara nce 8. These shoes don' t fit me, I need a size bigger. 9. Fashionable women usuall y buy hand bags to match suit (v): whe n use d together (1) be convenient fo r sb o r the best choice in a pa rticular their shoes . 10. Buy the whi te bl ouse. The colour really suits you. sit ua tion fit (v): (2) ma ke sb look a ttractive be of the correct size or shape units 5-8 Revision 02 IGrammar Practice A Choose the correct answers. 1. Jim be watching TV. I just saw him outside. a. mustn't b. shouldn 't @ can' t d. might not 2. We are really looking forward the competition. a. entering b. to enter c. enter @ to entering 3. Playing ball in the classroom was a bad idea, boys. You could a window. a. broke b. have been breaking c. be breaking @ have broken 4. The girl admitted to her teacher. a. to lie b. be lying CD having lied d. to have lied 5. Do we attend the dance? a. ought to b. have got to c. must @ have to 6. The robber was made where he had hidden the money. @ to confess b. confess c. confessing d. to confessing 7. Mike, we borrow your CD player? We're having a party tonight. a. would b. will ® could d. must 8. I have forgotten this machine. Can you show me how? @ how to operate b. to operate c. operating d. how operates 9. It's difficult for me whether I should accept the job offer or not. a. decide b. deciding c. to deciding @ to decide 10. We saw the girls football as we drove past the field. a. play b. to playing c. to play @ playing 11. I don't think the company can afford any new staff this year. @ to employ b. to employing c. to have employed d. be employing 12. Don't you know that you put that watch in water? It's not waterproof. a. don't have to b. needn't c. didn't need to @ mustn' t 13. you tell me how much this costs? a. May @ Would c. Might d. Had better 14. "What would you like to do tonight?" "We go and watch a film." @ could b. would c. need d. have to 15. I think you consider buying the house. a. can b. need c. shall @ should B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. It was wrong of you to cheat in the exam. ought You ought not to have cheated in the exam. 2. Hearing that an earthquake had occurred was a great shock to us. shocked We were shocked to hear that an earthquake had occurred. 3. Steve doesn't mind travelling by bus. used Steve is used to travelling by bus. _________________________________________ pag e45 4. It is necessary to buy skiing equipment if you want to take lessons. have You have to buy skiing equipment if you want to take lessons. 5. It isn't necessary for her to pick us up from the airport. needn't She needn't pick us up from the airport. 6. Have you forgotten that you sent her a letter last month? remember Don't you remember sending her a letter last month? 7. I'm sure Ted isn't older than me because he went to school with my younger brother. can't Ted can't be older than me because he went to school with my younger brother. 8. He believes that we will visit him on Saturday. expects He expects us to visit him on Saturday. I Vocabulary Practice AChoose the correct answers. 1. "Have you seen Helga?" "She was here earlier but I haven't seen her a while now ." a. at Cb) for c. by d. about 2. Luke came across this old coin by while cleaning the attic. a. surprise b. himself (f) chance d. force 3. I borrowed the money the bank. a. to b. of c. for @ from 4. Would you like to help me these photocopies? a. find out G) give out c. get by d.counton 5. are allowed at the hospital between 5 and 8 p.m .. a. Clients <E) Visitors c. Hosts d. Guests 6. Bright colours people with dark complexions. a. fit b. effect c. match @ suit 7. When buying something, never forget to ask for the _ G!) receipt b. bill c. debt d. tip 8. The Dragons the Bulldogs in the football match yesterday. a. won b. earned (f) beat d. gained 9. My annual is $30000. a. currency b. fine c. charge @ income 10. He is keen buying a dog. arn b. at c. for @ on II. If you want to lose weight, you should on fatty foods. w cut down b. fall behind c. cut off d. get away 12. Can you what time the film starts? eaning a. end up b. get by c. fall out @ find out 13. I really well with Sally. She is one of my best friends. a. get off b. get over (f) get along d. get on with 14. Don't forget to the book you borrowed from John. a. give away b. give in c. grve up GU give back 15. I decided to contact him because it was the quickest way to reach him. Cil by phone b. by heart c. by boat d. by mistake page 46 B Complete using the correct form of the words in bold type. 1. Please send your application to 22 Market St. 2. You'd be impatient too if you had been wait ing for two hour s! 3. Thi s outfit is (un)suitable for the dance, don 't you think ? 4. The employees at Maxwell' s are all trained in customer servi ce. 5. The children' s excitement was obvious at the birthday party. 6. The film is a bit depressing as it deal s with the reality of homel ess people. 7. He wor ks with great enthusiasm 8. [ can 't find the solution to the last maths probl em. CComplete using the -ing form or the infinitive of the verbs in brackets. Next stop Mars... APPLY PATIENT SUIT EMPLOY EXCITE REAL ENTHUSE SOLVE Travelling (travel) to Mars might become (become) a realit y sooner than you think. Scienti sts are planning to send (send) astronauts to explore (explore) Mars in the near future . The surprising thing is that they are not planning to send (send) ani mals first, but insist on sending (send) people, even though it may be (be) risky. That's because scientists believe that it's the only way to find out (find out) if there is or ever has been life on the planet and if there could ever be (be). "We are in favour of exploring (explore) the possibility of being (be) able to live there . There's no point in beginning (begin) this expedition with animals, is there ?" asks Profe ssor Huxley . Other experts in the field object to sending (send) people up there so soon in the experiment. "We need to study (study) the.'planet as much as we can before we start doing/to do (do) anything. It's no good risking (risk) our astronauts' lives and spending (spend) millions of doll ars until we are absolutely sure ." unit 09 Articles A/An The indefinite article a/an is used before singular countable nouns or adjectives followed by singular noun s. a +consonant sounds an + vowel sounds a ruler, a European country, a university, an apple, an egg, an umbrella, an orange, a one-way ticket, a hospital, a blue overcoat an hour, an exciting holiday • Uncountabl e or plu ral countable nouns take some / any, etc. I've bought some magazines. We haven't got any more ice cream. • A/an is not used before uncountabl e nouns, except in certain expressions: It is (such) a pity / shame! A goo d knowledge of French is required for this ;ob. What a relie f! She has a love for / a hatred of / fear of dogs. • A/an - one: She has got a car. (We do not specify what kind of car.) They have got one car. (= only one, not more) ientists e ng e only ve ent. ns of Theindefinite article is used: 1. before a noun which is mentioned for the first time and represents no parti cular person or thing. 2. before a noun whi ch represents a group of people, animals or things. We can also use the or the plural form. 3. when talking about someone' s character, job or nationality. 4. in certain numerical expressions: a couple / dozen a thousand / million a half / quarter a great deal of a lot of a great man y 5. to talk about: price per weight or item distance per amount of fuel or speed frequency per time certain illnesses 6. before Mr/Mrs/Miss/Ms + surname when we refer to someone unknown. Use Examples They live in a flat. Take a break. A car is fa ster than a bike. The dolphin is an intelli gent animal. Children need love and affection. He is a pessimist. Her husband is an accountant. Howard is an Englishman. But: Claire is French. We need a hundred copies. A great many teenagers listen to music while doing their homework. They walked a quarter of a mile. This brandy costs £25 a bottle. My car does 50 miles a gallon/ 130 kilometres an hour. They go to the cinema twice a month. He has afever / a cold / a toothache. A Mrs Jones wants to see you. The Thedefinite article the is used before countable and uncountable noun s of all genders both in the singular and the plural. Thedefinite article is used: 1. before countable and uncountable nouns which are specific or have been mentioned before . I'll see the doctor tomorrow. The postman brought three letters and a parcel; the parcel was for Mary . The definite article is NOT used: 1. before countable and uncountable nouns whi ch refer to something general or have not been mentioned before. He likes coffee. Experience is import ant for this j ob. Whal es are mammals. page 48 2. before unique nouns. the Earth, the sky, the Pyramids 3. before names of seas, oceans, rivers, channels! canals, coasts, deserts, countries or regions (plural), groups of islands, mountain ranges: The Mediterranean, the Pacific, the Mississippi, the English Channel, the Panama Canal, the Blue Coast, the Kalahari Desert, the Netherlands, the Highlands, the Bahamas, the Andes 4. with buildings: cinemas, theatres, museums, galleries, pubs, restaurants, hotels, institutions: the Odeon cinema, the Royal Theatre, the British Museum, the National Gallery, the Black Buoy, the Pasta House, the Hilton, the British Council S. with newspapers, ships, services, organisations: the Guardian, the Queen Mary, the police, the United Nations 6. with names of families and nationalities (when we refer to the whole family or nation): the Simpsons, the Dutch, the Japanese The is optional with nationalities ending in -s (the) Greeks, (the) Australians, etc. 7. before musical instruments, dances, inventions and the word radio: Pedro plays the guitar and Rosa dances the flamenco. When was the telephone invented? We heard the news on the radio. But: I saw thatfilm Oil TV last week. 8. with the superlative degree of adjectives and adverbs. He is the best student in his class. Most does not take the when it is a determiner: Most students passed the exam. 9. with adjectives referring to classes of people: the old, the blind, the poor, the educated, etc. 10. with only, same and ordinal numbers + nouns This is the only pen I 've got. Dogs are not all the same. Who was the first astronaut to walk on the Moon? 11. before noun + of + noun: the gu{{ ofMexico, the Statue of Liberty 12. with titles (not accompanied by proper names): the King, the Queen, the Prince of Wales But: Queen Beatrix of Holland, Princess Margaret 13. with historical events or references: the Greek Revolution, the American Civil War But: World War II. 14. with the North, the South, the East, the West: Last year we visited the South of France. 2. before names of people, streets, cities, islands, countries, continents, mountains (singular), religious holidays, days of the week, months: Maggie Smith, Oxford Street, Berlin, Ibiza, Italy, Asia, Mont Blanc, Christmas, Friday, August But: the High Street, the Hague, the Vatican The is optional before the names of seasons when the meaning is general: Where do you usually go in (the) summer? The is used when we talk about a specific season. Do you remember the winter of 1987? 3. before names of squares, parks, lakes, stations Euston Square, Holland Park, Lake Ontario, Liverpool Street station 4. with pubs, restaurants, hotels, shops, banks, etc. whose names include the name of their founder or another proper name (e.g. a place) Jimmy's bar, Luigi's Restaurant, Emily's Hotel, Harrods, Lloyds Bank, Gatwick Airport S. before names of magazines, sports, games, colours, school subjects and languages: Newsweek (but: The Economist), tennis, chess, white, geography, Greek German is a difficult language. But: The German language is difficult to learn. 6. before names of airlines or companies: Air France, Interamerican, BMW, etc. 7. with meals (breakfast, lunch, dinner, snack): What did you havefor breakfast? But: When we talk about a specific meal, we use the: I didn't enjoy the dinner on the plane. . 8. before the words bed, court, church, home, hospital, prison, school, university, work when they are used for the purpose for which they exist: Thomas went to university to study engineering. But: Patrick went to the university to visit his professor. 9. before the words father, mother, mum, dad (when we refer to our own parents). Father / Daddy taught me how to drive. 10. before means of transport. I travel by car / by bus / by train / by air. Also: on foot, on horseback But: He was in the car / on the bus when I saw him. 11. with north, south, east, west when they are used as adverbs. They are heading west. 12. with some diseases (cancer, malaria, etc.) You should be vaccinated against malaria if you want to travel to the tropics. _________________________________________ page49 I Grammar Practice igious AComplete using a, an, the or -. Not just a cup of tea Asia, ___ tea is an evergreen plant. It was accidentally discovered by the Emperor nthe _ _ _ Shen Nung of China. Whilst on a trip, he was boiling a pot of water when a tea leaf fell into it. _ _ _ British sailors, returning from the Far eJ1JOO! East, brought packets of tea back ~ _ c. home as presents for their relatives. r The first advertisement for tea appeared in a newspaper called Mercurius Politicus in 1660. The advertisement in the newspaper said that tea could cure colds and other urs, illnesses. The poor were prepared to pay as much as a third of their weekly wage to have tea. ___ tea has been the most popular drink in Britain for three hundred years. The/ An average Briton drinks thirty cups of tea a week. In fact, the British import almost twenty-five percent of all -/the tea exported in the world. the: BComplete using a, an, the or -. 1. Jim plays the guitar in St Mark's Square every day. pital, 2. Unfortunately, there are a lot of accidents on the motorway between Athens and _ used Salonica. 3. Hyde Park is t he biggest park in London. 4. malaria is a disease carried by mosquitoes. 5. Every year swimmers attempt to swim across the English Channel. 6. Ibiza is an island off the coast of Spain and is part of the Balearic islands. 7. It has been a long time since I last spoke Russian. 8. Europe is the smallest continent on Earth, yet it is the most heavily populated. 9. most flowers bloom in the j - spring. 10. Every year millions of people visit the Statue of Liberty. him. 11. The colours of the Greek flag are blue and white. das 12. In 1995, t he United Nations celebrated their fiftieth anniversary. 13. father is taking us to a nice restaurant called Wheeler's on Sunday for ___ dinner. II want 14. Sophia is a mechanical engineer but she also writes for the Herald. 15. Head east for about a n hour and you 'll find the Palace Hotel on the right hand side of the motorway. page 50 CUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Julie said that her tooth was aching, so her father took her to the dentist's. had Julie said that she had a toothache , so her father took her to the dentist's. 2. Connor has become a very good saxophone player. learnt Connor has learnt (how) to play the saxophone very well. 3. He had to catch a bus to work this morning because his car had broken down . go He had to go to work by bus this morning because his car had broken down. 4. As a student, I couldn't afford a car other than that old Mini Cooper. only That old Mini Cooper was the only car I could afford as a student. 5. Did you know that a lot of rice is consumed in China? Chinese Did you know that the Chinese consume a lot of rice? 6. My weekly wage is $120, which isn't a great deal. week I get $120 a week , which isn't a great deal. 7. The government should help the people who are out of work, don't you think? unemployed The government should help the unemp loyed/unemployed people , don 't you think? 8. I'm really disappointed that he didn't win the race. pity It is a pity that he didn 't win the race. Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. The bank manager wants to go over the details go ahead (with 5th): start doing sth after of the loan before he approves it. planning it or ask ing permission for it 2. I suggest you go ahead with your picnic, go on (with sth): continue doing sth regardless of the weather forecast. go out: go over: stop burning examine, discuss or think 3. The fire went out after burning for seven hours. about sth carefully or in 4. The skirt goes with the vest. You can't buy them detail separately. go up: increase, become higher or greater than before 5. Interest rates have really gone up this month. go with: belong together with sth 6. I've filled in part of the application form but I can't else go on because I need more information. B Choose the correct answers. 1. Nobody warned me the side effects of this medication. a. in b. on @ about 2. This insect repellent will keep you safe all kinds of insects . a. with b. by @ from 3. The children were punished breaking the window. a. by <E) for c. since 4. I feel sorry Steven. Having to work such long hours must be very tiring. ofor b. about c. with 5. The thief, Peter Russell, has escaped Longbay Prison. ~ from b. in c. to list' s. ken t. _________________________________________ page 51 6. You shouldn't fight your brothers and sisters. a. about (i;)with c. on 7. The lifeguard saved the woman drowning. a. after b. since Cf) from 8. The search the lost boy lasted thirty-six hours. a. about b. with (£) for 9. You shouldn't have lied your friends about that. (i} to b. about c. with 10. The wedding will take place a Wednesday. a. in ® on c. by CComplete using the correct form of the words in bold type. THE ART OF ACTING My decision to become an actor/actress was not an easy one. After all, one's ability to ACT act well isn't enough. It isn't a stable profession. However, I find acting most enjoyable and am willing to live without job security ENJOY, SECURE I don't work on TV serials or anything like that. I only take part in theatre performances PERFORM It's most rewarding as you get the audience's immediate reaction . For example, REACT whendoing a humorous play, we all wait to hear the audience's laughter HUMOUR, LAUGH If we don't, we know that the production has been unsuccessfu l and we have failed. SUCCESS Eventhough I've had many years of experience, I'm always terrified and TERROR nervous before going on stage. But once I start performing, I quickly lose myself in NERVE theplay. Playing a character completely different from your own is always a challenge. oComplete using the correct form of the words given. loose 1. I've lost weight and this skirt is too for me to miss (v): (1) not attend or take part in sth because you are unable to, wear. don't want to or have forgotten 2. You won't believe what happened. I missed the plane! to (2) arrive too late to catch a 3. Karen has lost her passport and can't leave the bus/train/plane, etc. lose (v): (1) not know where sth is because country until she finds it. you have forgotten where you put it (2) to have been deprived of sth loose (odj): not tight 4. There has been a shortage of water this summer and as lack (n): when sth is insufficient or does not exist at all a result, we aren't allowed to water our gardens. shortage (n): deficiency, not having enough of 5. A lack of calcium in his diet didn't allow him to sth develop strong bones. 6. The teacher divided the students into four groups. reduce [v) : make smaller in quantity or size decrease [v] : become smaller in quantity or 7. During the summer sales, many shops reduce their size prices by up to 60 %. divide [v): separate sth into smaller equal 8. The national debt has decreased by one percent this year. parts 9. Craig is lying down because he's not feeling very well. lie (v): (1) (lie-lay-lain) be in a horizontal position; not standing or sitting 10. I suggest you lay the blanket on the ground before (2) (lie-lied-lied) not to tell the we sit down and have our picnic. truth 11. How can I trust you? You've lied to me so many lay (v): (lay-laid-laid) place sth somewhere times . I L unit 10 Nouns • T '-' tl A . Countable Nouns F Countable nouns can be counted and have singular and plural forms. They are defined by a/an, one in the singular and some, any, (a) few, etc. in the plural. Plural Formation Regular nouns • Most nouns take -s: car-cars • Nouns ending in -ch, -sh, -x, OS, -ss take -es: church-churches, fox-foxes, bus-buses • Nouns ending in -f or -fe form their plural in -ves: wolf-wolves, life-lives But: some nouns just take -s and some others form their plural in both ways: belief - beliefs, roof - roofs, safe - safes, scarf - scarfs/scarves Irregular nouns • Some nouns change completely in the plural: man - men goose - geese woman - women mouse - mice child - children louse - lice foot - feet ox - oxen tooth - teeth • Certain nouns are always in the plural form. These are: a. arms (=weapons), clothes, contents, customs, goods, people, police, scales, stairs, surroundings (=environment) b. all nouns that consist of two parts: binoculars, glasses, jeans, pliers, pyjamas, scissors, shorts, tights, trousers, etc. With these nouns we often use a pair of. • Some nouns of Greek or Latin origin form their plural by adding Greek or Latin suffixes: analysis - analyses criterion - criteria basis - bases phenomenon - phenomena crisis - crises medium - media ~ • Nouns ending in -0, normally take -es: tomato-tomatoes p But: nouns ending in vowel + -0 (e.g. radio), musical instruments (e.g. piano) and abbreviations L (e.g. photo), take -s: radio-radios, piano-pianos, photo-photos • Nouns ending in -y, drop the -y and take -ies: library-libraries But: nouns ending in vowel + -y, take -S. boy-boys, tray-trays • Some nouns are the same in the singular and the plural form: deer - deer species - species sheep - sheep series - series fish - fish aircraft - aircraft salmon - salmon means - means trout - trout crossroads - crossroads • Collective nouns describe groups of people: audience, class, committee, crew, family, government, jury, staff, etc. These nouns take a plural verb if they refer to the members of the group individually, and a singular verb if the group is considered as a unit. My family are organising a trip to Italy. (The family is seen as a group of individuals.) The government is thinking of increasing taxes. (The government is seen as one unit.) • Nouns preceded by cardinal numbers and used before C other nouns are always in the singular form: a ten-pound note (not a ten-pounds note) a three-year-old boy N r. B Some nouns have different forms for the masculine and the feminine gender: N husband -.. wife father -.. mother son -...daughter brother -.. sister uncle -.. aunt nephew -.. niece boy -.. girl (bride)groom -.. bride widower -.. widow host -.. hostess waiter -.. waitress prince -.. princess sf. steward -.. stewardess duke -.. duchess actor -.. actress hero -.. heroine king -.. queen ular is plural ience, , staff, tothe arverb efore incess hess _________________________________________ page 53 B. Uncountable Nouns Uncountable nouns cannot be counted and have no plural form. Some, any, (a) little, etc. can be used with most of them, but not alan/one. Food meat, cheese, bread, butter, fruit, fish, etc. Liquids milk, water, wine, beer, coffee, tea, etc. Material glass, wood, iron, paper, steel, gold, etc. Natural weather, heat, snow, lightning, Phenomena wind, rain, thunder, etc. Languages English, French, Greek, Japanese, Italian, etc. • The quantity of uncountable nouns is defined by other words that we can put in front of them : a cup of coffee/tea a bottle of wine/beer a glass of water/orange juice a pint of beer a jar of jam a piece of cake/advice/ information/news Diseases Sciences and School Subjects Games Abstract nouns Some Concrete Nouns measles, chickenpox, cancer, etc. Mathematics, Physics, Chemistry, Economics, Literature, etc. baseball, chess, billiards, darts, football, golf, soccer, poker, tennis, etc. beauty, freedom, love, honesty, justice, business, work, time, information, news, knowledge, accommodation, etc. baggage, furniture, money, luggage, traffic, business, etc. a piece/sheet of paper a bar of chocolate/soap a packet of tea/flour a can of soda a carton of milk a block of wood/ice a slice/loaf of bread a tube of toothpaste a lump of sugar a flash/bolt of lightning an ice cube/a sugar cube a clap/peal of thunder a pot of yoghurt • Some nouns can be either countable or uncountable, but with different meanings : Uncountable There's a lot of light in this room. This bottle is made of glass. She brushes her hair every morning. This table is made of pine wood. She loves walki ng in the rain. J've still got some work to do. Experience is important for this job. Countable Please, turn on the lights. He can't see without his glasses. He found two hairs in his soup. We saw a fox in the woods. How often do the rains come in Thailand? The motorway is closed due to mad works. We had some fascinating experiences when we visited Japan. C. Compound Nouns Compound Nouns consist of two parts. Be careful with their plural! Noun + noun reception hall -+- reception halls But: woman driver -+- women drivers Noun + preposition + noun sister-in-law -+- sisters-in-law Types of Compound Nouns -ing + noun dining room -+- dining rooms Noun + preposition passer-by -+- passers-by Adjective + noun greenhouse -+- greenhouses No noun (e.g. verb + preposition) a take-off-s- take-offs Grammar Practice A Put the words in brackets into the plural form where necessary. 1. Appliances Plus sells many different brands of ta pe recorders (tape recorder). 2. Tea , " s made from the dried leaves discovered five thousand years ago . 3. Margaret and Don have two three-year-old (three-j.rear-old) daughters _ twins 4. Jack: I can't see a thing . Brian: Do you want your glasses (glass)? Jack: No. It's the dim light (light) that is making it difficult to see. 5. The first three runners-up (runner-up) will each receive a medal. 6. The attic is full of mice (mouse). . ench dictionaries 7. The Italian and Fre -, --'" L f'. criteria 9. We are wai ting for all the staff (staff) to arrive before beginning the meeting. 10. That booklet has all the information (information) you'll need. B Choose the correct answers. 1. I'm really thirsty. Could you get me a of water? (l1.)glass b. jar c. can 2. 'Could I have a of cheese, please? a. bar @ slice c. sheet 3. I made a mistake. Could you get me a clean of paper? a. block b. packet @ sheet 4. Mum, where's the of marmalade? a. tube @ jar c. cup 5. A sudden of lightning lit the sky up for a second. @ flash b. clap c. block 6. This is a of my favourite soap. I love the way it smells. a. lump b. packet @ bar 7. Can I have two of sugar in my tea, please? ® lumps b. pieces c. pints C Complete using a, an, some, any or -. 1. I teach - History and - Spanish. 2. I'm really thirsty. Do you have any beer? Otherwise some/- water is fine. 3. An igloo is made from - ice. 4. I'd like some tomatoes, some/a lettuce and some oranges, please. 5. - cancer is a disease which a lot of people die of. 6. Have some food. You must be starving after playing - football all day. 7. We decided to replace the balcony door with a sliding glass door because we wanted more - light in the living room. _________________________________________ page 55 8. There isn't any paper left in the machine so I can't make any photocopies. 9. Jane would like some time off work. She needs a holiday. 10. Brian had an unexpected phone call from World Travel this morning. They told him that he had won a trip to Hawaii , including free accommodation. o Circle the correct answers. In some cases, both answers may be correct. 1. The the ship ready to sail. 2. Snow cover I (cover s) the whole valley in winter. 3. Scales (measur e)t measures weight. 4. Salmon (spend)! spends the first part of their life in a river. 5. The medium which @)t are used mostly for advertising is are television. 6. News travel/§VclS)fast nowadays. .iew. 7. The firewood you bought burn 8. The cheese on the table@1 are very tasty. Try it. 9. This series of books contain I information. 10. The staff(§l§attending the Chri stmas dinner tonight. E Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. They went on holiday to Tunisia for two weeks . week They went on a two-week holiday to Tunisia. 2. My glasses need changing, Mum. pair I need a new pair of glasses , Mum. 3. How many suitcases do you have? much How much luggage do you have? 4. He has travelled a lot by air, but he still gets nervous when the aircraft takes off. make Although he has travelled a lot by air, take-ofts still make him nervous. 5. Paul likes playing darts mor e than any other game. favourite Darts is Paul's favourite game. 6. It didn't rain a lot last year. had had (very) little rain 7. I'll give you some advice, Mary. a piece of advice of 8. She doesn't know a lot about astronomy. knowledge Her knowledge of astronomy is very poor. light page 56 Vocabulary Practice A Complete using the correct form of the phrasal verbs given. hand in: give sth (a document, homework, a notice of resignation, etc.) to sb in charge or of authority hand out: distribute sth to several people hang about: spend time at a place not doing anything important hang on: wait for a short time hang up: end a phone call and put down the receiver 1. A lot of my friends hang out at the local cafe. 2. The teacher handed out the test papers to all the students. 3. When she had finished the call , she hung up and went into the kitchen to tell her husband the news. 4. All the students had to hand in their essays by Friday. 5. Could you hang on a minute while I finish with this customer? 8 Complete using the prepositional phrases given. in addition (to): besides, as well as, also in advance: beforehand, before doing sth in bed: (still) sleeping or not having got up yet in the beginning: initially, at first in case of: as a precaution against in cash: in notes and/or coins in charge of: responsible for sth reveal [v): confess (v): admit (v): agree [v}: accept (v): uncover or expose sth hidden, make it known to people admit that you have done sth wrong or shameful acknowledge that sth is true have the same opinion as sb else about sth say "yes" to sth or agree to take sth prevent (v): (1) make sure that sth wil l not happen (2) make it impossible for sb to do sth avoid [v]: take action so as not to do sth unpleasant 1. We've given some money in advance and we'll pay the rest when we get the car. 2. Scott is a foreman and is in charge of many workers. 3. Victoria doesn't feel \\ 'ell. She 's been in bed J morning. 4. The price includes the flight and hotel accommodation. In addition , you'll be provided with a rental car. 5. Will you pay for the items in cash or by credit card ? 6. You must have a first-aid kit in your car in case of an emergency. 7. The children were excited about the trip in the beginning , but now they've lost interest. , ~ 1 1 " confessed questioning. 2. Will you admit that what you did was wrong? 3. Statistics revealed that people are recycling rubbish more than they did in the past. 4. I don't agree with the new policy the committee has introduced. accepted wonderful parties. 6. I avoid walking down dark streets at night. 7. Wearing a seat belt could prevent you from getting hurt in an accident. unit Adjectives - Adverbs - Comparisons 11 A . Adjectives nts. o Adjectives are placed before nouns to describe them. He is afamous author; everybody knows his novels. entinto o They have the same form in the singular and the plural. They live in a large house near the beach. This neighbourhood is full of large houses. o They can follow expressions of measurement. The river is 50 metres wide. ay. o Adjectives may appear after linking verbs (appear, be, John is lucky to have afriend like you. s become, come, get, go, grow, keep, prove, remain, seem, stay, turn, etc.). After the verbs feel, look, smell, sound, taste, we use This soup tastes good. adjectives, not adverbs. This music sounds awful. Adjectives beginning with a- (afraid, alive , alone, She 's been awake since six o'clock. awake, etc.), ill and glad appear only after linking She f ell seriously ill last year. verbs. I'm sure he'll be glad to meet you. • We use adjectives such as young, old, blind, deaf, poor, rich, unemployed, illiterate, y therest etc. with the definite article the to describe groups of people in term s of age or status. In this case, the adjectives are not followed by nouns and the verb of the sentence is usually in the s. plural . iearly all • We can also use as adjectives: ~ nouns fallowed by other nouns describing material and purpose. Amy got a gold bracelet as a birthday present. ~ nouns preceded by cardinal numbers. My house is only a ten-minute walk from here. card? ~ present and past participles. an She heard a frightening noise. He won a well-deserved gold medal. , but Order of adjectives NUMBER OPINION FACT NOUN Size Age Shape Colour Origin Material Purpose t hours of Three practical small new rectangular yellow Korean plastic lunch boxes ng? B. Adverbs bbish verbs, e.g. Read the instructions carefully. adjectives, e.g. I'm awfully sorry about what happened. Adverbs describe other adverbs, e.g. He speaks very quickly. whole sentences, e.g. Apparently, he has forgotten our appointment. mittee ves getting Adverbs Adverbs of manner (seriously , happily, quietly, etc.) Adverbs of place (here, there, etc.) Adverbs of time (now, today, soon, recently, etc.) Order of adverbs: Adverbs of frequency (occasionally, rarely, often, always, etc.) Adverbs of degree (rather, quite, very, hardly, absolutely, etc.) Sentence adverbs (apparently, definitely, obviously, probably, etc. ) Use and Placement Placement They appear in any position in a sentence. At the beginning of a sentence, they show emphasis. • In the active voice, adverbs of manner usually go after the main verb and its object. In the passive voice, they are usually placed before the main verb. They usually appear at the end of a sentence or after the verb and its object. They are usually placed at the end of a sentence. They may appear at the beginning for emphasis. • One syllable adverbs (soon , then, etc.) usually appear in the middle of a sentence. • Just goes after the auxiliary verb. manner - place - time • after verbs of movement: place - manner· time They usually appear before the main verb but after the (first) auxiliary and the verb "to be". They usually appear before the word they modify. • a + quite/rather + adjective + noun or quite/rather + alan + adjective + noun But: a + fairly/pretty + adjective + noun They express how sure we are about what is said and they appear: • at the beginning of a sentence. • before the main verb or after the auxiliary. • at the end of a sentence. Examples He dictated the letter slowly. He slowly dictated the letter. o a' Slowly, he dictated the letter. Some people learn languages easily. t Some languages are easily learnt. a, a I'll see you there. IT Call him tomorrow. Last year we went to Spain for our holidays, but this year we'll stay in Greece. I'll soon need a new pair of shoes. She has just arrived. Did you work hard at school yesterday? Did you go to Paris by plane last summer? She rarely listens to classi cal music. I've always wanted to live in Paris. He is never at home on Sundays. I absolutely love this film. The trip was rather interesting. It was a rather dangerous expedition. It was rather a dangerous expedition. It was a pretty dangerous expedition. Apparently, he won't be here on time. You've obviously made a mistake. She is very beautiful, undoubtedly. • Some words end ing in -Iy are adjectives, not adverbs: deadly, elderly, friendly, lively, lonely, lovely, silly, etc. The adverb of these adjectives is formed with "in a ... way/manner". He is a very friendl y person. Th at's why everybody likes him. He treats his employees in a very friendly manner. • Some other words ending in -Iy are both adjectives and adverbs: hourly, daily, early, weekly, monthly, yearly, etc. This is a daily programme. He brushes his teeth twice daily. • Pay attention to the meaning of the following adverbs: late = not early lately = recently hard = with a lot of effort hardly = almost not any near = close nearly = almost ________________________________________ page 59 C. Comparisons Formation of comparisons (Adjectives and Adverbs) one-syllable adjectives and adverbs sity. t. two-syllable adjectives and adverbs ending in -y adjectives and adverbs with morethan one syllable r Positive Comparative short fast shy short-er fast-er shy-er funny early funnier earlier modem often more modern more often Irregular Forms inGreece. s. Positive Comparative Superlative good/well better best terday? • badlbadly worse worst old older/elder oldest/eldest t summer? far farther/further farthest/furthest {sic. much/many more most ris. little less least Elder/Eldest describe family relations. Elder is not followed by than. My elder brother is studying in England. ition. My brother is older than me (not elder than me). ition. 'tion. Farther/Farthest are used only for distance. time. Further/Furthest are used for distance but they e. also mean more/most. 1y. Today we walked farther/further than we did yesterday. There are no further details available yet. ,lonely, Type as..,as like eekly, the same as not so/as + + as not such a + + noun + as comparative/superlative twice/three times as...as less...than theleast... the+ comparative... the + comparative comparative + comparative Superlative the short-est the fast-est the shy-est the funniest the earliest the most modem the most often Be careful with: hot - hotter - the hottest simple - simpler - the simplest dry - drier - the driest quiet - quieter - the quietest or quiet - more quiet - the most quiet But: recent - more recent - the most recent Comparative + than Mary is taller than Anne . [Of all / period of time The + superlative + f in + place / group 0 people Nick is the best student of all/in his class. Rudolf Nure;ev was among the most important dancers of the 20th century. When we compare two people or things, we can use the + comparative (not the + superlative) . Sam is the taller of the two brothers. • We can emphasise the meaning of adjectives and adverbs by adding : ~ very, pretty, most, rather, quite, fairly in the positive degree. He was most annoyed by the flight delay. ~ a bit, a lot, even, far, much, rather in the comparative degree. She is for more attractive than her sister. Types of Comparisons Use Similarity Dissimilarity Superiority Inferiority Successive comparison, meaning that the second depends on the first. Successive comparison, indicating a continual change. Examples 1 won't miss a film as interesting as that one. He must be sleeping like a log. This exercise is the same as the previous one. A bicycle is not so/as fast as a car. Tim is not such afast runner as his brother. A car is faster than a bicycle. This is the slowest car I've ever driven. He works twice as hard as his son. Italian food is less spicy than Indian. This is the least interesting book I've ever read. The sooner we arrive, the better. The more you study, the more you learn. The ozone layer is getting thinner and thinner. page 60 Grammar Practice A Put the words in brackets in the correct order. 1. My father always uses a big round aluminium frying pan to fry fish in. (alan, aluminium, big, round, frying) 2. Mr Brown found three old French wine (French, old, wine, three) 3. I got a beautiful blue Italian silk (alan, Italian, silk, blue, beautiful) 4. We have an anti que oval oak dining (a/an, oval, antique, dining, oak) 5. That is a strange triangular green glass (a/an, strange, green, glass, triangular) B Choose the correct answers. Pre-school teaching is a lot (l) than most other jobs. People think that looking after young children is (2) than looking after (3) children, but then again the job is not as (4) as some might think. What makes it difficult is that the (5) _ they are, the (6) responsibility you have. Small children can be (7) . They are (8) warned than adults about saying "inappropriate" things. Also, they are three times (9) energetic as adults. The (l0) moments in the classroom are when it's quiet. Of course, you always get some children who are (l1) and (12) than others by nature. I arrive at work (l3) than teachers who work with (l4) children. Sure it's not the (15) job in the world nor the (l6) paid. In fact , I know I could work elsewhere for (l7) hours and get paid (l8) money. However, I believe it's a (19) _ rewarding job (20) many others I can think of. bottles which are very valuable. scarf for my birthday. table. ashtray. Don't you think? 1.0 more demanding 2. a. easiest 3.@0Ider 4. @bad 5. a. young 6. a. most 7. a. funniest 8. a. little 9. a. so 10. a. rarer 11. a. shy 12.@more quiet 13. a. earliest 14. a. old 15. a. easier 16. a. good 17. a. few 18.@more 19. a. much 20. a. of b. demanding c. most demanding b. more easier @ easier b. elder c. oldest b. badly c. worse @ younger c. youngest b. much @ more @ very funny c. much funny @ less c. least b. like @ as b. rarely @ rarest @ shyer c. shyest b. quiet c. more quieter @ earlier c. early @ older c. oldest b. easy @ easiest b. better @ best @ fewer c. fewest b. much c. most b. most @ more ., than c. from 1 _________________________________________ page 61 CCircle the correct answers. 1. The Johnsons bought a beautiful house at a much / airly good price. 2. I was able to finish reading the book most sooner than I thought since I had some free time. 3. The baby' s temperature must have risen. He feel s very / (even)warmer than before . 4. Ray' s part y is going to be (quite)! fairly an exciting event. He told me that it's going to cost him very / 0more than last year 's. 5. This is a bit good educational programme for children. 6. I'm leaving for the USA pretty / (a lot)sooner than I had originally planned. 7. It's very marvellous that you could make it to the reunion. 8. Margaret finds taking much rel axing. 9. I like the car but it' s a rather / @!)more expensive than I thought it would be. 10. It must be far / retty exciting travelling all over the world . ing DRewrite the sentences using the adverbs in brackets. 1. Kimwill go camping. (in the spring/probably/there) Kim wil l probably go camping there in the spring. 2. Steven knew nothing about the robbery that took place. (absolutely/yesterday/apparently) Apparently, Steven knew absolutely nothing about the robbery that took place yesterday. 3. That restaurant is expensive, so I won't come with you. (definitely/rather/tonight) That restaurant is rather expensive, so I definitely won't come with you tonight. 4. Young people find part-time work. (nowadays/in the summer/often) Nowadays, young people often find part-time work in t he su mmer. 5. Peter has arrived but I'm sure he has for gotten about our meeting. (completely/just/pretty) Peter has just arrived but I'm pretty sure he has comp lete ly forgotten about our meeting. EUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. We can't afford such an expensive holiday. as We can't afford a holiday as expensive as that. 2. As we climbed higher, we had more diffi culty breathing. harder The higher we climbed, tile harder it was to breathe . 3. Jane gave us a warm welcome when we arri ved. friendly Jane welcomed us in a friendly way/manner when we arrived. 4. The weather was getting worse by the minute, so we decided not to go out. and The weather was getting worse and worse , so we decided not to go out. 5. Chris skates better than his sister Anne. such Anne is not such a good skater as her brother Chris . 6. The journey was less tiring than I thought it would be. as The journey was not as/so tiring as I thought it would be. 7. This is the worst book I have ever read. a worse book than the same as page 62 Vocabulary Practice A Complete using the correct form of the phrasal verbs given. hold on : hold on to: hold up: hurry up: keep back: keep off: keep on : wait for a short time hold sth (1) delay sb or sth (2) rob make haste, do sth quickly reserve sth, not reveal or give away all of it stay off st h continue doi ng sth keep out (of) : stay outside a place, not enter keep up (with) : maintain the same level or speed as sb else 1. Can't you read the sign ? It says keep off the grass! 2. Craig kept on working despite being tired. 3. Could you hold on a minute while I phone Mr Bent? 4. No matter how hard I tried , I couldn't keep up with Samantha in the race. 5. Cou ld you hold on to these bags while I buy some bread? 6. Hurry up ! If we miss the bus , the next one isn't for an hour. 7. A masked man held up the Nat ional Bank this morning, but he was caught later in the day . 8. The police kept back information about the murders so as not to scare people. t ho ,.Jr.,., out 9. Please, keep ...'"' .... vE> v, . ..'"' ~ H , " , l I ' - ' l I because I've just was hed the floor. S Complete using the prepositional phrases given. in common: in comparison with: in conclusion: in control of: in danger: in detail: in the end: in fact: in fashion: in favour of: shar ing certa in thin gs or characteristi cs com pared with lastly, final ly having the power to manipul ate sth or make deci sions about it in a dc nqerous situation ana lytica lly, prec isely finally, lastly actua lly, in rea lity fashionabl e supporting st h in good/bad condition: in good/bad shape in sb's free time: when sb is not busy 1. The presi dent of the company is the man in control of everything. Nothing can be done without his approval. 2. In conclusion , I would like to thank you all for listening to me. 3. What do you do in your free time ? Do you read books ? 4. I agree with you. I am In favour of renovating the house. 5. The witness was asked to describe in detail the events which took place on 26 March. 6. In comparison with last year's recor ds, it seems that our sales have increased. 7. These bright colours are in fashion this summer. 8. Even though we are brother and sister, we have nothing in common 9. You should buy this second- hand car. It really is in good condition 10. This painting looks like an original Monet, but in fact it is a copy. 11. We couldn't decide where to go for a holiday, so in the end we consulted our travel agent who suggested New Zealand. 12. If you continue spending money like this, you are in danger of losing your business. hour. ng, as ks? ouse, the sales er. _________________________________________ page63 CComplete using the correct form of the words in bold type. WHAT'S ON THE TELLY TONIGHT? After 1948, the Hollywood studios, where films for the cinema were produced, faced a new kind of competition. The arrival of television. ARRIVE At first, Hollywood didn't worry. After all, John Baird's invent ion could only INVENT produce small black and white pictures. However, they were mistaken. weekly Tothe astonishment of the Hollywood studios, by the early 1950s ASTONISH, WEEK attendance at cinemas had dropped by fifty percent. end less Television today has become part of everyday life. These boxes give _ END hours of pleasure to millions of people. It is also an economical form of PLEASE, ECONOMY entertainment. However, TV can also be harmfu l and not only for the eyes. For HARM instance, programmes containing scenes of violence can influence children's VIOLENT behaviour negatively. BEHAVE Who would have thought that television would influence our lives so much? oComplete ~ i n g the words given. 1. I avoid foods that have artificial additives. false (adj): (1) incorrect, untrue, mistaken (2) artificial, not 2. Call the police. These American dollars are counterfeit real (e.g. false teeth) 3. It felt so unreal seeing all my high-school friends artificial (adj): not natural (e.g. artificial after 15 years! flowers) false 4. In the 1970s wearing eyelashes was very fake (adj): sth looking valuable or genuine in order to fashionable. deceive people (e.g. a fur 5. This is a very good imitation of the painting. coat) untrue 6. That statement is . I have papers to prove it. unreal (adj): (1) not real, imaginary (2) bizarre, so strange 7. This architecture is different to anything I've ever seen that you can't believe it is before. happening 8. This isn't a real diamond. It's a fake untrue (adj): not true, not based on fact different (from/to) (adj): not the same imitation (n): a copy of sth, made to look as if it were genuine (e.g. imitation leather) counterfeit (adD: (money, goods, documents, etc.) not genuine, but looking genuine in order to deceive people 9. Authent ic Asian cuisine has some unusual herbs. authentic (cdj}: genuine original (cdj): the first and genuine 10. You keep the original copy and I keep the photocopy. form of sth (a document, a work of art, etc.), not a copy unit 12 Determiners A. Some I Any I No I Every / Each Some, any and no are used with countable (singular and plural) and uncountable nouns. Each and every are used only with singular countable nouns. The compounds of some, any, no and every are pronouns; no noun can be used with them. some someone/somebody something somewhere any anyone/anybody anything anywhere no no one/nobody nothing nowhere every everyone/everybody everything everywhere each Use • in affirmative sentences • in questions when a positive answer is expected • in polite requests and offers • in questions • in affirmative sentences, meaning "no matter which" • in negative sentences when not or other negative words (hardly, never, rarely, etc.) are included • in negative sentences instead of not any; no other negative words can be used • when we consider people or things as a group • with nearly and not everyone of + plural noun/pronoun • when we consider people or things separately each (one) of + plural noun/pronoun Examples Someone took my keys by mistake. Are you looking for something? Would you like some cake? Is anyone in the kitchen? You can visit us any day next week. I don't eat anything spicy. Hardly anyone has arrived yet. He has nowhere to go. Every car has a steering wheel. Nearly every house in this area has a garden. Not every room has a nice view. I found every one of these books interesting. Each student came up with a different idea. Each one of them received a free copy of the magazine. . __________________________________________ page 65 B. Much I Many I A lot of I (A) little I (A) few Countable Uncountable Use nouns nouns many much ed afew a little few little Countable and uncountable nouns alot (of) lots of plenty (of) c. Both I Either I Neither I Most I All I None / Whole For two people or things Determiner Both (of) Both ... and Either Either of Either.,. or Neither Neither of of Neither ... nor Most Most of All All of None None of • mostly in questions and negations • in affirmative sentences with too, so , how and as • at the beginning of the sentence (in formal English) • they show a small amount (positive meaning) and can be used with only. • they show a very small amount (negative meaning) and can go with very, so, too, as and how. • in affirmative sentences before nouns and pronouns A lot, Lots and Plenty can also be used without nouns. Examples Are there many homeless people in Athens ? There is too much sugar in my coffee. Much mon ey is spent on space exploration. She has lived in Englandfor a f ew years. I've only got a littl e work to do. There are very few pencils on the table (not enough for everyone). There 's too little sugar in my coffee. A lot of cars rem on unleadedfuel. We needn 't buy any more bread; we've got pl enty. Use • It has a positive meaning and goes with a plural verb. • They state that something is true for two people or things. The verb of the sentence is always in the plural form. • Either means "any one of the two". • Either of goes with a singular or plural verb. • They state that something is true for anyone of two people, things, etc. The verb of the sentence is either in the singular or plural form. • Neither means "not one and not the other". • Neither of goes with a singular (formal) or plural verb (informal). • They have a negative meaning and state that something is not true for either of the two people or things. The verb of the sentence is either in the singular or plural form. Examples Both my brothers are engineers. They both live in England. Both of them saw the film. Both Tim and John like football. Paris or London ? Either city is beautiful. Either of these cities is/are beautiful. Either he was too busy or he didn't know about the party. Neither book was interesting. Neither ofmy parents works / work at weekends. Neither Tim nor John likeis) fo otball . For more than two people or things • They have a positive meaning and go with a plural verb. All + that-clause + singular verb =The only thing... • None has a negative meaning. It is not followed by a noun. • None of is used before nouns or object pronouns with a singular or plural verb. Most young people like pop music. Most ofmy friends live in Athens. All ofthem enjoy picnics. All (that) he does is criticise me. Any questions ? No, none. None ofthe students speaks/speak German. None of them wants/want to leave. Whole (=complete) goes between a determiner and a singular countable noun . She spent the whole evening watching TV Grammar Practice A Circle the correct answers. 1. Christopher: Does (anyone)/ someone need the car for the next hour ? I need to go anywhere Michael: No, I don't. Darren: Neither do 1. I've got anywhere go, so take it. But on your way back, could you get (each one of)! everyone us an ice cream? 2. Louise: You sit in the sun nearly (every) / each day. Aren't you worried about getting burnt? Marion: Oh, I never stay in the sun for too long and I always put on any lotion. 3. Catherine: I haven't had(anything)! something to eat today. Alexander: I'm so hungry that I could eat something the table. Catherine: We can eat as much as we like. Every / (Everyone)else has eaten. 4. Receptionist: Are you looking no one? Woman: Yes, I am. Mrs Byrne. Receptionist: Let's see...Oh yes, she's on the third floor, in room 309. Woman: Could you also tell me what the morning visiting hours are? Receptionist: You can visit patients in this hospital at(any)t notime as long as it's not after midnight! S. Salesperson: Every of these cars has air-conditioning. Customer: Do all of them have airbags? Salesperson: No, not each / (every)car has an airbag. B Circle the correct answers. 1. (Many)/ Much people showed up at the concert. 2. (Few)! Little people go mountaineering during the winter. 3. There's a little time left to get ready for the dance. 4. You needn't apply any more suntan lotion; you 've got plenty of S. There is(a lot ofJ! a lot traffic on the motorway . 6. You didn't make much mistakes in the test, but you should be more careful with your spelling. 7. We've only a few petrol left. We'd better stop at the next petrol station. 8. We need to get(a few)! few stamps from the post office. I want to send off my Christmas cards. 9. I couldn't find many I(much)information on ancient Greek art in my encyclopaedia. I'll go to the library. 10. How(much)1 many bread do you want me to buy? C Complete using both, either, neither, all, none or whole. 1. I can 't wear either of these two jumpers. Both of them need washing. 2. Some siamese twins have to spend their whole life joined together. 3. You can eat either/both of these two small pies but leave the big one for John. 4. I don't think the address I have is correct. I' ve sent him several letters but I've received none in return. All el g. 11m. able. --------- page 67 6. After she had talked to her two older sisters, she told both of them that she appreciated their advice but that she would do what she thought was right. 7 Neither of my parents can drive us to school because they're at work. 8. I had an awful Sunday. I spent the whole day cleaning. 9. Tanya, Robert, Craig and I are corning to visit you . Don't cook anything because we had a big lunch and none of us are hungry. 10. Sally has been sick all week. I hope she starts feeling better soon. oChoose the correct answers. Sometimes both answers may be correct. 1. Both actors Shakespeare beautifully. 5. Neither of them Spanish very well. @ perform b. performs ®speak @ speaks 2. Either dress fine. 6. Nobody arrived, so we can't start the @ is b. are meeting yet. 3. Everybody wearing formal evening G) has b. have clothes. 7. All Derek does complain. @ is b. are a. are @ is 4. Each room of the house painted a 8. None of us a car, so let's rent one. different colour. @ has @ have a. were @ was EUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. It's unbelievable, but not a single dress in that shop suited me. none It's unbelievable, but none of the dresses in that shop suited me. 2. This restaurant doesn't have any English-speaking waiters. no There are no English-speaking waiters in this restaurant. 3. She was doing her Christmas shopping all afternoon. the She spent the whole afternoon doing her Christmas shopping. 4. I thought that both novels were boring at the beginning. neither I thought that neither novel was int eresting at the beginning. 5. Mark, the only thing you do is watch TV! all Mark, all 'IOU do is watch TV! 6. There aren't a lot of things to do in a village. much There isn't much to do in a village. 7. I always take my sunglasses with me wherever I go. never never go anywhere without my sunglasses. 8. Jim bought two books last week, but he hasn't started reading them yet. of Jim hasn't started reading either of the books (that) he bought last week. ~ - page 68 u Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. If you don't like garlic, leave it out of the recipe. knock down: (1) hit sb (with a vehicle) 2. Don't forget to lock up when you leave the house. and cause them to fall down (2) pull down a building or 3. My best fr iend has never let me down . She 's part of it always there for me when I need her. knock out: make sb unconscious 4. I heard that the City Council has decided to knock down that old knock over: hit sb (with a vehicle) and cause them to fall down building and build a car park in its place. leave out: not include 5. The boxer knocked out his opponent in the second round. let down: disappoint sb 6. The driver didn't see the man crossing the street and knocked lock out: prevent sb from entering by him down/over . locking the doors lock up: (1) place sth somewhere and 7. I accidentally locked out the cat last night, so it slept on the fasten the lock front doormat. (2) make sure that all the doors and windows of a building or a car are locked ~ B Complete using the correct form of the words in bold type. NOT FOR THE FAINT-HEARTED! Sky-diving isn't something new, but courageous cameramen jumping out of planes COURAGE with all the necessary equipment to film a sky-diver, is. The cameramen are not of EQUIP course totally inexperienced ,as they go through a training programme. EXPERIENCE, TRAIN After a lot of thought and careful planning this amazing idea was put into THINK 1 practice so that judges could observe the sky-divers' skilful manoeuvres from SKILL the ground. Then they judge them accordingly in competitions at a height of COMPETE, HIGH 1 over 10000 feet! The pictures are shown on huge screens on the ground for the judges. Crowds gather and look on with curiosity and amazement at seeing such a CURIOUS, AMAZE dangerous sport in action. 1 C Complete using the words given. 1. He was impolite and had bad manners ,as he spoke with 1 behaviour (n) : social conduct, the way a person or an animal behaves his mouth full. 1 manner (n) : the way sb does sth 2. Clients trust Mrs Parker as she always deals with them in a manners (n): social conduct very professional manner habit (n): sth you do often or regularly 3. The dog's strange behaviour made us realise that something routine (n) : the usual series of things sb does regularly at a particular was wrong. time 4. When I'rn nervous, I am in the habit of biting my nails. 5. Part of our daily routine includes a jog before breakfast. 2 3 - ld IN g s. units 9-12 03 Revision IGrammar Practice AChoose the correct answers. I. "Who is it?" _ _ _ _ _ Jenny." a.My b.I'm 2. You should hear Lucy play ®the b. one guitar! @ It ' s c. some d. a d. Mine 3. There's freshly squeezed orange juice in the fridge if you 're thir sty. a. a (1;) some c. one d. little 4. can come to the club. You don't need to be a member. a. Someone b. Every c. Each one @ Anyone 5. "Saturday or Sunday"? _____ day is fine. Come whenever you like ." a. Neither @ Either c. Both d. None 6. They had ashtrays on the table . @ two square glass b. square two glas s c. glass square two d. two glass square 7. My nephews speak French really _ a. good b. better @ well d. best 8. Coffee is cheap at this supermarket but it costs even at Save Supermarket. a. least b. more little c. little @ less 9. There is food left but not enough for everyone. a. little CW a little c. few d. a few 10. I have never seen tall building as that before. a. a so b. a more 0 such a d. a such II. Don't forget to buy a of toothpaste for the trip. a. can ® tube c. carton d. pint 12. Neither Julie nor Sue to work today because they are both ill. a. goes b. isn't going c. aren' t going @ is going 13. If you require any , please contact my secretary. ®further information b. further informations c. farther information d. farther informations 14. The we work out, we become. a. most ... the fitter b. more ... the more fitter @ more ... the fitter d. more ... the fittest 15. All he does is all day long. a. to sleep b. sleeping c. sleeps @ sleep BUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) I. OnSunday nights, the roads into Athens are very busy. traffic There is a lot of traffic on the roads into Athens on Sunday nights. 2. None of these books are more informative than the encyclopaedia. most The encyclopaedia is the most informative of all these books. 3. The attic doesn't have any windows. no There are no windows in the attic. • I • page 70 4. The mechanic made a careful inspection of the car to see what was wrong with it. inspected The mechanic inspected the car carefully to see what was wrong with it. 5. I attended a course at Kent College for two months. on I went on a two-month course at Kent College. 6. I can't live in such a small flat. as I can't live in a flat as small as this. 7. In my opinion, both hotels are expensive, so let's find another one. cheap In my opinion, neither hotel is cheap , so let's find another one. 8. I don't think that Japanese is easy to learn. language I don't think that the Japanese language is easy to learn. Vocabulary Practice AChoose the correct answers. 1. the grass! a. Go out @ Keep off c. Move out d. Pull over 2. Please don't the phone on me again! a. hand in b. hang out @ hang up d. hang on 3. We didn't have to pay for the furniture in but on the day of delivery. a. time @ advance c. cash d. future 4. My children have excellent table _ @ manners b. manner c. behaviour d. habits 5. You can't traffic in the city centre in the afternoon, so why don't you go in the morning? a. prevent b. miss @ avoid d. lack 6. flowers are usually made of plastic or silk. @ Artificial b. Untrue c. False d. Unreal 7. He never he is wrong. @ admits b. reveals c. confesses d. agree 8. I the concert because of the exams. a. lost b. loss @ rnissed d. loose 9. The teacher needs to the class into two to play the game. a. decrease (li) di vide c. reduce d. shortage 10. The government the name of the spy last night. a. admitted b. agreed c. confessed @ revealed 11. Jenny is Korean, so she cooks Korean food. @ authentic b. imitation c. artificial d. original 12. We decided to our old house and build a new one. a. knock over ® knock down c. knock out d. let down 13. That scarf really that dress! It's a perfect match. a. goes up @ goes with c. goes over d. goes on 14. Can you clean the kitchen to the bathroom? a. in advance b. in case @ in addition d. in change 15. The reception took place Saturday. @ on b. in c. at d. by _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ page71 BComplete using the correct form of the words in bold type. l. We shouldn't hire such a young and inexpe rienced man for a job as difficult as this one . 2. It is said that electricity is the greatest invention 3. Everybody liked the play and the critics said that it was definitely a success 4. Entering the burning house to save the little boy was a very courageous thing to do. 5. Despite their terrifying appearance, most dinosaurs were harmles s vegetarians. 6. We didn't find our trip unpleasant although it was raining. 7. His react ion to the news was unpredictable. 8. She looked at me in amazement CComplete using only one word in each blank. EXPERIENCE INVENT SUCCEED COURAGE HARM PLEASE REACT AMAZE Roller-coasters have been around for over one hundred years and their popularity is constantly increasing. the for their speed, length or height. They love the feeling of not being (2) in control, the speed and the "sickening" feeling in their stomach. Some roller-coasters are made of pine wood. These rides feel (3) les s safe because the track shakes and makes (4) more/ rather a lot of noise. As a result, the rides seem (5) very/extremely dangerous. However, they are just (6) as safe as steel frame ones. Besides, all roller-coasters are equipped with safety bars which people hold (7) on -=-" to and which can (8) prevent riders from falling off. 1 unit 131Pronouns Possessives A. Personal Pronouns Personal Pronouns replace nouns and are used as subjects (I , you, he, she, it, we, you, they) or objects (me, you, him, her, it, us, you, them) of verbs. John is 171Y cousin. He lives next door. Have you seen him lately? Pronouns Use Examples He/Him • for people, babies and animals if we know their gender Don 't go near that dog; he could bite you. She/Her ~ Shelher can also be used for ships and countries. The large cruise ship looked impressive as she steamed out of the harbour. It • for things, babies and animals (if the gender is unknown It's a really cute baby. or unimportant) • in expressions of time, distance, weather and temperature It 's twelve o'clock. • when we are asking or saying who a person is It was very cold last Christmas. • at the beginning of a sentence, instead of a full infinit ive Who is it ? It 's Mary. or a that-clause It is not wise to lend money to strangers . • as the subject of the verbs appear, depend, happen, It seems that he is not enjoying the party. look , occur, seem , sound, etc. • It takes + (object) + time expression + full infinitive It took an hour to drive to the airport. Subject + take + time expression + full infinitive Anne will take at least two hours to iron these clothes. • There + be is used for something we mention for the fir st time. It + be/other verb is used for something that has already been mentioned. There was a letter for you this morning. It is on your desk. B. Possessive Adjectives Possessive Adjectives (my, your, his , her, its , our, your, their) are always used before a noun (without an article). They have the same number and gender as the owner. my parents, her bicycle, their clothes • If we want to emphasise that somethi ng bel ongs to only one person, we use my/your, etc. + own + noun. They have theirown flat. • on my/your/his, etc. own = al one, without hel p Mary does her homework on her own. c. Possessive Pronouns Possessive Pronouns (mine, yours, his, hers, ours, yours, theirs) replace my/your, etc. + noun. They are never followed by nouns. Shall we take your car or mine? A/an + noun + of + mine/yours, etc. =one of + my/your, etc. + noun a friend of mine=one of my fri ends Possessive case Form Use Examples 's • singular nouns (people or animals) Tim's computer, the dog 's collar • someone/somebody, anyone, etc. It 's nobody's fault. • irregular plural noun s (not ending in -s) the children 's clothes • compound nouns myfather-in-law's car 00, bite you. essive tngers. party. rticle), + own ver _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ page 73 • time expressions/idioms today's weather, last Sunday's newspapers, for heaven's sake ~ When two or more people own something in John and Mary's car. common, 's is added to the last noun. ~ When two or more people own different George's and Andrew's desks. things, 's is added to each noun. • regular plural nouns my parents' bedroom ~ Nouns ending in -s in the singular Chris's / Chris' shoes (especially names) take both's and '. of +noun • things, abstract nouns, animals (sometimes) the front seat of the car the price of success ~ We can use offor people, only in long phrases. the eye of the tiger (=the tiger's eye) The son of the man who rents our fiat is a doctor. ~ For places and organisations we can use of or's. the city's population / the population of the city the company's plans / the plans of the company D. Reflexive Pronouns Reflexive Pronouns are: myself, yourself, himself, herself, itself, ourselves, yourselves, themselves. Use Examples • with the verbs behave, cut, educate, enjoy, help, hurt, kill, like, He has taught himself how to play the guitar. teach, etc. if the subject and the object of the verb are the same • after certain verbs with prepositions (talk: to, say to, take care of, etc.) He was sitting in the dark, talking to himself. • after the verbs look, seem, etc. to describe emotions or behaviour You don't look yourself today; is there anything wrong? • for emphasis (emphatic pronouns); they are placed after the The President himself visited the hospital. subject or the object of the verb, or at the end of the sentence. by + reflexive pronoun = alone, without help . The scouts built this boat by themselves. Reflexive pronouns are not normally used: - with the verbs concentrate, relax, rest. You have to concentrate more. - with ;:erbs describing actions that people usually do for She got up, washed her face and had breakfast. themselves (wash, dress, shave, wake up, etc.). - after prepositions of place. He was watching the woman in front of him. • Reflexive pronouns are used after certain verbs to form idioms: enioy yourself = have a good time behave yourself = be good help yourself to (sth) = you are welcome to have an amount of sth make yourself at home = make yourself comfortable make yourself heard/understood = speak loudly/clearly • Note the difference between themselves and each other = (one another), both referring to two people. They were looking at themselves in the mirror. They were ;ust sitting there, looking at each other. E. Other Pronouns • One-Ones are used if we do not want to repeat a • Other means "more" or "different". countable noun. ~ the other(s) = the rest Would you like the green sweater or the blue one? ~ others = more, apart from those already mentioned Where are the glasses? I need some tall ones. ~ every other day/week, etc. = every second day/week, etc. ~ the other day =a few days ago • Question word + ever (whoever, whatever, ~ another =one more. It can also go with expressions of time, wherever, whenever, however, whichever) =any distance or money. person, thing, place, time, etc. T'd like another glass of orange juice. Wherever you hide, they will find you. We must drive t or another ten miles. Grammar Practice 6 A Circle the correct answers. Little White Lies 7 (0/There is difficult to admit itself /@, but most of our /0tell lies now and again. There is the social lie, (How 8 nice to see(rou)! yourself, ...oh and me !(!llove that newhairstyle of1!0urs)! your ...), the white lie (Sol1y(!11my can't come to you party because myself!(!l am having guests themselves I l!nyseI9 ...) and the lie that 9 makes life easier (®t Me have no idea how that report got on mine I §desk, sir). Most forms of lying are innocent and involve a harmless desire to make us / §lives easier. But @Yits depends on 10 how much 8 /us lie. Some people spend them life deceiving others. Margaret, for example, is a compulsive liar. It / (She)has always enjoyed gossiping with(§")t hers friends about other 11 people. (S§/ Herself starts out with something which is true and comes out with a totally different story, using that great imagination of herself Margaret's need for attention drives 8 /she to lying. 1 But let's not kid lourselvesj' us. Lying is a really bad habit. Yourselves / (You)all know the story of the little boy who cried "Wolf!" too many times and then found him ignored when the it came. S Complete using the words in brackets and the Possessive Case. 1 1. Keeping the environment clean should be (the concern/everyone) everyone's concern 2. Both (the essays/Craig and John) Craig's and John's essays were detailed and very well-written. 1 3. Baby kangaroos live in (the pouch/the mother) the mother's pouch/the pouch of the mother for about eight months. the children of our next door neighbour/our next 4. Those are (the children/our next door neighbour) door neighbour's children 5. (the parents/the children) _ The children's parents tile principal's office 1. Christine and Michelle's room 6. (the room/Christine and Michelle) .. 7. (the newspapers/last week) Last week's newspapers .. .. .. __.. _ 2 8. (the cover/this book) The cover of t his book •. w C Choose the correct answers. Sometimes both answers may be correct. 3 1. Your cat is so tame and friendly. is completely wild and won't let anyone come near her. 4 a. Us c. Our 2. I bumped into our old friend Margaret Stanton. 5 @ The other day b. Another day c. Every other day 3. Ann: Are you going to wear the blue or the grey suit to the interview? Tom: The __ @ blue one 4. Mark: Who's at the door, Julie? Julie: Jim. a. He's 5. I go to aerobic classes a. the other b. other blue c. blue ones b. His @ It ' s day. (E)every other c. another 6 (How /my ie that nds on out other ng that boy who l-written, t eight ncipal) Internet. ________________________________________ page75 6. We made this bookcase by . Do you like it? c. ours a. themselves b. me c. mine a. ones @ others 10. Does Kelly live on own? a. hers b. herself @ her 11. We worked for two hours and then stopped to eat something. a. other ®another c. more 12. Brian wrote the article _ a. his own @ himself c. him 13. I had an accident with my bike and now handlebars are crooked. @ its b. it c. it's 14. Jane sat next to on the bus and we chatted all the way home. a. myself b. mine @ me 15. We helped put on our costumes for the play. a. ourselves @ each other c. us DUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. She has known him for five years. other They have known each ot her for five years. 2. This pen belongs to another person, but I used it by mistake. someone I used someone else's pe n by mistake. 3. No one helped me repair the roof, you know. by I repaired the roof by myself , you know. 4. He prefers to live alone rather than share a flat. his He prefers to live on his own rather than share a flat. 5. I heard that they are all going to receive an award for bravery. each I heard that each (one) of tllem is going to receive an award for bravery. 6. If you go by train, you'll be in Brighton in six hours. take It wil l take you six hours to.get to Brighton by train. 7. Graham Bell was the man who invented the telephone, wasn't he? inventor Graham Bell was the Inventor of the te lephone , wasn't he? 8. It was a great party and we had a good time. we enjoyed ourselves enjoyed It was a great party and - : : . . . . ~ a lot. , page 76 un I Vocabulary Practice A Complete using prepositions. - 1. My parents were di sappointed in/ wit h me when they saw the marks I got in the final exam. The 2. Customers are not satisfied with this product. It causes allergic reactions. can 3. Graham Bell is famous for inventing the telephone. 4. Simon complained to the manager about the poor service in the restaurant. 5. I'm tired of all the work I'm expected to do while others sit around doing nothing. Ac 6. I was very impressed by/with the way things were run at that school. 7. I'm really bored with my routine. I should take up a new hobby. 8. Chocolate ice cream is popular with most children. Pa 9. Christine was annoyed with me because I arrived late. 10. The President wa s upset bv the violent demonstration held outside the Parliament. 11. I'm fed up with your excuses for not doing any work! 12. I disapprove of your staying out so late. B Complete using the correct form of the words in bold type. A HANGOUT During cold winter afternoons, I normally meet my friends at the local fast food restaurant. It's an ideal meeting place as there is lots of warmth Tasty food (which my mum calls poisonous ) is also available. So, it 's a comfortable place to chat. Young people, like me, need a place to go and talk. We usually talk about our interests and hobbies, mine being photography . Our behaviour is typical of many teenagers, I suppose. However, my parents think I go out too often. Luckily, though, after many arguments they have begun to accept my explanation that young people need to find ways to relieve their boredom especially if they live in a small town like I do. C Complete using the words given. Vt Pr PI' NORMAL IDEA, WAR1\1 TASTE, POISON COMFORT Pa Pr Pa PHOTO P: ARGUE , EXPLAIN, BORE G H I , 1. Hans is a very common German name. Ii usual (adj) : happening most often in a particular situation 2. Despite his disability, he leads a norma l life. normal (adj): regular, ordinary, in accordance 3. Waiter, I'll have my usua l drink. with what people expect 1 I common (adj) : ordinary, frequently encountered or often happening 4. No problems will arise as long as you have raise (v): (raise-raised-raised) lift sth, move it to a higher position (transitive) organised the trip well. rise (v): (rise -rose -rise n) move upwa rds, 5. Those of you in favour of the proposal , please raise stond up (intra nsitive) your hands. arise [v): (arise-a rose-arisen) begin to exist It _:1 i ,. h:111 nnn rise or become known to people (for a situation or problem) unit 14 Passive Voice The Passive Voice stresses the action itself, not who or what caused it. Only transitive verbs (=verbs with an object) can beused in the passive. Formation Active Voice employs Passive Voice Eighty people are employed Verb forms in the Passive Voice Verb Forms Present Simple Present Progressive Past Simple Past Progressive Present Perfect Simple Past Perfect Simple Future "Will" Going to Future Perfect Simple Present Infinitive Present Infinitive -ingform Modal Verbs Imperative Active Voice They always serve tea with cakes. They are renovating the hotel. I repaired the roof last year. The scouts were pitching the tents when it started to rain. We have removed all the furniture from the living room. The fire had destroyed the house before the fire brigade arrived. Mary will pay the bill tomorrow. They are going to publish his new novel next month. I will have posted all the letters by noon. We need to finish this work by tomorrow. He could have bought the tickets earlier. I hate people staring at me. You must take him to hospital. Please complete this exercise. Passive Voice Tea is always served with cakes (by them). The hotel is being renovated. The roof was repaired (by me) last year. The tents were being pitched by the scouts when it started to rain. All the furniture has been removedfrom the living room The house had been destroyed by the fire before the fire brigade arrived. The bill will be paid (by Mary) tomorrow. His new novel is going to be published next month. All the letters will have been posted by noon. This work needs to be .finished by tomorrow. The tickets could have been bought earlier. I hate being stared at. He must be taken to hospital. This exercise must / should be completed. The Present, Past and Future Perfect Progressive and the Future Progressive are not used in the Passive Voice. 'kyo page 78 Use We use the Passive Voice: • when the agent (the person performing the action) is unknown, unimportant or obvious from the context. This portrait was painted before the 17th century. The environment is being polluted more and more every day. • when we want to emphasise the action itself, not the agent. Eight people were injured in a car accident. • in instructions, processes, formal statements, etc. The lever on the right should be pulled down slowly. • • Get can be used instead of be in informal speech to show that something happened unexpectedly. Hi s ieons got caught on a spike as he was climbing over the fence. • By + agent is used when we want to emphasise who does or what causes the action. The investigation was ordered by the Police Commissioner. • with + instrument/material} . . . 6 . I describe what caused the cction or what the agent used to perform iI. of + matena This photograph was taken with an expensive camera. The ba sement was flooded with water. This cardigan is made of wool. Note the following changes: Active Voice Passive Voice Examples Verbs with two objects Both the indirect object (person) and He gave her a rose. --.. 1 the direct object (thing) can be used as She was given a rose. or subjects of a Passive sentence. A rose was given to her. Question words (what, who, Question Word + AuxiliarylModal Who wrote this play? --.. when, where, why, how) Verb + Subject + Past Participle Who was this play written by ? (informal) • With who and whom we never By whom was this playwritten? (formal} 1 omit by. not...any --.. no They didn't change anything. --.. 1 not...any of --.. none of Nothing was changed. not...anyone/anybody not...anything --.. --.. no one I nobody nothing 1 make hear see, etc. let make John made me leave. --.. 1 I was made to leave (by John). hear + bare infinitive + full infinitive see, etc. be allowed to They didn't let me go to the party. --.. I was not allowed to go to the party. • When "let" has other meanings, You have to let the dog out. --.. it does not change in the Passive. The dog has to be let out. 2 believe, consider, expect, find, • It + passi ve form of verb + that... Scientists believe that this virus is 3 hope, know, report, say, think, (impersonal construction) deadly. --.. understand, etc. It is believed that this virus is deadly. or • Subject + passive form of verb + full This virus is believed to be deadly. 4 infinitive (personal construction) Verbs with prepositions The preposition goes immediately A car nearly knocked Jane down this 5 after the verb. morning. --.. 6 Jane was nearly knocked down by a car this morning . dly. rm it. ual ) ai) or ar _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ page 79 I Grammar Practice ARewrite the following sentences using the Passive Voice. More than one answer is possible in some cases. 1. Everyone knows that fruit and vegetables are high in water content. Itis known that fruit and vegetables are high in water content./Fruit and vegetables are known to be high inwater content. 2. Mr and Mrs Philips didn't buy anything from the supermarket. Nothing was bought from t he supermarket by Mr and Mrs Philips. 3. They first published this book in 1867 . This book was first published In 1867. 4. What did they say about the accident? what was said about the acc ident? 5. They saw the President leave by the back door. The President was seen to leave by the back door. 6. The nurse gave the patient a robe to put on. The patient was given a robe to put on (by the nurse)./ Arobe was given to the patient to put on (by the nurse). 7. The waiters didn 't seat any of the gues ts till af ter the orchestra played the national anthem. None of the guests were seated by the waiters till after the national anthem was played by the orchestra. 8. Mike will send flowers to Jane, who is in hospital. Rowers will be sent to Jane. who is in hospital. by Mlke.ZIane, who is in hospita l, will be sent flowers by Mike. 9. The government provided the refugees with food. The refugees were provided with food by the government./Food was provided to the refugees by the government. 10. Who desi gned this building? Who was this building designed by? I!. The painter is spraying paint on the door with a spray gun. Paint is being sprayed on the door with a spray gun (by the painter). 12. The hurricane has totall y destroyed the town. The town has been totally destroyed by the hurricane. 13. We could have taken the car to the garage today. The car could have been taken to the garage today. 14. The chil dren are going to organise a surpris e party. Asurprise party is going to be organised by the children. 15. Local authorities hope that people will recycle more of their garbage. It Is hoped that people will recycle more of their garbage. BComplete using the Active or the Passive Voice of the verbs in brackets. thought went to the nearest police station. 2. We are staying (stay) with my parents becau se our house is being renovated (renovate) at the moment. 3. Two new schools will be built (build) in our area because of the growth in population. Building will start (start) next month. 4. The tables were being cleaned (clean) by the waiters when a group of tourists arr ived (arrive) . 5. More chocolate bars have been consumed (consume) thi s year than in any other year. 6. My car was repaired (repair) by the mecha nic yes terday but unfortunatel y I crashed (crash) it into a tree this morning. page 80 C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. People believe that the chairman of the committee is involved in the scandal. be The chairman of the commi ttee is believed to be involved in the scandal. 2. She misses her friends visiting her in the eve nings. visited She misses being visited by her friends in the evenings. 3. Why did they turn down our offer , Mr Steinberg? turned Why was our offer turned down , Mr Steinberg? 4. The teacher didn't let us leave before we finished the essay. allowed We were not allowed to leave before we fini shed the essay. . 5. Nobody in my class can solve this maths problem. solved This maths problem can 't be solved by anyone in my class. 6. The y were gi ving the dog a bath when I arrived. given The dog was being given a bath when I arri ved. 7. You know, people say that the Minister of Educat ion is going to resign. is You know, it is said that the Minister of Education is goi ng to resign. 8. Karen would have sent me a letter if she had known my address. been I would have been sent a letter by Karen if she had known my address . I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. LLllJlldl V 0LlI - look UP _ 1. Students should have a dictionary ----"::.=.:......=:J"--- look after: take care of sb or sth look forward to: expect sth to happen unknown words. because you think you 2. We are all looking forward to going on holiday. will enjoy it 3. Lookingafter old people isn' t an easy j ob, but it's look into: investigate, examine in very rewarding. detail look over: examine sth in order to 1v looked over get a general idea of it look up: try to find inf ormati on in look into a book or li st decision. B Complete using the correct form of the words in bold type. VISITING LAS VEGAS Las Vegas has a new attraction ; the tallest American building west of the Mi ssissippi. ATTRACT Its owners have high expectations of its success. The design is original and EXPECT, ORIGIN certainly different to anything ever seen before. Taller than the Eiffel Tower, the DIFFER building has something for everyone. The description of what the building offers is DESCRIBE quite amazing. The building has a casino, for which the state is famous for. Also, there is a fashionably decorated revolving rest aur ant , so that clients are able to see the FASHION impressive views through the glass windows. Three chapels are available for anyone IMPRESS who would like to get marri ed and have a " religious ceremony, 800 feet in the air. RELIGION In addition , two of the highest rides are available for ride lovers. The roller coaster, ADD 865 tracks in length , and the Spa ce Shot ride, which goes up to the top of the tower LONG at appro ximatel y 90 km per hour. Anyone for a go? -------------------------- page81 CComplete using the prepositional phrases given. in future: in general: in a hurry: in love (with): in a good/bad mood: in the time to come generally needing to do sth quickly loving sb or sth feeling cheerful! angry and impatient inone's opinion: according to what sb thinks about sth in order/a mess: tidy/untidy in pain: feeling pain in particular: particularly, especially in person: personally in pieces: broken up into small parts n. oComplete using the words given. persist (in) (v): go on doing sth insist (on) (v): t' s resist (v): 'ore ga lough (adj): hard (adj): despite having difficuIties say or demand sth very firmly and not change your mind about it (1) refuse to accept sth (2) stop yourself from doing sth although you would like to do it (1) rough, violent (2) difficult to do or deal with (1) not soft or smooth (2) difficult to understand or do, requiring considerable effort to be accomplished demanding (adj): requiring a lot of time, effort, energy or attention beside (prep): next to besides (prep): in addition to 1. Pam left the office in a hurry . She had a train to catch. 2. The estate agent said that in general/in the house was in a his opinion reasonable condition. 3. Mrs Kay loves animals, in particular cats. 4. You're late! In future ,please try to be on time for our meetings. 5. Model aeroplanes come in pieces ,which you put together yourself. 6. Jenny was in pain after the accident. '7. I'm always in a bad mood when it rains. It makes me miserable. 8. Mr Fane keeps his office in order . He is very tidy. 9. I'd rather meet my clients in oerson than speak to them over the phone. 10. In my opinion , we should sell the flat and buy a house. 11. I fell in love with the island and decided to live there. 1. I insist 2. Why do you late ? you stay and have dinner with us. persist in finishing the reports even though it's 3. I ate up the cake.I just couldn't resist it. 4. Al Capone had killed many people and was considered a tough criminal. 5. Children require a lot of care and guidance, that's why being a parent is very demanding . 6. The whole project requires a lot of ha rd work. 7. Besides Katie, I've also invited Jenny to the dinner party. 8. Please, place a wine glass beside every plate. unit 15 Causative Form The Causative Form is used when we do not do something ourselves, but we arrange for someone else (usually an expert) to do it for us. Formation Subject + Have/Get + Object + Past Participle ~ ~ ~ ~ He had his car serviced last week. Verb forms in the Causative Form Verb forms Active Voice Causative Form Present Simple We paint the house every year. We have the house painted every year. Present Progressive Beth is washing her car. Beth is having her car washed. Past Simple He typed three letters yesterday. He had three letters typed yesterday. Past Progressive She was cleaning the carpet when I arrived. She was having the carpet cleaned when I arrived. Future "Will" We will install the lights next week. We will have the lights installed next week. Future Progressive I'll be planting some trees in the garden I'll be having some trees planted in the tomorrow morning. garden tomorrow morning. Present Perfect Simple The girls have repaired their bicycles. The girls have had their bicycles repaired. Present Perfect We've been importing clothes from Italy since We've been having clothes imported from Progressive we opened the shop. Italy since we opened the shop. Past Perfect Simple He had organised the meeting before I called. He had had the meeting organised before I called. Past Perfect They had been photocopying a book when the They had been having a book photocopied Progressive manager arrived. when the manager arrived. Present Infinitive He managed to repair the roof He managed to have the roof repaired. -ing form I remember taking my blood pressure. I remember having my blood pressure taken. Modal verbs You should fix the leakage in the tank. You should have the leakage in the tankfixed. Imperative Clean the table, please. Have the table cleaned, please. • Questions and negations ore formed as in the Active Voice: with the auxiliaries do/does in the Present Simple and did in the Post Simple. When did you last have your eyes tested? • We can use get instead of have, especially in informal style. / have to get the house painted this year. • The Causative Form is often used instead of the Passive Voice to express an occident, a misfortune or something that hod not been arranged : They had their house broken into last week. Mark had his leg broken in the car crash. • If we want to ment ion who performs the action, we can add by+agent at the end of the sentence. She a/ways has her hair dyed by a hairdresser. .Ill nl ek. ed. In eI ied .ed. e or ceo _________________________________________ page 83 • make/have someome do something=cause someone to do something (but there is a slight difference in meaning) Mrs Smith made her husband do the shopping. (=She insisted that her husband should do the shopping) Mrs Smith had her husband do the shopping . (=She asked her husband to do the shopping) • get someone to do something=persuade someone to do something Mrs Smith got her husband to do the shopping. (=She persuaded her husband to do the shopping) I Grammar Practice A Choose the correct answers. 1. Brian will @ get his teeth polished 2. When a. had you 3. He often ®has his suits cleaned 4. Debbie knows how to sew and a. has all her dresses made 5. Please, a. you have 6. Jake @ didn' t have 7. We postponed a. having painted our house 8. She a. had stolen her wallet 9. The teacher ®had John clean 10. If you feel dizzy, you should by the dentist tomorrow. b. polish his teeth your new carpet fitted? @ did you have at the dry cleaner's. b. has cleaned his suits herself. b. gets all her dresses made c. have his teeth polish c. you had c. cleans his suits @ makes all her dresses the accounts checked by the accountant first thing tomorrow morning. @ have c. will have his passport renewed last week. b. hadn't c. not had because we didn 't have enough money. b. have painted our house while shopping yesterday. b. stole her wallet the board. b. had John cleaned _ @ having our house painted @ had her wallet stolen c. had John to clean a. your blood pressure have checked @ have your blood pressure checked c. checked your blood pressure 11. I always to my friends living abroad because I like to keep in touch with them. a. have e-rnails sent @ send e-mails c. have e-mails sent 12. I would like to for me, as I'rn an awful cook. ohave my cooking done b. having my cooking done c. have done my cooking 13. Macey her organise a party at her house. a. got me help b. got me helped @ got me to help 14. your newspaper delivered to your house every morning? a. Have @ Do you have c. Do you : page 84 A Complete using the correct form of the phrasal verbs given. I Vocabulary Practice r i 01 m opeili and a a 7. 1'1 o mor any give stres favo Slee ------1! sleep Slee C c 8. T 9. Y 10. T 11. l' 12. The B COl 1.Ik 2. Pe 3. C(] 4. Yq 5.1 6. Te a 111'-''-'11 <>'111'-': H'" services mycar in similar bottles. 2. Mark moved out of the flat after an argument with his flatmate. 3. We quickly made for the bam when it started raining. 4. Don 't believe anything he says. He's always making up stories. 5. Could you speak up, please? I can't make out what you're saying. 6. We've got the keys to our new house and tomorrow we're going to move in mix up Luke: make for: go towards a place make out: manage (with difficulty) to see, hear or understand sth make up: (1) invent a storyor excuse (2) become friends again after a quarrel or disagreement confuse people or things begin to live in a house or place stop living in a house or place and go somewhere else mix up: move in: move out: 3. Tanya: Brenda: B Complete using the Active Voice or the Causative Form of the words given. 1. Mr Fane: Are you using the computer? Mr Parker: Yes, I am typing my lett ers (my letters / type) at the moment. Mr Fane: Do you type all your letters yourself? Mr Parker: No, I don't have the time to do that. I usually have mv lett ers typed (my letters / type) by my secretary, but she's away today. I had my car serviced (my car / service) by the mechanic yesterday. The bad thing is that I had to pay quite a lot of money for it. Didn't you know that my brother is training to r.r., nl ... --"-_ _ (my car / service) for me. Maybe he could have a look at yours next time, too. What are you doing? Are you painting the house (the house / paint) yourself? No, of course not. I am having the house painted (the house / paint) by a painter. I'm just helping him. Do you want to come in and have a look? 2. Macey: C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) as soon as possible. before I go on holiday. while he was playing football. her motorbike for the day. this afternoon. cleaned twice a week? 7. A bank clerk was cashing my cheque when the robbers entered the bank. cashed I was having my cheque cashed when the robbers entered the bank. 8. I haven't been to the hairdresser's for a haircut lately. cut I haven't had my hair cut lately. 1. Please, arrange for these parcels to be posted as soon as possible. have Please, have these parcels posted 2. My car will need servicing before I go on holiday. get I'll need to get my car serviced 3. Someone broke Gary's front teeth while he was playing football. had Gary had his front teeth broken 4. Betty eventually agreed to lend me her motorbike for the day. got I eventually got Betty to lend me 5. A plumber is repairing my dishwasher this afternoon. repaired I am having my dishwasher repaired 6. Kelly , does the cleaner clean your house twice a week? have Kelly, do you have your house dto self? ng e teo es. mg _________________________________________ page85 BComplete using prepositions. 1. I kept thinking of/about the accident all night long. 2. Pet owners care for/about their pets a great deal. 3. Could you take care of little Jimmy tonight? 4. You can rely on your good friends when you need them. 5. I have a need for coffee in the morning. 6. Teachers feel responsible for the progress of their students. 7. I'm very thankful for all your help. 8. Teachers must learn to be patient with their troublesome students. 9. You should take responsibility for your actions. 10. The amount of food you make depends on the number of guests you're expecting. 11. I'd like to thank you for the gift you gave me. 12. She was grateful to him for helping her out at such a bad time. CComplete using the correct form of the words in bold type. SSH, LET THEM SLEEP! The discovery that a member of your family is sleepwalking may be DISCOVER alarming , but it is not an uncommon phenomenon. Both adults and children ALARM sleepwalk, however it is more common in children. Sleepwalking is not a psychological disorder , as some may think. Nor is there ORDER any connection between dreams and sleepwalking. The explanation which experts CONNECT give for sleepwalking is that it is mainly due to being tired and under a lot of TIRE stress. Anxiety pressure at work or at school or even the loss of a ANXIOUS, PRESS favourite possession could trigger it off. POSSESS Sleepwalkers move easily around the house despite the darkness , sometimes DARK opening drawers as if searching for something. It is difficult to wake up a sleepwalker and it is considered unwise because it can cause great distress. The following WISE morning the sleepwalker doesn't usually remember anything. oComplete using the words given. 1. My grandfather is very active even though he is old ancient (adj): of the distant past antique (odj): made in the style of an 2. My father buys antique furniture, restores it and then earlier period sells it at a profit. old-fashioned (adD: no longer fashionable 3. This is traditional Irish music. Do you like it? traditional (odj): in accordance with tradition 4. In ancient times, people believed there were many gods. elderly (cdj): qu ite old, past middle age (for people) 5. My grandmother still makes jam in the good old-fashioned old (adj): mature (cdj): no longer young or new (1) fully developed in personality and behaviour way. 6. An elderly/old couple won the trip to Hawaii. (2) when sth is left for a 7. Ripe bananas are great for making banana cake. time to allow its full flavour to develop (usually for wine 8. Jane is very mature for a fifteen-year-old. or cheese) ripe (od j): fully grown and ready to be eaten or used (usually for fruit) unit 16 Conditionals Type 1: Real situat ions in the present or future. If clause Main clause Use If + Present Tense • Future tense real or probable situations in the present or (simple or continuous ) IfMartin gets the j ob. he will move to future or Oxford. Present Perfect Simple • can/may/might/must/should + infinitive (if the action has already If you have finished your homework, you nUlY go out with yourfriends. finished) • Pr esent Simple general truths (ifewhen, whenever) If you mix blue and yellow. you get green. instructions or commands • Imperative Ifyou mis s the train, take the bus. • If-clauses either prec ede or foll ow the main clause. If they precede the main cl ause, we separate them with a comma. If you eat a lot o f sweet s, you'll gain weight. BUT: You'll gain weight if you eat a lot o f swee ts. • If there is only a slight possibil ity of somet hing happening, we can use should. If you should ever go to Colomb ia, visit the Museum of Gold in Bogota. In thi s case, if can be omitted; should comes before the subje ct (inversion). Should you ever go to Colombi a, visit the Museum of Gold in Bogota. Type 2: Unrea l situations in the present or future. If clause Main clause Use If + Past Tense WOUld (simple or continuous) could + present infiniti ve j might If he were still living with his parents, he unreal or imaginary situations in the present would be able to save more money. III won a lot ofmoney, I would spend 11I0st events that are unlikely to happen in the of it travelling round the world. future If I were you, I wouldn 't argue with my to give advice employer. • We use were instead of was in type 2 conditional sentences in formal English. If he were not so lazy, he would be more successful . • If can be omitted when it is followed by were; were comes before the subject (inversion) . Were she toller, she could become a model. (=;{ she were toller, ..,) • We can use will/would in the if- cl ouse (Type 1+ 2 con ditio nal sentences) to express desire, will ingness, politeness, insistence, annoyance, uncertainty or to make a requ est. If you will keep on bei ng so noisy, /'11 have to report you. I would appreciate it if you would turn the radio down. or ent ________________________________________ page87 Type 3: Unreal situations in the past. If clause Main clause Use If +Past Perfect WOUld (simple or continuous) could j + perfect infinitive might If he had known your phone number, he for actions that did not happen would have called you. If I had been more careful, I would have to express criticism or regret passed the driving test. If can sometimes be omitted; had comes before the subject (inversion). Had you arrived earlier; you would have met my grandmother. (= If you had arrived earlier... ) Mixed conditionals Mixed conditionals do not follow the tense rules strictly; we can make combinations according to the context: IfI had a car, I would have picked you up from the airport. (Types 2, 3) Ifyou had taken some aspirin, you would feel better now. (Types 3, 2) Conditionals can be introduced with other expressions instead of if: • unless (= if not], e.g. Unless you hurry you'll miss the bus. • as long as/provided/providing (= only in, e.g. You can borrow my camera as long as you promise to handle it with care. You can visit me anytime provided/providing (that) you call me in advance. • in case, e.g. I'll buy some mineral water in case I get thirsty (= I'll buy some mineral water before I get thirsty.) But: I'll buy some mineral water if I get thirsty (= I'll buy some mineral water when I get thirsty.) • on condition (that) (= provided). e.g. On condition (that) she passes her exam, her parents will let her go to Italy for the holidays. • but for (= if it wasn't/hadn't been for), e.g. But for the rain, we would have enjoyed the picnic. • or else (= if not/otherwise}, e.g. Hurry up, or else we'll miss the train. • Suppose/Supposing (= imagine in, e.g. Suppose/Supposing the lights went out, what would we do? • only if, e.g. She will go to the party only if she has finished her work. • even if, e.g. He wouldn't talk about his plans even if you begged him to. • whether, e.g. Whether he agrees with me or not is not important to me. ~ We never use the Future "Will" after these structures, except for or else and whether. 1. If you the Louvre while in Paris, buy me a poster. a. visited (B should visit c. have visited 2. 2. If I had installed an alarm, the thieves wouldn't able to break into my house last week. a. be b. had been @ have been 3. 3. If I the job, I will take you out to dinner on Saturday to celebrate. a. have got ® get c. got 4. I would make a film with Leonardo DiCaprio if I a famous director, but I'm not. 4. ~ w e e b. had been c. will be 5. 6. b. had apologised 7. 7. If you the application to the company on time, they might have called you for an interview. I can't understand why you didn't! a. send @ had sent c. will send 8. B Make sentences using conditionals. 1. The lift may not work so use the stairs. If the lift doesn't work (isn't working), use the stairs. page 88 I Grammar Practice A Choose the correct answers. 6. The bus drivers might be on strike tomorrow, so I'll probably catch a taxi. If the bus drivers are on strike tom orrow, I'll catch (I may catch) a taxi. 1. 2. I want a new car but I can't save up enough money. If I could save up enough money, I would buy a new car. 3. This isn't a very good camera. The photos I took aren't very clear. If this were a better camera, the photos I took would have been clearer. 4. I think that you shouldn't drink so much coffee. If I were you, I wouldn't drink so much coffee. 5. We didn't have your address so we didn't send you a Christmas card. If we had had your address , we would have sent you a Christmas card . C Complete using mixed conditionals. 1. He wouldn't be (not be) ill today if he hadn 't walked (not walk) home in the rain last night. 2. You've been playing with that cat for hours . If you were (be) allergic to cats, you would have known (know) by now. 3. If they caught (catch) a taxi, they will be (be) here any minute now . 4. We wouldn't be (not be) stuck here now if you had take n (take) the car to the garage before we left for our holiday. 5. If I were (be) you, I wouldn't have sold (not sell) my car before I bought another one . How will you get to work now? _________________________________________ page89 D Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. If she doesn't follow a stricter diet, she won't lose any weight. unless She won't lose any weight unless she follows a stricter diet. 2. I wouldn't have succeeded if my parents hadn't encouraged and supported me. eek. but I wouldn't have succeeded but for my parents' encouragement and support. 3. He has twisted his ankle, so he can't play tennis this afternoon. not Had he not twisted his ankle , he would have been able to play tennis this afternoon. 4. We didn't follow the directions, that's why we got lost. would We would not have got lost if we had followed the directions. 5. You should read more to improve your vocabulary; that's what I'd do. were If I were you. I would read more to improve my vocabulary. 6. Jenny can get a puppy only if she promises to take care of it. long Jenny can get a puppy as long as she promises to take care of it. 7. I wouldn't mind being transferred to another city if they offered me a higher salary. condition I wouldn't mind being transferred to another city on condition (that) they offered me a higher salary. 8. Fortunately, they were wearing seat belts, so nobody was seriously injured. not If they had not been wearing seat belts, they could have been seriously injured. I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. John pointed out his old school friend in the photograph. pay back: give back money you have borrowed 2. The policeman asked him to pull over for a breathalyser payoff: give sb back all the money you test. owe them pay 3. I'll give you the money, but when will you __""""'---:!""-__ me point out: draw sb's attention to sth back ? pull down: demolish pull over: move closer to the side of the road 4. That building will be pUlled down next week. and stop (forvehicles) 5. It will take me two years to payoff/back my loan. BComplete using the correct form of the words in bold type. LION KING The lion is known as the king of the jungle. Perhaps this is because of its size, strength and ability to run up to 35 mph. STRONG, ABLE Yet, for twenty hours a day, the lion just lies under the sun doing nothing. However, when it gets hungry , its manner changes and it becomes threatening . Its only HUNGER, THREAT intention is to satisfy its enormous appetite. INTEND In its natural surroundings , the lion will eat anything, from rats to animals as large as SURROUND giraffes. But zebra meat provides the lion with the greatest satisfaction SATISFY Lions live in groups called prides. The lioness is truly amazing. She is quicker TRUE than the male. She is so caring that she will hunt and look after her young for CARE two years before they become independent . DEPEND page 90 C Complete using the prepositional phrases given. in practice/theory: in private/public: in reality: in secret: in the shade/sun: in tears: in time (for): in touch (with): in uniform: actually happening/ theoretically without/with the presence of others actually, in fact secretly protected from/ exposed to sunlight crying early or at the appointed time in contact with sb wearing the same special clothes as everyone else at work or school in a loud/low voice: loudly/quietly in the way: when sb or sth stops you from moving forward or seeing clearly in other words: saying sth differently oComplete using the words given. 1. The mayor hasn't been seen in Dublic for some time. 2. Do you keep in touch with your old school friends? 3. Martha looked very upset. I saw her running out of the office in tears 4. Your idea works in theory , but not in practice. 5. You've arrived just in time for lunch. 6. Could you help me move this table? It's in the way 7. Nobody knew about our affair. We used to meet once a week in secret 8. The children should all be in uniform for the parade. 9. The mirrors made the room look bigger, but in reality it was quite small. 10. You shouldn't stay in the sun for too long, you 'll get burnt. 11. Your car isn't reliable enough for a long trip, in other words , you 'd better not take it. 12. I can 't hear you very well. Could you repeat that in a loud(er) voice ? 1. This box is em pty . Can I put the rubbish in it? vacant (odj): not being used or occupied (e.g. hotel room, job position) 2. We must buy some more cheese, there's only a small piece free (odj): not being used or occupied left by sb or not reserved for sb to , no morp vacant use (e.g. table, seat) empty (odj) : with no people or things in it deserted (adj): becoming empty because 4. The bandits hid in the abandoned/empty/ warehouse. everybody has left deserted 5. The only free table we have is the one in the left (adj): what remains after the rest has gone or been used corner. abandoned (adj): no longer used or occupied 6. It was 1:00 a.m. and the usually busy street was now quiet (e.g. building) and deserted/empty . alone (adj): not with any other person 7. All my friends are married except Kate , who is still lonely (adj): unhappy because you are single alone single (cdj): not married 8. I get really lonely at Christmas because all my family live abroad. 9. Mr Jones came to the party alone as his wife was away on business. alive (adj): living, not dead (not followed by a noun) 10. The football match \ . __ br __dcast live ... live (adj): (event, performance or thirty countries. programme) being broadcast 11. The rock group zave a lively • exactly at the time it happens, not recorded in adva nce stage. lively (odj): full of energy or enthusiasm 12. The wounded bird was barely alive living (adj): alive, not dead (followed by a 13. The old man said that life during the war was a noun) living nightmare. e. ? iffice it burnt. ords , init? I piece s. The house. inthe quiet 11 my vife e on units 13-16 Revision 04 I Grammar Practice AChoose the correct answers. 1. If you a flight, would you have gone by train? a. haven't booked b. don't book @ hadn' t booked 2. Here are your photos. We at the photographer's. @ got them developed b. develop them c. got developed them 3. Betty a lot of presents on her birthday. a. was been given b. gave c. was giving 4. The dog must to the vet. a. taken @ be taken c. be take 5. Diana, congratulate her for me, will you? a. Should you saw b. If should you see @ Should you see 6. My son told me he tied his shoes by _ a. him ® himself c. his 7. We have had the roof of our house _ a. to replace b. replace c. been replaced 8. Sue by the police all night. GV was being questioned b. was questioning c. is being questioned 9. Kev into the tree if the brakes on his bike had been working. a. wouldn't crash b. won't crash c. won't have crashed 10. Jack last night. a. had stolen his wallet b. his wallet stolen @ had his wallet stolen 11. I'll lend you my car you promise to drive carefully. 0 as long as 12. If! a. had owned 13. He got his brother @ to wash 14. Don't go out by a. myself 15. I'll find you a. whatever b. unless c. even if a house like that, I'd look after it better. b. have owned @ owned the dishes. b. wash c. washing at night. It's dangerous. (E} yourself c. me you go. b. whichever c. whenever d. won't book d. got them develop @) was given d. take d. If you saw d. his own @ replaced d. had questioned @ wouldn ' t have crashed d. has stolen his wallet d. whether d. own d. to have washed d. her @ wherever III page 92 B Using the words given and other words, complete the second sentence so that it has a similar 12 meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. She has arranged to work this afternoon, so she can't come shopping with us. 13 not Had she not arranged to work this afternoon, she would have been able to come shopping with us. 1 2. Someone has stolen my bike, Dad. had I have had my bike stolen , Dad. 3. People expect that the weather will change soon. 1 to The weather is expected to change soon. 4. I wouldn't mind contacting her but I don 't have her phone number. would I would contact her if I had her phone number. 8 5. When did they replace the broken windows, Annie? replaced When were the broken windows replaced , Annie? 1. 6. You are all welcome to have some more cake. 2. help Feel free to help yourselves to some more cake. 3. 7. Chri s, I shall be glad to show you round if you decide to visit London. should Chris, if you should/should you decide to visit London, I shall be glad to show you round. 4. 8. We 've asked an electrician to install lights in the garden. 5. have We will have an electrician install lights in the garden. 6. Vocabulary Practice A Choose the correct answers. 1. I'm really Christmas this year. a. looking after b. looking out for c. looking into 2. It' s raining! Quick, let 's make that shop. a. out b. up c. in 3. During the month of August, Athens is almost . a. vacant b. abandoned c. left 4. After the break, we 'll with chapter three of the book. a. insist b. persist c. keep 5. This is a valuable chair which dates back to the eighteenth century. @ antique b. old-fashioned c. ancient 6. My job is so that I don 't think I'll be able to take a summer break. @ demanding b. persi sting c. hard 7. Is he enough to take on so much responsibility? a. elderly b. ancient c. ripe 8. Billy the Kid was wanted dead or _ a. live @ alive c. lively 9. I went to Spain on holiday , but I made a lot of friends there. a. single @ alone c. lonely 10. You'd better up all the unknown words in the dictionary. a. point b. make c. mix 11. The room was in a _ a. hurry @ mess c. mood 7. .,l ooking forward to @) for .ideserted @ continue d. traditional " d. tough .imature d. living d. free @ look d. shade 8 rome _________________________________________ page 93 12. His handwriting is so difficult to read. I can hardly what he's written. Wmake out b. make up c. look into d. point out 13. If you have a problem, don't hesitate to your hand. @raise b. rise c. arise d. rised 14. Mike was after he broke his leg. a. in love b. in order @ in pain d. in person 15. Please don't forget to the money you have borrowed from me. a. pull over (2) pay back c. point out d. pull down BComplete using the correct form of the words in bold type. 1. John couldn't give a logical explanation as to why he had arrived so late. EXPLAIN 2. The eyewitness gave an accurate description of the bank robber. DESCRIBE 3. For additiona l information on flight times and package holidays, contact your ADD travel agent. 4. We lost most of our possessions in the flood. POSSESS 5. I was unable to carry my luggage, so I had to use a trolley. ABLE 6. The attic is in disorder . Let's tidy it up. ORDER 7. Alice had a tiring day at work and went to bed early. TIRE 8. He got the impression that the situation was out of control. IMPRESS CChoose the correct answers. My friend Sarah wanted to (1) her house painted, but she didn't want to do it (2) _ So, she decided to call the number of a painting company she had seen on an advertisement that (3) _ lefton her car. A young man answered the phone, and Sarah told him about her house. An appointment (4) for the following Thursday. When the day came, a knock (5) on Susan's door. When Susan opened it, she saw two twelve-year-old boys standing in front of (6) ! She was caught by surprise! They explained that they had wanted to earn some extra money for (7) , so they had created and handed out the ad. If Susan (8) the painters were twelve, she never would have called to begin with! She told them she was sorry, but she preferred to have her house painted by professionals. 1. (Vhave 4. a. was being made 7. a. itself b. having had b. will be made b. them c. having @ was made c. him d. have had d. was making @ themselves 2. a. her 5. a. had been heard 8. a. would have known b. she b. having heard (Q had known @ herself c. was hearing c. knows d. hers @ was heard d. was to know 3. a. was being 6.@her @ had been b. she c. having been c. it d. were d. them 17 Unreal Past- Would rather- Had better unit A . Unreal Past Past tenses referring to unreal situations are called Unreal Past. The Past Simple can refer to untrue or imaginary situations in the present or future, while the Past Perfect Simple can refer to unreal situations in the past. Unreal past with present or future time reference Structure If + Past Tense Imagine j Suppose + Past Tense Supposing wish If only ] + Past Tense wish ] would + If only + infinitive wish ] + could + If only inf rutive .. as if as though ] + Past Tense It's time It:s a ~ o u t time] + Past It s high time ] Tense If + Past perfect wish ] If only + Past Perfect asif ] + Past Perfect h h j as t oug Imagine Suppose + Past Perfect Supposing Use Type 2 Conditional imaginary situations in the present or future • wish about a present situation that we would like to be different ~ If only is stronger than wish. • to express annoyance, irritation, dissatisfaction • to make a wish concerning a present situation which is unlikely to change ~ The subject of would must be different from the subject of wish. to make a wish or express our regret about sth we cannot do at present. • untrue situations in the present ~ Were is used instead of was. • to indicate that the time has come for someone to do something • to express criticism or a complaint about sth that should have already been done ~ It's about time/it's high time are stronger than It's time. ~ It's time + infinitive: it is the right time (for sb) to do something Examples If I had a car, I would drive to work. Suppose you lived in a small village, would you miss the city? I wish 1 lived in the country. (I don't.) If only 1 were on holiday. 1 wish he wouldn 't smoke in the office. 1 wish time wouldn't pass so quickly! She wishes she could speak French. (she can't.) He speaks as if he were a foreigner. (He is not.) It's time we went home. It's time they started working. It 's about time we got rid of this old car! It's time to tidy up. It's time for them to start working. Unreal past with past time reference Type 3 Conditional to express sorrow or regret about sth that did or did not happen in the past . unreal situations in the past imaginary situations in the past If she had worked harder, she would have been promoted. 1 wish 1 had remembered her birthday. (1 didn't.) He talked to everyone as if he had known them for years. Suppose he hadn't fled his country, would he be in prison now? c ld an't.) snot.) hem he _________________________________________ page95 • wish can al so go with an inf initive (meaning want) or a noun: She wishes to spe ak to the headmaster. We wish you happiness. • wish is used for unreal or improbable situat io ns; hope is used for possibl e sit uat io ns. I wish yo u were here . I hope to see you whe n I come to London. B. Would rather ( = I would prefer) If the subject of would rather is the same as the subject of the main verb: Time Reference Structure Examples . ~ PresentlFuture would rather + present bare infinitive She'd rather stay at home tonight. (;j E 15 Past would rather + perfect bare infinitive I'd rather have travelled to Egypt last winter. < PresentlFuture would rather + not + present bare infinitive I'd rather not eat any more today. ~ '';:: ~ Past would rather + not + perfect bare infiniti ve Nick would rather not have gone to the party z'" yesterday. If the subject ofwould rather is different from the subject of the main verb: Present/Future would rather + subject + Past Simple I'd rather you left your umbrella outside. (affirmative or negati ve form) /'d rather you didn 't smoke in the office. Past would rather + subject + Past Perfect I'd rather you had informed me earlier. (affirmative or negative form) I'd rather she hadn't borrowed my bicycle. Synonymous expressions Structure Examples • prefer + -ing/noun + to + -ing/noun He pref ers swimming to scuba diving. • prefer + full infiniti ve + rather than + bare infinitive She pref ers to travel by plane rather than (travel) by boat. . (general preference) • would prefer + full infinitive + rather than + bare I would pref er to go to the cinema rather than stay at infinitive (preference in a particular situation) home. • would rather + bare infinitive + than + bare infinitive I'd rather wa lk than go by bus. • would sooner is used in the same way as would rather. I'd sooner we left earlie r. (presentlfuture time reference ) He' d soo ner she hadn't spe nt so much money on clothes. (past time refe re nce) c. Had better ( = should) Had better expresses strong advice, a warning or a threat and is stronger than should and ought to. Its subject is always the same as the subject of the main verb. Time Reference Structure Examples Present / Future had better + (not) + present bare infiniti ve He'd better see a doctor as soon as possible. You'd better not drive so fast. Past It would have been better if + Past Perfect It would have been better if you hadn 't argued with him last week. page 96 I Grammar Practice c A Write sentences using wish or If only. I wish/If only my sister didn't/wouldn·t take 1. I My sister always takes my 1'1 car without asking me. my car without asking me. I wish/If only my til She's so inconsiderate. sister wasn't/weren't so inconsiderate. w (4 I wish/If only our luggage l1adn't been stolen. 2. l Our luggage was stolen h from our hotel room. We I wisl1/lf only we Ilad insured our luggage. c, should have insured it. I wish/If only I could keep the puppy I found. to keep it but my parents 3. I I found a puppy. I want I wish/If only my parents would let/let me won't let me. keep the puppy I found. 4. I I woke up late and missed I wish/If only I hadn't woken up late . I wish/If my flight to Rome. only I hadn't missed my flight to Rome. I wish/If only I were artistic. I wish/If only I paint or draw, but I'm not 5. I Everyone in my family can could paint or draw. artistic at all. 1 B Choose the correct answers. 2 1. You had better in here . The fire alarm might go off. @ not smoke b. to not smoke c. not smoked 3 2. Imagine you the opportunity to become a guitarist. What would you have done? a. not had b. don't have @ hadn' t had 3. I would rather you her about the situation. Now she's very worried. a. not have told b. didn't tell @ hadn' t told 5 4. It's time . Don't you think? a. to have left @ to leave c. we had left 5. I get along with my brother but I wish he his clothes lying around the house. a. couldn't leave b. hadn't left @ wouldn' t leave 6. After our argument she acted as if nothing _ @ had happened b. would happen c. has happened 7. He would rather pizza. He didn't like the spaghetti. a. ordered @ have ordered c. had ordered 8. I'd prefer tea rather than coffee, if you don't mind . a. have ® to have c. having 9. I've got a terrible head ache . If only I to bed late last night. @ hadn' t gone b. didn't go, c. wouldn't go 10. I really liked our day trip to the countryside. I wish we again next week. a. going b. went @ could go ke my olen . e sh/lf -------- page 97 CChoose the correct answers. SMOKING IN PUBLIC PLACES I'm not a smoker and I prefer (1) around non-smokers rather than smokers. In fact , I think it's about time they (2) smoking. I hear smokers talk about smoking as though it (3) harmless but we all know the damage it can cause. Why should I have to put up with it in public places? If only people (4) the consequences of smoking, they might not take up the habit in the first place. The government had better (5) action soon. It's time they (6) cancer related deaths is increasing every year. 1.0to be b. be c. having been 2. a. are banning (h) banned c. had banned 3.@were b. be c. had been 4. a. consider ® considered c. have considered smoking everywhere. The rate of lung 5. a. be taking ® take c. taken b. will prohibit c. have prohibited D Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Jeremy regrets not having accepted the job he was offered. wishes Jeremy wishes he had accepted (hadn 't rejected) the job he was offered. 2. If you had heard the politician speak, you'd think he had won the elections. though The politician spoke as though he had won the elections. 3. I think you should get a haircut! about It's about time you got a haircut! 4. I can 't stand bon-owing my clothes without asking me first. rather I would rather Betty didn't borrow my clothes without asking me first. 5. It 's a pity governments spend so much money on nuclear weapons. wouldn't I wish governments wouldn't spend so much money on nuclear weapons. 6. I advise you to see the dentist today, otherwise your toothache will get wor se . better You had better see toothache will get worse. 7. It would have been better to have hired a car during the holidays. only If only we had hired 8. I would like to know how to play the piano. knew I wish I knew how the dentist today, otherwise your a car during the holidays. to play the piano. .. 01 page 98 I Vocabulary Practice A Complete using the phrasal verbs given. 4. Luckily, the fire brigade came quickly and put out put aside: keep sth to be dealt with or used 1. I always put on weight during the winter. at a later time 2. One thing I can't put up with is rudeness . put away: store sth tidily where it is usually 3. You shouldn't put off the meeting with Mr Brown. kept put oR: postpone the fire . put on: (1) wear (clothes) (2) gain weight put out: extinguish (a cigarette or fire) r T put up put up: offer hospitality put up with: tolerate or accept sth unpleasant B Complete using prepositions. 1. Do you believe i n ghosts? 2. You'll find the information aboutjon prehistoric animals in the encyclopaedia. 3. I insist on paying for dinner. 4. The employees were unaware of the financial problems the company was having . 5. I always listen to the news in the morning. 6. Are you certain of/ about the time our flight leaves? 7. Kim is familiar with most of the computer programmes on the market. 8. We haven't heard from Jane for weeks .. 9. Mr Kent had no knowledge of your whereabouts. 10. Did you inform them of/about the new plan? 11. Were you serious about buying a yacht? 12. I knew nothing of/about Tony's accident. B Complete using the correct form of the words in bold type. JUST TO BE ON THE SAFE SIDE... People are becoming more security conscious these days. Climes like burglary and theft are definitely on the increase. One of the most painful THIEF, PAIN experiences a home owner can have is to arrive home and find that his or her OWN valuables have disappeared because a window had accidentally been left VALUE, ACCIDENT open. What can we do to protect ourselves? ADVISE The most important piece of advice is to make sure that your INSURE, SENSE ins urance coverage is up to date. Another sensible thing to do is to go along to your local police station , where they will be more than willing to make " SUGGEST, RELY suggest ions on reliable ways of safeguarding your property. ------------------------------- page 99 D Complete using the words given. rown. from hem. for ENT y wild [odj]: very excited and ou t of control mad [cd j]: (1) very an gry (2) crazy or foo lish furious (odi): extrem ely angry bad-tempered (odj] : not cheerful,getti ng angry easily irritable [cdj] : getting annoyed easily nervous (cdj] : obviously anxiou s or worri ed about sth that is happening or might happen sensitive (adj): (1) easily affected or harmed by sth (2) aware of and understandi ng ot her people' s needs and pr oblems sensible (adj) : based on reason , not on emotions timid (odj ): shy, nervous, lacking in courage and self co nfi de nce shy (adj): nervous and uncomfortable in the company of ot her peo ple embarrassed (adj): feel ing uncomfortabl e in a sit uation or guilty a bout sth ashamed [cdj): feeling gu ilty or embarrassed because of sth you have done nervous 1. The students were obviously __:..:..::..:....:....::..::.=.__ before the exa m. 2. In the heat , babies get irritable and restless. 3. My parent s were furious/mad with me when they found out that 1had used the car without their permi ssion. 4. The crowd went wild/mad as soon as the band began playing. 5. Som e people are bad-tempered by nature. mad/furious 6. I'll tell you the truth. Just don 't get _ :":'=:=L..:..'::":"':":=_ 7. Michelle is a ver y good social worker. She ' s very sensitive to other people ' s proble ms. 8. The sensible thing to do would be to get a lawyer' s advice. 9. You should be ashamed of yourse lf for acting like a child. shy/timid friends at the new school. 11. You can imagine how embarrassed I felt when I realised I was wearing two different shoes. 12. I'm too shy/timid/ to sing in publi c. embarrassed unit 18 Reported Speech In Direct Speech we give the exact words somebody said and use quotation marks. In Reported Speech we give the meaning of what someone said, but with some changes and without quotation marks. Direct Speech: She said, "I'm tired. " "I'm tired, " she said. Reported Speech: She said (that) she was tired. We usually introduce Reported Speech with the verbs tell (when there is a person/pronoun as an object) and say (when there is no person/pronoun as an object). That is optional. "I'm leaving, Tom," she said. ---+- She told Tom (that) she was leaving. "I'm leaving," she said. ---+- She said (that) she was leaving. Changing from direct to reported speech Direct Speech Reported Speech Present Simple He said, "I want to buy a new car. " Past Simple He said (that) he wanted to buy a new car. Present She said, "I'm learning Spanish." Past She said (that) she was learning Progressive Progressive Spanish. ~ Past Simple "I missed the train, " he said. '" ::: ~ Eo-; Present Perfect "I've missed the train, " he said. Past Perfect Simple He said (that) he had missed the train. Simple Past She said, "I was staying with a Progressive friend. " Past Perfect She said (that) she had been staying Present Perfect She said, "I have been staying with Progressive with a friend. Progressive a friend. " will She said, "I'll call you." would She said (that) she would call me. can He said, "I can run very fast. " could He said (that) he could run very fast. may They said, " We may go on holiday." might They said (that) they might go on holiday. '" 'f must She said, " I must get up early every had to She said (that) she had to get up early ~ ~ - day. " (obligation) every day. ell 'e He said, " You must be tired." must (deduction) He said (that) I must be tired. o ;;E must not She said, "You mustn't smoke." must not She said (that) Ilwe mustn't smoke. (prohibition) need She said, "I need to go shopping. " needed/had to She said (that) she needed/had to go shopping. needn't He said, "I needn't hurry." She said, "You needn't pick me up tomorrow. " He said (that) he didn't have to hurry. She told me (that) I wouldn't have to pick her up the following day. needn't/didn't have to (present) wouldn't have to (future) ~ would, could, might, should, ought to do not change in Reported Speech. ive the say ' anew g Ie train. lying /le, yfast. on pearly oke. togo i hurry. ve to _________________________________________ page 101 Direct Speech Reported Speech ~ now then .= today/tonight that day/that night QI '" 8 ~ yesterday the day before/the previous day ... s f-; ~ tomorrow the next/following day W last week (month, etc.) the previous week (month, etc.)/the week (month, etc.) before next week (month, etc.) the following week (month, etc.) ago before '" this/these that/those l.< QI ~ ~ here there o~ pronouns /possessive adjectives they change according to the context u No changes are made in the following cases: • When the reporting verb is in the Present, Future or Present Perfect tense. He says, ''I'll be a lawyer when I grow up. " ~ He says (that) he will be a lawyer when he grows up. • when the sentence expresses a general truth or something that is unlikely to change . She said, "The days are longer in the summer." She said (that) the days are longer in the summer. She said, "I prefer coffee to tea." ~ She said (that) she prefers coffee to tea. • The Past Perfect (Simpl e and Progressive) does not change in Reported Speech. She said, "I had prepared dinner in advance." ~ She said (that) she had prepared dinner in advance. • The Past Progressive does not usually change; Past tenses in time clauses do not change. "I was speaking on the phone when the doorbell rang," she said. ~ She said (that) she was speaking on the phone when the doorbell rang. • When som ething i s reported immediately after it is said. "This dress looks awful," Mary said. ~ Mary said (that) this dress looks av:ful. • The Past Simple in coll oquial speech can either change or rema in the same . "I got my school report yesterday," said Jim. ~ Jim said (that) he got/had got his school report the day before. • When something, although said earl ier, wi ll take place in the·future. John said, "I'm flying to Rome tomorrow." John said (that) he is fl ying to Rome tomorrow. (It is still today.) • When there is a Conditional (Type 2 or 3) or a sentence with wi sh/If only. Peter said, "If I wer.e rich, I would travel a lot." Peter said (that) if he were rich, he would troveI a lot. Karen said, "If I hadn't woken up late, I wouldn't have missed the bus." ~ Karen said (that) if she hadn't woken up late, she wouldn't have missed the bus. Susan said, "1wish I knew his name. " ~ Susan said (that) she wished she knew his name. Reported Questions Reported Questions are introduced with the verbs ask, inquire, wonder, want to know, etc. The auxiliaries do, does, did and question marks are not used. The word order is the same as in statements and the tenses change according to the rules. Type Form Examples Yes-No questions "Do you spe ak German?" ~ ask d ] + if/whether + subject + verb won er, etc. She wondered if 1 spoke German. Wh-questions ask ] . d b' b "Where do yo u live?" ~ wonder , etc. + question war + su ~ e c t + ver She wanted to know where 1 lived. 1 - Whether ofte n indi cates uncertain ty or doubt. It is used when there is a choice between two B alterna tives. He won dere d whether I had posted the letter or not. ~ Question Tags are omitted i n Reported Speech. "Th ey haven't arrived yet, have they?" he said. -.. He asked if/whether they had arrived yet. 1 Commands - Requests - Advice To report command s, requests, advice, warnings or sugges tions, we use the verbs tell, ask, beg, order, command, 21 advise, forbid, warn, encourage, etc. + (obj ect ) + full infinitive The flight attendant said, "Please return to your seats and fasten your seat belts. " -.. The flight attendant asked us to return to our seats and fas ten our seat belts. 3 "Don 't talk so f ast, " he said. -.. He advised me not to talk so fas t. Other Reporting Verbs • refuse/offer/promise ( + object)/threaten ( + object)/claim/agree, etc. + full infinitive "I' II pick you upf rom the airport, " he said. -.. He offered to pick me up fro m the airport. • accuse sb of/complain to sb about/insist on/admit (to)/deny/apologise for + -ing form Susan said, "He stole the old woman's handbag. " -.. Susan accused him of stealing the old woman's handbag. "I didn't write anything on the desk, " he said. -.. He denied writing/having written anything on the desk. • complainlexplainlagree/claim/deny ] th t I . / h nI (obj ect) + a -C ause promise t eate warn + object "My coffee is too cold," she said. -.. She complained that her coffee was too cold. E goi ng for a swim. " Let' s go for a swim," Peter sai d. -.. Peter suggested that t hey should go for a swim. that the y go/went for a swim . Grammar Practice A A dentist advises her patient on her problem. Rewrite the dialogue in Reported Speech. Mrs Kent: My gums are very sore. Yes terday, as I was brushi ng my teeth, I noticed that my gums were bleeding! Is there anything wrong with them? How can I stop the bleeding? What should I do? Dentist: Firstly, don't panic. If you take my advice, you won' t have any problems. Buy a soft toothbrush and brush your teeth twice a day to keep your gums healthy. I'll make an appointment for you next week, so that I can remove the plaque that has built up and is causing you problems. Mrs Kent said that her gums were very sore. She explained that the day before/the previous day, as she was brushing her teeth, she noticed that her gums were bleeding. She asked the dentist if there was anything wrong with them and how she could stop the bleeding . She wanted to know what she should do. The dentist told her not to panic. He said that if she took his advice, she wouldn't have any problems. He advised her to buy a soft toothbrush and to brush her teeth twice a day to keep her gums healthy. He said that he would make an appointment for her the following week, so that he could remove the plaque that had built up and was causing her problems . 1 ________________________________________ page 103 BChange the following sentences into Reported Speech. Use one of the reporting verbs given below. advise suggest warn threaten complain promise inquire agree apologise refuse 1. "Why don't we invite Jane to dinner tonight?" Mrs Stone said. Mrs Stone suggested inviting/that they invite(d)/that they should invite Jane to dinner that night. 2. "Where is Mount Everest?" asked a student. A student inquired where Mount Everest was. LIS 3. "If you scream, I'll shoot," said the robber to the girl. The robber threatened the girl that he would shoot her if she screamed. or The robber threatened to shoot the girl if she screamed. 4. "I have been standing in this queue for two hours! " said the man. The man complained about standing/that he had been standing in that queue for two hours. 5. " You should stay in the shade and wear a hat, Mrs Bent," said the doctor. The doctor advised Mrs Bent to stay in t he shade and wear a hat. 6. "You' ll burn yourself, Tom, if you keep playing with matches," said his father. Tom 's father warned Tom that he would burn himself if he kept playing with matches. 7. "I' m reall y sony that I woke you up this mornin g, Harry," said Chri s. Chris apologised to Harry for waking him up that morning. 8. "I think you' re right, Tracey. We ought to let the others know," said Kerry . Kerry agreed with Tracey to let/that they ought to let the others know. 9. "I' ll definitel y pay you back by the end of the week, Mum," said Sue. Sue promised her mum that she would definitely pay her back by the end of the week. or Sue promised to pay back her mum by the end of the week. 10. "I will not let you borrow my car tomorrow, Graham," said Michael. Michael refused to let Graham borrow h.is car the next/the following day. C Rewrite using Direct Speech. Sandra told Marie that she had been trying to call the universit y for the last hour but the line had been engaged. Marieinquired what Sandra wanted to ask them. Sandra answered that they had sent out her results the week before but that she hadn 't received them yet. Marie asked Sandra whether she knew that the post office had been on strike for the past week. She replied that she hadn 't known. She expl ained that if only she had known, then she wouldn't have wasted so much time on the phone. Sandra: I've been trying to call the university for the last hour but the line has been engaged. , Marie: What do you want to ask them? Sandra: They sent out my results last week but I Ilaven't received them yet. Marie: Did you know that the post office has been on strike for the past week? Sandra: No, I didn't know. If only I had known, t hen I wouldn't have wasted so much time on the phone. page 104 _ D Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. "I must have this document translated into French," said Robert. had Robert said that he had to have that document translated into French. 2. "You really must let me pay for the meal, " said Jane. insisted Jane insisted on paying for the meal. 3. "Leave me alone," Tony said to us. told Tony told us to leave him alone. 4. "I rang you last night, Julie," said Brian. rung Brian explained to Julie that he had rung her the previous night. 5. "You needn't move to England next year, " they told me. would I was told that I would not have to move to England the foll owing year. 6. "How much does it cost to go to Rome by plane?" he asked himself. wondered He wondered how much it cost to go to Rome by plane. 7. "Are you working today, Peter?" she asked. whether She wanted to know whether Peter was working that day. 8. "Don't bring your dog into the shop," the shop owner said to Mary. forbade The shop owner forbade Mary to bring her dog into the shop. TI cl th I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. throwaway: get rid of sth you don't want throw out: (1) force sb out of a place or group (2) get rid of sth you don't want tidy up: ma ke a place neat try on: put on clothes to see if they fit you or if they look nice try out: test sth in order to see how effective or useful it is 1. Tidy up this room! It's a complete mess! 2. Could we trv out the bike before we buy it? 3. He ate the last biscuit and threw away/out the packet. 4. Would you like to tryon this dress ? The dressing room is over there. 5. He was thrown out - --- r-- -- -------0 - ..0--- B Complete using the prepositional phrases given. on time: not late, at the expected or scheduled time on the way: in the course of a journey out of breath: breathing very quickly and with difficulty because you've been doing sth energetic out of control: uncontrolled, unrestrained out of danger: safe, no longer likely to be harmed out of fashion: old-fashioned, no longer popular out of luck: unlucky out of order: broken, not working, not functioning properly out of reach: impossible to have, get or accomplish out of sight: sth that you cannot see out of work: unemployed I . Medicine should be kept out of reach of children. 2. It seems we're out of luck . The last tickets were sold to the couple in front of us. 3. The fire was out of control because of the high winds. 4. Don't worry, she usually arrives at meetings on time 5. It's depressing being out of work . There's nothing to do and no money to spend. 6. We'll stop on the way to their house and buy a bottle of wine. 7. Why are you out of breath ? Have you been running? 8. I watched the train leave until it was out of sight . 9. I couldn't call you because my telephone was out of order 10. Nowadays people can wear whatever they like . Hardly anything is out of fashion . 11. Fortunately, it was announced that all the injured people from the accident were out of danger . nch. ar. om he nd me. hing m _________________________________________ page 105 CComplete using the correct form of the words in bold type. CLIMBING UP THE STARSl The highest mountain in the world is Mount Everest, 8 848m high. Many adventurous climbers have risked their lives climbing it. More than 140 people have died, some in their attempt to reach the peak, and others who were unfortunate in their return trip from the top. Being confi dent is not enough for this trip. You should be fit, skilled and you must take the proper supplies with you. This could mean the difference between life and death. Nevertheless, such an operation is full of danger. Rarely does a climber return from Mount Everest without needing medical attention. Somecome down, with fingers or toes so frozen that they clink like glass. But what is it that makes people risk their lives or take the punish ment Mt Everest imposes on them? Why is it that even the death of fellow climbers doesn't discourage them? Understanding climbers' reasons may be difficult. Perhaps it's the thrill of standing on the peak of the highest mountain, the place on earth that's the closest to the stars. DComplete using the correct form of the words given. ADVENTVRE FORTUNE CONFIDE SUPPLY OPERATE MEDICINE FREEZE PUNISH COURAGE UNDERSTAND baker v}: boil (v): grill (v): roast (v): fry (v): spread (v): spill (v): drop (v): flood (v): debate (n): cook in an oven (e.g. cake) cook in boiling water cook using strong heat directly above or below the food cook food by dry heat in an oven or over a fire cook food in a pan with very hot oil or fat apply on a surface as a coating accidentally cause sth (usually liqu id) to flow on a surface cause sth to fallon the ground make or become covered with water (formal) discussion about a subject on which people have different and often opposing opinions discussion (n):when people talk about an issue in order to reach a decision dialogue (n): (1) communicat ion or discussion between people or groups of people (2) conversation between two people in a book, film or play interview (n): (1) formal meeting at which sb is asked questions in order to find out if they are suitable for a job or course of study (2) conversation between a journalist and a famous person 1. Add the pasta when the water has boiled 2. I always fry my eggs with lots of oil. 3. Bake the cake for 50 minutes. 4. Let's Roast 6. Tom dropped the vase and it broke. 7. I always spread butter on my bread. 8. The children forgot to turn the tap off and the whole kitchen flooded 9. Oh no! You've spilt/spi lled the milk on the table . 10. My Interview with the personnel manager went well. I might get the job after all. 11. The dialogue in the comedy was very unnatural. 12. The presidential candidates are going tq have a live debate on television. 13. The members of the school council are going to have a discussion ' tomorrow about how to solve the problem. unit 19 Question Forms A . Yes /No Questions These questions may be answered simply with a Yes or No. Formation Examples auxiliary verb j He lives in Manchester. ---+ Does he live in Manchester? modal verb + subject + main verb I can swim well. ---+ Can you swim well? be/have He is an accountant. ---+ Is he an accountant? ~ Yes/No questions can receive short answers, that is Yes/No + subiect + auxiliary (positive or negative). Is he looking for a new iob? Yes, he is. ~ Other ways of answering Yes / No questions in short: I expect so / I don't expect so / I expect not I suppose so / I don't suppose so / I suppose not I imagine so / I don't imagine so / I imagine not I think so / I don't think so I hope so / I hope not I guess so / I guess not I'm afraid so / I'm afraid not absolutely (not), certainly (not), definitely (not), of course (not) Can the children play in the garden? Certainly. / Iguess so. / I'm afraid they can't. / I'm afraid not. B. Wh-Questions Questions beginning with the words: who, which, whose, what, why, when, where and how ask for specific information. Formation Examples questiOn] auxiliary verb/] bi b What are you looking for? + + su ject + vel' word modal verb When must you leave? question word + be/have + subject Where are they? Prepositions are usually placed at the end of a question. e.g. What did he talk about ? In formal English, prepositions can appear before the question word. e.g. About what did he talk? Question Word We ask about: Examples Who people (subject or object) Who is your best friend? Who are you talking to? Whom people (object), in formal English or Who(rn) did you meet yesterday? after prepositions To whom has she been talking? Which people or things (limited choice) Which students will participate in the survey? Which of these sweaters do you like best? Whose possession Whose are these boots? Whose boots are these? What things (unlimited choice), What did you buy? actions and activities What happened? What...like? general descriptions What is your brother like? What type/sort kind of...? specific information What sort of cars do you like driving? What height are we flying at? What time/size, etc...? What do you need this for? What.. .for? Why reason, purpose Why did he sell his car? When time When are they coming? _________________________________________ page 107 Where place Where is your office ? How manner / the way something is done How did they behave? How+ adjective/adverb specific information How did you fix this? How much/many quantity How deep is this river? How + be someone's health How long does it take to fly to London? How much coffee is left ? How is your brother ? Who, what and which may ask ab out the subject or the obj ect of a sentence. er? • Q uestio ns ab out the subj ect do not take • Questions about the obj ect take an auxil iary verb . an au xiliary verb . IPet er I met IJane. ' I Who I met Jane? IPeter I met IJane· 1 I Who I did I Peter I meet? 1 1 1 1 1 1 1 1 Subject Object Subject Subject Obj ect O bject Aux Subject C. Negat ive Questions Negative questions are formed with a negati ve auxiliary in the short form, e.g. Aren't you Bill 's brother? Negative questions are used: Examples • to express emotions (surprise, anger, annoyance, Hasn't he finished his report yet? not. disappointment, shock, etc. ). Can't you dri ve? I thought you could. • when a positive answer is expected. It 's past midnight. Shouldn 't you be in bed? (Obviously yes) • to make sure that some informat ion is correct. Doesn't she live in Paris ? • in exclamations. Wasn't it a wonderful play? ~ If there are two auxi liary verbs, the f irst one is in the negative form. Haven't you been watching the news? ~ We may use t he ful l form of not in nega tive questions for emphasis or in forma l speech. Has he not signed the contract yet? D. Question Tags Question tags are ShOl1 questions placed at the end of a statement. Formation Examples Auxiliary/Modal Verb + Subject Pronoun You can drive a car, can't you? • If the statement is positive, the question tag is negative. He is coming to the party, isn't he? • If the statement is negative, the que stion tag is positi ve. You didn't forget to buy bread, did you? She hardl y noticed anything, did she? Question tag s are asked: • with rising intona tion ~ l , when we are not sure ab out some information and are aski ng for confirmation. You have a driving licence, don't you ( ~ ) ? Yes, I do. • with falling i ntonation (f ), when we are sure about the informati on and expect the listener to agree. It's quite cold today, isn't it (fl ?Ye s, it is. I am your best f riend, aren't I? There's no reason for him to co me over, is Let's go danci ng tonight, shall we? there? Let me give you a hand, will/won't you? They've got two chi ldren, haven't they? Leave the window open , will/can/would/could She has breakfast every morning, doesn't she? you? Everyone agreed with his proposal, didn't they? Don't forget to buy some groceries, will you? Somebody must take care of the situation, This/That is an amazing sto ry, isn't it? mustn't they? Nothing is wrong, is it ? No one would ever t rust him, would they? page 108 ~ = : . ~ ~ ~ ~ : ~ : ~ ~ : : : : : : ~ . I I I I l •••••••••••••• E. Indirect Questions Indirect questions begin with phrases such as Can/Could you tell me...? Do you know...? Can you remember...? Can/Could you explain...? Have you any idea ...? etc. They are used mostly when we ask for information. Formation Examples • introductory phrase + question word + subject + verb Where is the National Galleryr r-o when the direct question begins with a question word Could you tell me where the National Gallery is? • introductory phrase + if/whether + subject + verb Was thejlight delayedi i--e when the direct question does not include a question word Do you know if the jlight was delayed? The auxiliaries do, does and did are never used in indirect questions. Does he play golf regularly? -. Do yo u know if he plays golf regularly? Grammar Practice A Write questions. The answers are the words in bold type. 1. Which jumper suits me better, the red or the blue one? The red jumper suits you better than the blue one. 2. Did the basketball player sign the contract? I'm afraid not. The basketball player didn't sign the contract. 3. What does t he price include? The price includes two meals at the hotel restaurant, so it's convenient. 4. Howdid she feel when she fell? She felt embarrassed when she fell , as most of her guests were around. 5. Does the library open at 9:00 a.m. every weekday? Yes, the library opens at 9:00 a.m. every weekday. 6. Where will Professor Burns give his lecture? Professor Bums will give his lecture at the Palace Hotel. 7. Why are you buying a computer? I'm buying a computer because I need it for my job. 8. Who persuaded Jane to give up smoking? Paula persuaded Jane to give up smoking. Isn't it great? 9. What is your new house like? My new house is big and has a garden at the front. 10. Can I go to the beach with my friends? I suppose you can go to the beach with your friends. B Use the \Yords in brackets to make negative questions. 1. "Last year the children organised a bazaar to raise money for the hospital. Wasn't it a great idea ? (it/be/a great idea)" "Yes, I think they should do it again." 2. "I bought a new jacket today but the sleeve is tom!" Shouldn't you take it back ? (you/should/take/itlback)" "Yes, I will. I'll ask for another one." 3." Isn't the Town Hall just around the corner ? (the Town Hall/be/just around the corner)" "Yes, that's right." 4. "You've ruined my jumper by spilling coffee on it and last week you spilt bleach on my jeans. Can't you do anything right ? (you/can/do/anything right)" 5. "You haven't bought any bread. " Didn't you go to the baker's ? (you/go/to the baker's)" "No, I went to the supermarket but completely forgot to get some bread." ----------------------- ________________________________________ page 109 CComplete using question tags. Tanya: ... and the animal rights group I'm in is holding a demonstration outside one of the research laboratories. Brett: Do you think that's reall y necessary? I mean, there's a need for these experiments, is n't there ? Let's consider the advantages of these experiments, shall we ? Scientists must test new medical treatment somehow, mustn't they ? With these tests they can see how effective and safe the treatments are . Everyone wants new vaccines and safer drugs, don 't they ? Tanya: I see your point, but scientists don't really care about the animals, do they ? Are you aware that thousands of animals die every year as a result of these experiments? Scientists should find another way of testing their discoveries, shouldn't they ? DMake Indirect Questions using the phrases, Can/Could you tell me.••?, Can/Could you explain..•?, Do you know.•.?, Have you any idea.•.?, Can you remember••.? 1. How do you operate this video? _._.._h_o_w--' y'-- o_u_o--' p_e_r_ at_e_t_h_is_v_ id_e_o_ ? _ 2. Who directed this film? ... who directed this film? 3. Has the Moore family moved to their new house? if the Moore fam ily has moved to their new house? 4. When is their wedding anniversary? when their wedding anniversary is? 5. Did.we invite John to our party? if we invit ed John to our party? 6. Was the trip postponed? _.._.if_t_h_ e_t_ri..:.... p_w_a_s----'-- po_s_t..:.... p_o_n_ ed_?_ . _ 7. Whose is the luggage in the living room? whose the luggage in the living room is? 8. Where should I get my eyes tested? where I should get my eyes tested? 9. What time did you set your alarm clock for? what time you set your alarm clock for? 10. Are you working this weekend? if you are working thi s weekend? EUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. What was the price of the ticket? pay How much did you pay for the ticket? 2. Whose car is this? belong Who does this ca r belong to? 3. The film was interesting, wasn't it ? boring The film wasn't boring , was it? 4. How did the fire start, sir ? explain Could you explain how the fire started , sir? 5. Mr Wesley, what caused you to resign so suddenly? why Mr Wesley, why did you resign so suddenly? 6. Can you tell me Tom's address, Kelly? lives Can you tell me where Tom lives , Kelly? 7. What's the distance from the village to the beach? it How far is it from the village to the beach? 8. Should I inform our clients about the change of plans? whether I'd like to know whether I s hould inform our clients about the change of plans. I Vocabulary Practice page 110 ; . ~ : ; : ~ ; ; ; ~ : : : : ~ _ A Complete using the correct form of the phrasal verbs given. 1. Michael ran away from his boarding school because he ring up: telephone run along: go away thought it was too strict. run away: leave from a place that 2. I can't start the car because I've run out of petrol. makes you unhappy, escape 3. Peter, run along now and play with the other children. run into: meet sb unexpectedly run out (of): have no more of sth left 4. I rang up the restaurant and made a reservation. run over: knock down a person or 5. You'll never believe who I ran into the other day. animal with a vehicle 6. I accidentally ran over a cat as I was parking my car. B Complete using the prepositional phrases given. 1. If you are on a diet ~ _ . ••••0 __ 'j _ • -- .OJ off duty: not working off school/work: away from school or not foods and sugar. working because you are 2. Sue doesn't take the bus to school. She goes on foot ill 3. We are planning to go on a trip/on an to Bath next on behalf of: as a representative of sb excursion on business: in another place, working weekend. Would you like to join us? on the contrary: (1) not at all 4. Police officers don't carry their guns when they are (2) quite the reverse off duty on a diet: not eating very much because you are trying to 5. I'm going to give a talk on behalf of Greenpeace. lose weight 6. Extra staff were called on duty at the hospital after the on duty: working on an excursion/ terrible earthquake. a journey/ 7. I don't believe you; on the contrary ,I believe Bill. a tour/a trip, etc.: away for these reasons 8. Kim is in Brazil on business this week. Her job requires on fire: burning on foot: walking her to meet overseas clients. 9. You aren't feeling well and you've got a temperature! Take a few days off work . I'm sure your boss will understand. 10. Call the fire brigade. The neighbour's house is on fire C Complete using the correct form of the words in bold type. SOME GUYS HAVE ALL THE LUCKI It is thought that some people are just born lucky . They seem to have everything, LUCK from the perfect family to the best employment at the most successful company in town. EMPLOY Their good fortune causes jealousy in less fortunate people, who do all sorts of things JEALOUS to bring luck into their lives. Some people carry good luck charms, such as blue stones and horseshoes on a daily DAY basis, to make sure that they will stay healthy , safe and free from injury/les HEALTH, INJURE Also, some otherwise logical people go through superstitious actions like touching LOGIC wood in order to bring themselves good luck. But is there really any relation/ between all these things and success in life? Many RELATE relationship . people consider good luck charms foolish and unreasonable . They believe that FOOL, REASON success in life comes through working hard. --------------------------- page 11 1 D Complete using the corred form of the words given. bundle (n): a number of things wrapped or ti ed together in order to be carried heap (n): pile of things arranged in an untidy way pile (n): a quantity of things arranged neatly one on top of the other bunch (n): a number of similar things fastened, growi ng or grouped together (grapes, keys, etc.) pack (n): a col lection of thing s packed together (in a bag or packet) (v) put your belongi ngs into a bag because you're leavi ng a place or go ing on hol iday packet (n): .small container made of thin cardboard, paper or plastic, in whi ch items of the same ki nd are sold (biscuits, ci garettes, etc.) package (n): small parcel parcel (n): sth wrapped up in paper, usually the to be given or sent to sb by post wrap (v): fold paper or cloth around sth in order to cover it completely fasten (v): do sth up by means of buttons, straps, buckles or other devices tie (v): fasten with a stri ng or rope, a making a knot d. fold (v) : bend sth so that one pa rt cove rs another E 1. Hi s room is very unti dy; his clo thes are all thrown in a heap in a corner. 2. I bought my mother a bunch of flowers on Mother's Day. 3. Kerry keeps her old magazines tied up in bundles/piles in the att ic. 4. I want you to arrange these folders in alphabetical order and put them in a neat pile on my desk. packet parcel! 7. Simon is busy packing his clothes for the trip. 8. Little John is learn ing to tie his shoelaces. 9. Please fasten your seat belts. 10. Could you wrap thi s for me ? It' s a gift. 11. Would you fold these sheets for me and put them in the bottom drawer? unit 20 Clauses I A . Relative Clauses Rel ative clauses are introduced by relative pronouns (who, whose, whom, which, that) or relative adverbs (when, where, why) . Relative Pronouns For people For animals/things who, that , which who/that which/that (subject of the verb I saw a boy. He could ride his bike He has writt en a book. It is about the history of cannot be omitted) without using his hands. ---.. education. ---.. He has written a book which is I saw a boy who could ride his bike about the history of education. without using his hands. who, whom, that, who/whom/that which/that which He liked the girl. He met her at the pa rty That hat looks old-fashioned. She bought it (object of the verb yesterday. ---.. He liked the girl (who/ recently. ---.. The hat (which/that) she bought can be omitted) whom/ that) he met at the party yesterday. recently looks old-fashioned. Whom is used in fonnal speech or after prepositions. whose, of which whose whose/of which (poss ession-cannot I know the writer. His latest novel was I have a car. Its engine is noisy. ---.. I have a car be omitted) a great success. ---.. I know the writer whose engine/the engine of which. is noisy. whose latest novel was a great success. ~ Prepositions normall y go after relative pronoun s. In formal speech, prepositi ons can go before whom and which only (not before who/that/whose). The bed (that/which) I slept in last night was very soft . (usual) The bed in which I slept lost night was very soft. (formal) ~ Expressions of quantity (some of, many of, a few of, mo st of, hal f of, neithe r of, none of, a number of, etc.) can be foll owed by whom/which/whose. Our company has 80 employees, most of whom are computer literate. ~ Which somet imes refers to a whole sentence and cann ot be omitted. The lift was out o f order and this was very inconvenient. ---.. The lift was out of order, which was very inconvenient. Relative adverbs Use Examples when (can sometimes be omitted) Time I'll neverforget the day (when) I firs t met him. where Place The village where I grew up is very small . why (can sometimes be omitted) Reason The reason (why) he left was that he felt disappointed. . ~ That can be used instead of when. I'll never forget the summer when / that we went to Nice. ~ In/on/at which can be used instead of when and where. Where can be omitted or substituted by that if the verb is foll owed by a preposition. We stayed at a rather cheap hotel. ---.. The hotel where / at which we stayed was rather cheap. or The hotel (that) we stayed at Was rather cheap . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ page 113 Defining and non-defining relative clauses • Defining relative clauses provide infor ma tion which is esse ntia l to the meaning of the se ntence. No comm as are used . • Students who cheat should be punished. I, • Non-defining relative clauses provide additional information (not essential to the mea ning of the sentence). They are put between co mma s. The relative pronouns cannot be omitted; neither can we use that instead ofthem . DrMiller, who is the Head of the Deportment, will attend the reception. B. Clauses of Time Clauses of time are introduced by: when, as, while, as soon as, before, after, until, till, by the time, just as, since , the moment (that), whenever, every time, etc.They can go before the main clause (separated by a comma) or after the main clause (no comma is required). As soon as the fire alarm went off, everyone left the building. Everyone left the building as soon as the fir e alarm went off. Sequence of tenses Main clause Time clause Examples present / future present I 'll wait until the rain stops. past past I wait ed until the rain stopped. Time conjunctions m Conjunctions Use Examples when • for two events happening at the He dropped his shopping bag as he was as same time running to catch the bus. while er just (as) • for two short actions happening at Just as we got to the beach, it started to rain. the same time when • for event s taking place one after the They may go out af ter theyfinish/havefini shed as soon as other their homework. before He left before I could explain anything. after by the time • meaning "not later than" I will have finish ed my work by the time you arrive (=no later than the time you arrive). until, till • meaning "up to a certain time" I won't leave until I have finished everything. I Grammar Practice A Complete using who, whose, which, that, where, why or -. Sherlock Holmes, whose name is well-known, didn 't really exist. However, for many who/that have read his adventures, he might as well have been a real per son. The man who/that created Holmes was Sir Arthur Conan Doyle, born in Edinburgh in 1859. He trained as a doctor, but found he could earn more money by writing than by practi sing medicine. He wrote not only stories about Holmes, but many other books which/thatj- people al so liked. However, it is for the detective stories which/that/- he wrot e that he is best remembered. where who page 114 ~ : ~ : : : : : : : ~ : : : ~ : : : : ~ _ detective, uses his intelligence and scientific knowledge to solve the mysteries. Even though Doyle wrote many Holmes mysteries, we'll never know the reason why/ - he gave us so little information about Holmes' private life. Allthe books were written in the first person, not by Holmes, but by his assistant, Dr Watson, whose knowledge of his master's private life was limited. BJoin the sentences using relative pronouns or adverbs. Omit them where possible. 1. The journalist will interview the old man. His house was broken into last night. The journal ist will interview the old man whose house was broken into last night. 2. I remembered the man. I had seen him at the concert. J remembered the man who/whom/thatj- I had seen at the concert. 3. We visited the town. We were born there. We visited the town where/in which we were born. or We visited the town thatj- we were born in. 4. Bill and Jane haven't been talking to each other for days. There must be a reason. There must be a reason why Bi ll and Jane haven't been talking to each other for days . 5. People believe that the old building should be pulled down . The old building is on Park Street. People believe that the old bUi lding which/ that is on Park Street should be pulled down. 6. She got up late and missed the boat. That was quite foolish of her. She got up late and missed the boat, which was qU ite foolish of her. 7. I invited Mrs Kansas to my party. She lives next door. I invited Mrs Kansas , who lives next door. to my party. 8. We must arrange a time. Then we can discuss the problem. We must arrange a time when we can discuss the oroblem. C Choose the correct answers. _____ (1) we hear Walt Disney's name, we,' 1. a. While @ Whenever c. Just immediately think of the huge company which produces the world's most popular cartoon characters. This is Disney's story. Walt Disney was born in 1901. (2) he was 2. Ci)As b. As soon as c. Once growing up on a farm in Missouri, he became interested in sketching. He drew sketches of the animals living on the farm. He attended an art school (3) he was 3. a. as @ when c. just fourteen for a short period of time. (4) 4. a. By the time b. Every time Q After the war ended, he worked at a commercial art studio in Kansas City , where he met Db Iwerks in 1919. They worked together (5) Iwerks died. Together 5. a. since b. when C£,) until they began making advertisements, but it wasn't long _____ (6) they began creating and selling their 6. (Q)before b. after c. once own cartoons. The success of these cartoons was what made Disney decide to start his own cartoon production company in 1923. It was in 1928 that his most famous character was created-Mickey Mouse. (7) the character 7. a. The sooner b. Before (S) The moment appeared, it became very popular. - _ _ _ _ _ (8) Disney created other popular characters 8. a. Until @ By the time c. Since such as Minnie Mouse, Donald Duck, Goofy and Pluto, e sound and colour had been added to animati on. _____ (9) this had happened, the cartoons became 9. (i) Once b. Whenever c. Till I- ________________________________________ page 115 trul y magical. By the mid 30s, Disney was very successful and hi s organisation had grown into a "factory" of men and women. (10) he continued making 1O.(i)Whil e b. The moment c. When cartoons, he also began making feature length cartoon movies, such as Snow White and The Seven Dwarfs, which proved to be successful (11) it was 11. a. by the time ® as soon as c. until released. Disneyland in California opened in 1955, Disneyworld in Florida in 1971 and Eurodi sney in Paris in 1991. _____ (12) a child enters these amusement 12. a. While b. As long as @ Every time parks, they enter an enchanted world where anything and everything is possible. (13) there are 13. (i)As long as b. Until c. As soon as children and adults young at heart, these parks will remain ··open. Disney died in 1966. Sinc e then, the company has continued to produce animated films which still keep the Disney name the most popul ar in children's entertainment. D Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) I. I hadn 't heard from Robertfor years and yesterday I received a letter from him. who Yesterda y I received a letter from Robert who I hadn't heard from for years. 2. Chris, everyone will be asleep when you come. time Chri s, by the time you come , everyone will be asleep. 3. In 1986 they gave their first concert in Europe. was 1986 was the year when/in which/- they gave their first concert in Europe. 4. I spoke to a very helpful assistant manager last week. whom The assistant manager to whom I spoke / whom I spoke to last week was very helpful. 5. We've inter viewed all of the candidates but we haven 't found anyone suitabl e for the job. none We' ve int erviewed all of the candidates, none of whom are/were suitable for the j ob. 6. During a walk in the fore st Kell y w ~ s stung by a bee. while Kell y was stung by a bee while walking/she was walking in the forest. 7. The shop where I used to work has closed down. which The shop at which I Llsed to work has closed down. 8. I went to two pay phon es, but they were both out of order. which I went to two pay phones, neither of which worked. L ~ : : ; ~ ; ~ ~ ~ : ; : : ~ page 116 _ • I Vocabulary Practice (] A Complete using the correct form of the phrasal verbs given. 1. I set out to do some gardening, but it started raining. save up: economise by spending less than you earn, usual lyfor a purpose 2. John had been saving up his pocket money for months to sell out: sell al l the stocks of sth, so thaf buy a bike. u there is no more left for people to 3. Tickets for the concert were sold out in just one day! buy (goods, tickets, etc.) set oft: begin a journey 4. We set off/out on our trip very earl y in the morning. set out: (1) start a journey 5. My parents helped me set up my own business . (2) start do ing sth y set up: (1) establish sth (ho me, business, u organisation, etc.) (2) ma ke the necessary tl preparations for sth to start B Complete using prepositions. 1. This closet is full of 2. The children were covered 3. The students were divided into two teams. 4. Does this bag belong to anyone here? 5. These beautifully-designed ornaments are made of silver. 6. The concert hall was crowded with screaming fans . 7. This game is very different to/from any other game I've played. 8. The taste of broccoli is similar to that of cauliflower. 9. According to the street directory, we'll find Queen St. straight ahead . 10. There's hardly any difference in taste between these two wines. 11. Keep these magazines separate from the newspapers. 12. Your drink consists ~ different types of fruit j uices . children's toys. wit h/ in mud from head to toe. - _______________________________________ page 117 CComplete using the correct form of the words in bold type. NOT WRITTEN ON THE STARS Lots of people read their horoscope for an insight into their character and for the predictions which are made. Graphologists claim that they too are able to PREDICT understand a person's character-by examining their handwriting! How big the letters, how straight the lines, the presence of loops and even your signature , can reveal something about your personality . For example, if SIGN, PERSON your handwriting slants to the right, you have a cheerful nature. Writing with CHEER upward arches indicates that you are creative . A high t-bar means that CREATE the writer is imaginative and ambitious . But there is much more. IMAGINE, AMBITION Apparently , there are about two-hundred and fifty signs which graphologists APPARENT take into consideration when analysing a person's Writing. CONSIDER believable BELIEVE How accurate or how _ ~ ' - ' - ' - " ' - . ! . " ' - " ~ _ this is, is up to the individual to decide. D Complete using the correct form of the words given. 1. Do you think/suppose I ought to talk to my boss about a regard (v) : believe that sb or sth has a particular quolity raise? think (v): have an opinion or impression 2. I want you to imagine this; miles of golden sand and about sth consider (v): (1) think carefully about sth a beautiful blue sea. Doesn't it sound great? (2) have an opinion about sb or 3. Did you consider Mr Field's offer carefully? sth 4. We regard you as one of our best employees. suppose (v) : imagine that sth is probably true imagine (v): form an idea or picture of sth in 5. I saw Tom and Jill out together, 'so I suppose/think they your mind are dating. 6. Marconi invented the radio. learn (v): obtain knowledge or a skill through studying or training 7. Captain Cook discovered Australia in 1770. find out (v): learn sth you didn't know, 8. The Apollo programme was set up to explore outer especially through deliberate space. effort discover (v) : (1 )become aware of sth you 9. The insurance company have to inspect my car didn't know before (2)find sb or before paying me for the damage caused by the accident. sth by chance or because you 10. Craig has decided to attend classes in order to learn have been looking for them invent (v): create or make up sth for the first time 11. Did you find out whether you're working on explore (v) : investigate sth (a place or scientific field) systematically in Christmas Eve or not? order to find out more facts about it inspect (v) : examine sth carefully in order to check that it is all right ~ unit 21 Clauses II A . Clauses of Concession Clauses of concession express contrast, opposition or unexpected results and are introduced by although, even though, though, in spite of, despite, however, but, while, whereas, no matter how, etc. Structures Examples although Although he has plenty of money, he doesn't spend much. j even though + subj ect + verb Even though there .was a lot of snow, no trains were though delayed. ~ Even though is stronger than although. ~ Though is more informal and can go at the end of a She has a driving licence. She rarely drives, though. sentence, meaning "however". in spite Of] In spite off eeling ill, she came to work. . + noun/-ing form despite Despite her beautiful voice, she never became a singer. in spite Of] . + the fact + that -clause He didn't show up despite the fa ct that we had an despite appointment. however However hard she tries, she never manages to finish her + adjladv + subject + verb no matter how ] work on time. ~ However can also introduce a main clause. Vicky eats a lot. Howev er, she isn't overweight. whatever Nobody believes him any more, no matter what he says. ] + clause no matter what adjective Tired as/though she was, she offered to help us. ] + as/though + subject + verb adverb ~ A very emphatic and formal structure. but . I like travelling by plane. while/whereas my husband hil / h ] + subject + verb w 1 e w ereas doesn't. ~ Whereas is more formal than while . B. Clauses of Reason Reason is expressed with the following structures: Structures Use Examples because + clause • to answer a question with "why" She couldn't get to work on time because the because of + noun/-ing form traffic was heavy / because of the heavy traffic. as • usually at the beginning of a As the weather wasfine, we decided to gofor a since sentence swim. due to + noun/-ing form • formal structure meaning "because Due to a heavy snowstorm, all flights to Oslo due to the fact + that-clause (of)" were cancelled yesterday. If a clau se of reason or co ncessio n com es before the ma in clause, they are separated by a comma. Since you don't trust him, don't tell him anything. But: Don't tell him anything since you don 't trust him. Although the so up was cold, he ate it. But: He ate the soup although it was cold. __________________________________________ page 119 C. Clauses of Purpose Purpose is expressed with the following structures: - Structures Infinitive so as (not) to in order (not) to for + noun for + -ing form so that + can/may/will so that + could/might/would in case + present tense in case + past tense witha view to ] . f + -mg arm withthe aim of for fear / lest + subject + might/should for fear of + noun/-ing form Use • informal structure • informal structures • to express a person's intentions • to express the purpose or function of an item • purpose with present or future time reference • purpose with past time reference • purpose with present or future time reference • purpose with past time reference • formal structure • negative purpose Examples I just called to invite you to a party. He walked in quietly so as not to wake up his parents. We are saving money in order to buy a new car. He went to the pub for a drink. I use the electric knife for cutting meat. Please close the door so that the cat can't come in. He walked quietly so that nobody could hear his footsteps. I'll take an umbrella in case it rains. He gave me his telephone number in case I wanted to call him. He took evening courses in Marketing with the aim of getting more qualifications. He fled his country for fear he might be arrested. He fled his country for fear of being arrested. Clauses of purpose follow the rules of the sequence of tenses. D. Clauses of Result Clauses of result express a deduction or the result of an action and are introduced with: so...that, such...that, etc. Structures such (alan) + (adjective) + noun + that... such a lot of + noun + that... so + adjective/adverb + that... much, manYI so + I' I + + (noun) + that... I Itt e, lew so + adjective + alan + noun + that... (and) so, (and) therefore >- therefore is more formal than so Examples He was such a wise man that everyone respected him. They were such nice people that everyone enjoyed their company. Their new car cost such a lot ofmoney that I wondered how they could afford it. The fog was so thick that we couldn't see across the street. He had made so many mistakes that he had to write his report again. It was so boring a play that I nearly fell asleep. He had the qualifications required, so he got the job. Grammar Practice AMake one sentence using the words in brackets. Advertising Facts Products are advertised mainly through the media. This way, consumers become familiar with the variety of products available. (so that) Products are advertised mainly through the media so that consumers can/may/will become familiar with the variety of products available. Large companies employ advertising agencies. They want to make their product attractive to consumers. (so as to) Large companies employ advertising agencies so as to make their product attractive to consumers. c a. Companies spend millions of dollars on advertising. They want to increase their sales. (with the aim of) Companies spend millions of dollars on advertising with the aim of increasing their sales. b. Advertisers must consider their advertisements carefully. They can't afford to be accused of persuading people to buy things they don't need. (for fear of) Advertisers must consider their advertisements carefully for fear of being accused of pe rs uading people to buy things they' don 't need. All advertisements are reviewed by a consumer protection agency. False information mustn't be given to the public. (in case) All advertisements are reviewed by a consumer protection agency in case false information is given to tIle public. B Read Martha's opinions. Continue the sentences using so or such. o Martha's film reviews - See them if you dare! 1. The film "Walk in the Sky" was boring. I left halfway through. The film was so boring that I left halfway through. It was such a boring film/so boring a film that I left ha lfway through. 2. 3. "Adventures in the Pacific", an animated film, has many funny characters. Both young and old will love it. The film has such a lot of/so many funny characters that both young and old will love it. There are so many/such a lot of funny characters in the film that both young and old will love it. 4. 5. The film 'Tough" has a lot of violence. Many people will refuse to see it. The film has such a lot of/so much violence that many people will refuse to see it. There is so much/such a lot of violence in the film that many peope will refuse to see it. 6. 7. The thriller "Cold Blood" was very frightening. I was on the edge of my seat the whole time. The film was so frightening that I was on the edge of my seat ttle whole time. It was such a frighten ing film/so frightening a film that I was on the edge of my seat the whole time. 8. _________________________________________ page 121 CChoose the correct answers. a. (1) I had set the alarm, it didn't go off, (2) I was late for work. I've decided to go shopping today to buy a new alarm ts clock (3) something like this happens again. I don't want to lose my job all (4) of an alarm clock! f 1. @ Although b. Because c. Despite 2. a. since @ so c. because 3. @j in case b. so as c. in order 4. @because b.due c. though b. We have (5) a lot of fun going on camping trips that we go at least twice a year. I've got all the necessary equipment, ___ (6) you can borrow (7) you need. Just remember ___ (8) well you've planned the trip, expect the unexpected! Pack a first-aid kit, tins of food, bottles of water (9) you'll be prepared for everything. 5.@)such b. so c. therefore 6.@therefore b. while c. whereas 7. a. however @ whatever c. even though 8. a. no matter b. because @ however 9. a. in case @ so that c. so as oUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) I. Whatever they try to do, the police will stop them. no The police will stop them no matter what they try to do. 2. The road was slippery, so they couldn't drive fast. because They couldn't drive fast because of the slipperv road. 3. I've brought some extra blankets because it might get colder at night. case I've brought some extra blankets in case it gets colder at night. 4. You know, I felt disappointed but I didn't give up trying. spite You know, in spite offeeling disappointed/my disappointment , I didn't give up trying. 5. She is very talented but she doesn't play the piano professionally. though Talented though she is , she doesn't play the piano professionally. 6. The children hid the cake they had made because they wanted to surprise their mother. could The children hid the cake they had made so that they could surprise their mother. 7. Kate was too tired to do any housework. so Kate was so tired that she couldn't do any housework. 8. Paul went out even though he wasn't feeling well. fact Paul went out despite the fact that he wasn't feeling well. I Vocabulary Practice page 122 i ~ ~ : ~ ~ : ~ : ; ~ ~ : : : : ~ - - - - - - - - - - - - - - - - - - - - - - - - - - - A Complete using the correct form of the phrasal verbs given. settle down: start living a quiet life in a place, especially after getting married or buying a house sit up: take a sitting position after lying down or leaning back stand by: (1) ready and waiting to provide help or take action (2) provide loyal support to sb stand out: be noticeable stand up for: defend sb or sth and make your feelings or opinions clear B Complete using the prepositional phrases given. on the one/other hand: from one point of view/from the opposite point of view on holiday: on vacation, relaxing on one's mind: in one's thoughts on one's own: alone, without help on the phone: having a telephone conversation on purpose: deliberately, not by accident on the radio/television: broadcast by radio or television stations on sale: available to be bought in shops on second thought(s): completely changing your mind about sth, reconsidering sth 1. Red is used to signify danger because it stands out among g other colours. F 2. All emergency rescue teams were standing by to help take care of the survivors of the plane crash. It 3. Chris is too young to get married and settl e down . He's only l8! 4. Always stand up for your beliefs. 5. You're well enough to sit up bed. today, but don't get out of 1. These diaries are on sale everywhere. 2. I was planning to go to the party but on second thoughts I won't, as I have to wake up early in the morning. 3. Can you please be quiet? I'm speaking on the phone . 4. The workers of this factory are on strike ,demanding better working conditions. 5. There are too many commercials on television . It's so annoying when you're watching a good film. 6. We could always do the cooking for the party ourselves, but on the othe r hand/ it might be easier if we got a catering service on second thoughts to organise everything. 7. Did you really build this tree house on your own ? That's great! 8. What's wrong? You look like you have a lot on your mind . 9. I'm sure he didn't do it on purpose . It must have been an accident. on strike: refusing to work as a 10. I'm sorry but Mr Sullivan won't be able to help you. He's gone sign of protest abroad on holi day for two weeks. _________________________________________ page 123 CComplete using the correct form of the words in bold type. HOME SWEET HOME What will homes be like by the year 20S0? What improve me nt s will there be in the general standard of living? Forget about entering the house with a key. Admittance will only be possible with a personal card. It will be of no importance if you leave lights or heaters on when you go out. They will be automatical ly switched off. The safety of your house will not be a problem. Protection against fire and intruders will be guaranteed. f Doing the shopping, going to the bank, talking and seeing people on the other side of the world without leaving home will all be possible due to the existence of 21st century technology. Each home will have a central computer controlling all sorts of oractical devices that will make life easier and more comfortable. oComplete using the correct form of the words given. IMPROVE ADMIT PERSON IMPORTANT AUTOMATIC SAFE, PROTECT EXIST CENTRE, PRACTICE encourage (v): support (v): assist (v): aid (v): help (v): , t, save (v): rescue (v): defend (v): guard (v): e give sb the confidence they need in order to do sth (1) help, encourage (2) agree with or approve of sb's ideas or plans help sb finish their work or task (1) help or assist sb (2) provide a person, country or organisation with money, equipment or services they need make it easier for sb to do sth, assist help sb to avoid harm or to escape from a dangerous situation get sb out of an unpleasant or dangerous situation take action in order to protect or support sb or sth watch over in order to protect or not allow to escape manage (to) (v): (1) be responsible for a control (v): check (v): business or organisation (2) succeed in coping with difficulties have the power to manipulate sth or make important decisions about it examine sth to make sure that it is correct, accurate or of good quality 1. The parties in parliament are prepared to support the new tax laws. 2. My parents always encourage me to do my best. 3. The profits of the concert will go to _ aid__ the hungry ------'= in Africa. assisted/ 4. The nurse helped the doctor during the operation. 5. Could you help me get these curtains down? 6. There is an international campaign to _ save ---==-'-'''---_ the whale from extinction. 7. The firemen rescued ten people from the burning building. 8. The National Bank is guarded by the police 24 hours a day. defend 9. Will you _....:.=-'-=-'-'-=----_ your country in time of war? 10. A computer controls the automatic doors at the airport. 11. How did you manage to get this old car running again? 12. Did you check the quality of the material? units 17-21 Revision 05 I Grammar Practice A Choose the correct answers. 1. I'll be on holiday you receive this letter. a. just b. while @ by the time d. since 2. I bought these magazines have something to read on the trip. a. so that ®so as to c. for d. in order 3. My boss wanted to know whether the documents or not. a. had I sent b. if I sent c. if I had sent @ I had sent 4. " luggage is this?" "It's Karen's." a. What b. Which c. How much @ Whose 5. we arrived late, we didn't miss the speech. a. Despite b. In spite of @ Even though d. However 6. They suggested the archaeological site. a. that visit @ visiting c. to visit d. to visiting 7. We had food left over that we had to throw it away. a. such much b. so many c. so a lot of @ such a lot of 8. That's the artist paintings are very fashionable. @ whose b. which c. who d. 9. The manager of the shop, is a friend of mine, offered me a discount. a. which b. whose @ who d. whom 10. The man denied us before. a. to have seen b. that he has seen @ having seen d. not to have seen 11. Let's organise a surprise party for his birthday, ? a. don't we b. do we c. will we @) shall we 12. Can you tell me ? a howmuchdoes thissweatercost @ how much this sweater costs c. what does this sweatercost d. howthis sweatercosts 13. I'll always remember the place we went on holiday last year. a. which b. at where @) where d. to where 14. Our team didn't win despite very well. ®playing b. being played c. of playing d. they didn't play 15. No one asked for me while I was out, ? a. did he b. didn't he @ did they d. didn't they _________________________________________ page 12 5 BUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. "Do you have anything to declare?" asked the customs officer. us The customs officer asked us if we had anything to declare. 2. Rosie had lost a lot of weight, so I hardly recognised her. much Rosie had lost so much weight that I hardly recognised her. 3. You know, Mr Davidson was ill, so he couldn't go to work for a week. illness Mr Davidson couldn't go to work for a week because of/due to his illness , you know. 4. They live in a modern and spacious apartment. where The apartment where they live is modern and spacious. 5. I'll leave only after you apologise for what you said. soon I'll leave as soon as you apologise for what you said. 6. You know, although she was angry, she managed to speak calmly. spite You know, in spite of being angry/her anger , she managed to speak calmly. 7. "I'll inform you next Monday," Sally said to Mike. him Sally told Mike that she would inform him the following Monday. 8. Sally regrets not having entered the competition. wishes Sally wishes she had entered the competition. I Vocabulary Practice AChoose the correct answers. l. Don't use that machine. It's out of _ a. danger b. work c. control @ order 2. I'm here behalf of the workers. a. for b. in @ on d. at 3. This material is different the one I bought yesterday. a. for b. with c. of @ to 4. The shop assistant offered to the gift for me. a. fasten b. fold (0wrap d. tie 5. My parents bought two dogs to our house. a. defend b. support c. assist @ guard 6. The rock star gave only one when he was on tour. b. discussion c. debate d. dialogue 7. He was so startled by the dog that he the shopping bags he was carrying. a. spread b. flooded (f) dropped d. spilt 8. I've never been to a tropical island but I can how beautiful it must be. a. think b. suppose c. consider @ imagine 9. The school all the students to take an interest in the arts. b. regarded c. supported d. managed 10. When ironing, I like to put the clothes in neat _ a. packs eEl piles c. bunches d. heaps 11. How did you to stop little Lisa from crying? a. help b. control c. aid @ manage page 126 12. As I was going home, I that I had left my keys at the office. a. found out b. inspected @ discovered d. learnt 13. Whenever we go camping, we like to the area for interesting plants and animals. a. discover b. find out (S) explore d. learn 14. I need a of sugar from the supermarket. @ packet b. bundle c. package d. parcel 15. I John Westwood yesterday! I hadn 't seen him for ages! a. stood by eli) ran into c. ran along d. settled down B Complete using the correct form of the words in bold type. 1. Students are under considerable stress when studying for exams. CONSIDER 2. It may seem unbelievable , but many people believe that UFOs exist. BELIEVE 3. Admittance! to the concert is free for children under twelve. ADMIT Admission . . 4. There was a(n) misunderstanding and as a result we failed to meet last night. UNDERSTAND 5. Those papers are unimportant . Just throw them out. IMPORTANT 6. These dresses are Townsend's latest creation(s ) CREATE 7. Children have a lot of imagination IMAGINE 8. We've made some improvements to our house. IMPROVE C Choose the correct answers. It was in 776 BC in Olympia that the first recorded Olympic Games were held. The Ancient Greeks (1) _ the games (2) order to honour their gods. Thus, many religious ceromonies as well as sporting events took place during the Games. Taking part in the Games was considered a great honour, and athletes travelled long distances so (3) to participate. If the city states (4) at war, they did not cancel the Games. They simply (5) their differences until the Games were over. The Games were banned in 393 AD by Emperor Theodosius I, (6) disapproved of false gods and festivals . However, they were revived in 1896, by Baron Pierre de Coubertin, who (7) them as a representation of ideals that the modern world needed. He (8) that they symbolised the idea of cooperation between nations, honour, fairness , and high moral and physical standards. 1. a. set off 3.@as 5. a. put on 7. a. viewed (2) set up b. that b. put away b. supposed c. set out c. for C£) put aside c. imagined d. set in d. though d. put out (d) regarded 2.@in 4. a. are 6. a. which 8. a. says b.on b. had been b. whose ew said c. at (£) were c. whom c. has said d. for d. will be . @ who d. is saying • unit 22 Linking Words The linking words listed below join either main clauses or parts of the same sentence (not a main with a subordinate clause). Linking words and, both ...and, or, either...or, neither...nor too, not only ...but also, not only ...but...as well, as well as, besides, in addition to this, furthermore, what is more but, however, nevertheless, on the other hand, regardless of, yet, contrary to, in contrast to, in comparison to in fact, as a matter of fact, actually, indeed, to tell you the truth, strangely enough like, as, likewise, similarly, in the same way ~ like +- noun/pronoun/-ing form =similar to as + subject + verb =similar to ~ as + article + noun describes sb'sjob or the function of sth like, such as, for example, for instance, especially, particularly, in particular in other words, specifically, to be (more) specific, that is to say, I mean so, therefore, otherwise, thus, in this case, for this reason, under those circumstances, consequently, as a consequence, as a result but (for), except (for), apart from beginning: initially, first, first of all , at first, to begin/start with continuing: second, secondly, after this/that, afterwards, then, next concluding: finally, lastly, last but not least, in the end, eventually, to conclude, in conclusion regarding, considering, concerning, with respect/regard to, as for, as to tosummarise, to sum up, in summary, in . short, on the whole, (all) in all, altogether in my opinion/view, according to, personally Use • co-ordination • to give additional information • to express contrast • for emphasis • manner or companson • to give an example • to clari fy the meaning of a sentence • to express the results or the consequences of a situation • exception • to organise the text • for reference • to summarise • to give opinions Examples He is both lazy and irresponsible. Neither your parents nor your teachers would approve of such bad behaviour. As well as losing his job, he lost most ofhis friends. She cooks well but she hates washing up afterwards. She was not prepared for the test; however, she managed to pass it. To tell you the truth, I didn't know that he was leaving. We had a very good time, indeed. Exercising strengthens our body; likewise, eating more vegetables improves our health. He behaves like a real gentleman. We left everything as we found it. She works as a shop assistant. I used a folded blanket as a pillow. Electronic devices such as mobile phones and personal stereos should not be used during the flight. The company is facing financial difficulties; in other words, they cannot payoff their debts. Alex didn't sleep at all last night and consequently he feels very tired today. Apart from her mother-in-law, everyone liked Sarah's wedding dress. First you boil some salted water. Then you add the pasta and cookfor ten minutes. Finally you drain the pasta, add some butter and serve immediately with your favourite sauce and grated cheese. The government must take serious action with regard to the problem ofpollution. To summarise, this novel gives us a clear picture of life in the nineteenth century. According to most art critics, Guernica is a masterpiece ofmodern art. page 128 I Grammar Practice A Circle the correct answers. egardless of); As for what you may think and apart from I(contrary to) popular belief, pasta is not an Italian invention, however Chinese one. (To be more specifi01 In addition to this, legend has it that Marco Polo, the explorer, learnt the recipe for pasta from the or brought it to Italy. Pasta is the most important food in Italy. In short, it is served@1 like a starter to any meal. It is 0 0t I both popular in and also in other countries, where it is served with different sauces. Concerning I (Regarding) the sauces, there are so many that even the mo st fussy eaters are sure to find something c . they like. n a B Complete the sentences using the appropriate linking word from the box. otherwise not only.. .. but also neither.. .nor to conclude but for personally v either. ..01' in compari son to besides in this case however next b tl 1. I agree with you . Personally , I believe that anything you learn is useful. v 2. To conclude my talk, I'd just like to emphasise how important it is to recycle anything we can. II 3. I'd like to visit Spain with you, however I can't get the time off work. Sl 4. You had better pack tonight, otherwise you'll have too much to do in the morning. v 5. And next on the show with us tonight, we have Mike Sullivan! 6. I would have been in deep trouble but for my friend who is a lawyer. ir 7. This house is very small in comparison to ours. e: nn"litipc besides 1\/fi"h<lp] nor their exam. 10. They not only made the wedding cake but also the appetisers. 1 11. You weren't responsible for the accident. In t his case , the other person must pay for the damage to your car. 12. You can take either the blue bag or the green one. Not both! 2 C Choose the correct answers. ____ ( 1) hi storians , people were very 1. a. Specifically b. Concerning (S) According to 3 superstitious in the sixteenth and seventeenth centuries. (2) , people were terrified 2. <i) As a matter of fact b. In the same way c. On the other hand 4 of witches, and (3), thought they 3. a. as well as b. too @ fur thermore were (4) the devil. 4. a. likewise eN like c. similarly 5 ___ _ (5), witchcraft was considered to be 5. a. Nevertheless eli) Consequently c. However 6 one of the most serious crimes. (6), 6.Gi)Thus b. Otherwise c. Particularly anyone even suspected of being a witch was hunted down and (7) put to death by 7. a. secondly eli) afterwards c. last but not least hanging or by being burnt at the stake. 8' 71 - or r. d _________________________________________ page 129 _ _ _ _ (8) these facts, one would think that 8. a. With regard b. Altogether (S) Considering they had some proof that these women were (9) witches, and 9. a. to tell you the truth eEl indeed c. especially ___(10) they didn 't. 10. a. however eEl yet c. but ____ (11), there wasn't any real way of 11. a. As a result b. Otherwise 0 1n fact identifying a witch. (12) they made 12.G)For this reason b. In this case c. In other words lip ways of identifying them. (13), 13. a. Similarly b. Such as 0 For instance any natural marks (14) moles or 14. G) such as b. as for c. but for birthmarks, were thought to be "witch" marks. ____ (15), they used another terrible 15.G)What is more b. In addition to c. On the whole method of testing a "witch". They tied her up and (16) threw her into a river. 16. a. second (E) after that c. initially ____ (17), it was thought that the guilty 17. a. Therefore b. In conclusion (£)Strangely enough would float (because people (18) 18. a. both (E) actually c. besides believed that water rejected evil) (19) 19. G)and b. as c. otherwise theinnocent would drown. (20) those 20. a. Besides (E) As for c. Except who floated, they were later killed anyway. It wasn't until the late seventeenth century, as scientific knowledge increased, that belief in witchcraft (21) began to fade, and 21. (g) eventually b. lastly c. then the "witch laws" were (22) abolished 22. a. last but not least b. yet <£)finally in 1736. (23) the last English 23. a. To summarise (QWith regard to c. In the end execution, that was in Exeter in 1684. oUsing the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in totaL) 1. I must admit that I haven't read the report yet. tell To tell you the truth , I haven't read the report yet. 2. We are supposed to meet again in a week's time, which is next Thursday. say We are' supposed to meet again in a week's time, that is to say next Thursday. 3. You know, she's a good swimmer but she also plays tennis very skillfully. well You know, as well as being a good swimmer, she plays tennis very skillfully. 4. We could visit them or we could call them instead. either We could either visit or call them. 5. You should not only give up smoking but also follow a healthier diet. addition You should follow a healthier diet in addition to giving up smoking. 6. The article was not only interesting but also informative, you know. both The article was both interesting and informative , you know. 7. The truth is that he doesn't enjoy travelling very much. fact As a matter of fact , he doesn't enjoy travelling very much. 8. I had to repeat the exam because I failed it. consequence I failed the exam and as a consequence I had to repeat it. page 130 I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. take after: look like sb, resemble 1. The baby takes after his father. He's got the same blue take off: (1) leave the ground eyes. (aeroplane) (2) remove (clothes) 't 2. You shouldn • take on ... .. ..... .. take on: accept a job or responsibility take over: win control or management of sth you feel you won't be able to handle them. 3. The two brothers took over the company when their take up: begin or become interested in a father died. new hobby or activity 4. The plane had to make an emergency landing only a few minutes after it had taken off B Complete using prepositions. :- 1. She was angry with/at me for forgetting her birthday. 2. He shouted at me for no reason at all. 3. Will you forgive me for being so selfish? 4. You can't always blame everyone else for your mistakes. 5. They accused him of stealing the money from the counter. 6. He was charged with murder and had to appear in court the next day. 7. Kate apologised to us for being late . 8. I disagree witt, the government's policy concerning traffic regulations. 9. I'm having trouble with my car. Could you help me start it? 10. Three young men have been arrested for breaking into the building. 11. The football team put the blame on the referee for not winning the game. 12. It's no use arguing with them; their decision is final. _________________________________________ page 131 eblue es if heir CComplete using the correct form of the words in bold type. MAKING IT A BETTER PLACE TO LIVE At times, it seems that people have no sense of responsibility towards their environment. RESPONSE They have the tendency to carelessly drop their rubbish wherever they TEND, CARE happen to be, even when there is no shortage of rubbish bins. However, this must SHORT change. Littering doesn't only make a place look ugly, it also puts public health at risk and can endanger wildlife. The authorities need to become more informative about DANGER, INFORM how pollution affects our everyday lives, providing the community with a better education concerning the preservation of the environment. EDUCATE There is no quick or simple solution. One thing is certain, though. Fail ure to act FAIL now will in the long term mean a great loss . The choice is ours! LOSE, CHOOSE D Complete using the correct form of the words given. chew 1. Doctors say that we should always _ ~ . . : . . : . . = . . : . . : . . - _ our food bite (v): use your teeth to cut into sth sip (v) : drink sth slowly by taking a well before swallowing it. small quantity at a time 2. She gulped down her milk as she was late for school. chew (v): break up food in your mouth 3. Ouch! I bit my tongue by mistake. (using your teeth) in order to swallow it 4. The little boy swa llowed a coin accidentally and was gulp (v): eat or drink sth quickly by taken to hospital. swallowing large quantities swallow (v): cause sth to go from your 5. We sat there for over an hour while he just __ sipped ,-,-__ his mouth down into your stomach coffee without saying a word. meals food (n) : what people or animals eat meal (n) : the food you eat for breakfast, dish lunch or dinner food course (n): one part of a meal (starter-main course-dessert) dish (n) : food prepared in a particular 9. We were offered a three- course dinner. style or combination book (v): (a hotel room, ticket, lesson, 10. Diana booked her flight three weeks beforehand. etc.) reserve sth, arrange to 11. Could I reserve a table for two for Saturday evening, have or use it at a particular time please? reserve (v) : (a table, ticket, magazine, seat, etc.) arrange for it to be kept especially for you unit 23 Participles Participles as adjectives Present Participle (-ing) Past Participle (-ed) Present participles as adjectives have an active Past participles as adjectives have a passive meaning meaning and describe a person, thing or event. and describe a person's feelings or attitudes. He is a hard-working person. He looks exhausted. It was a very boring play. The audience was utterly bored. Everyone was fascinated by the film. The film was fascinating. Participles replacing clauses A. The present participle is used: Examples • to replace a clause of time introduced with when, while, as, after, before, etc. ~ for a lengthy action interrupted by a shorter Walking home, she was attacked by a dog. (As she was walking or sudden one. home, she was attacked by a dog.) ~ for an action taking place at the same time as I arrived at the examination centre feeling very nervous. (When I arrived at the examination centre, I was feeling very nervous.) another one. Opening the door, Ifound two letters on the floor. ~ for an action taking place immediately (As I opened the door, I found two letters on the floor.) before another one. • to replace a clause of manner. Reading books, he managed to improve his vocabulary. (He managed to improve his vocabulary by reading books.) • to replace a clause of reason introduced with Not wanting to miss the bus, they ran to the bus stop. (As they because, since, as, for. didn't want to miss the bus, they ran to the bus stop.) • to replace a relative clause in the active The girl talking to Jim is my sister. (The girl who is talking to Jim voice. is my sister.) B. The past participle is used: • instead of a subject + verb in the passive Shocked by the tragedy, they didn't know what to say. (They were voice. shocked by the tragedy and didn't know what to say.) • to replace a relative clause in the passive Clothes made in France and Italy are very elegant. (Clothes which VOIce. are made in France and Italy are very elegant.) • to replace a conditional sentence containing Stored in the fridge, the pudding will keep for up to one week. passive voice. (If it is stored in the fridge, the pudding will keep for up to one week.) c. The perfect participle is used for an action that happened before another one in the past. • Active voice: having + past participle Having finished cleaning up, she started cooking. (She finished cleaning up and then she started cooking.) • Passive voice: having been + past participle Having been seriously injured, the driver was rushed to hospital. (The driver had been seriously injured and was rushed to hospital.) • Participles are sometimes accompanied by when, while, before, after, if, though. He noticed the scratch while washing his cor. • If a participle is at the beginning of a sentence, its subject is the same as that of the main verb: Crossing the rood, I was nearly knocked down by a cor. But: Pushing the button, the lift moved up to the third floor. (Thiswould mean that the lift pushed the button.) • If the subject of the participle is different from the subject of the verb, it goes at the beginning of the sentence. Weather permitting, we may drive to the beach. _________________________________________ page 133 I Grammar Practice A Complete using adjectives ending in -;ng or -ed. 1. We found Egypt fascinating (fascinate). 2. Karen was surprised (surprise) by the news. 3. He was a loving (love) father to all his children. 4. We were amazed (amaze) to see so many birds. 5. I am very pleased (please) with my results. 6. The most annoying (annoy) thing was the heat. 7. The doctor is concerned (concern) about your health. 8. Fairy tales are enchanting (enchant). Don't you agree? 9. The film was very boring (bore). 10. The trip was great but exhausting (exhaust). B Complete using the present, the past or the perfect participle of the verbs in the brackets. 1. Making (make) the salad, I cut my finger. 2. Warned/Having been warned (warn) about the bad weather, they cancelled the fishing trip. 3. Reading/Having read (read) the book, I wrote down some notes. 4. Beaten (beat) well, the mixture will thicken. 5. Having polished (polish) his car, he then vacuumed it. 6. The man giving (give) the speech is my son . 7. Not fee ling (not feel) well , the boy left school early. 8. Surprised (surprise) by the event, we didn't know what to say. 9. Not knowing (not know) where to go, I asked for directions. 10. Trapped/Having been trapped (trap) in the car, they waited for help . 11. The dry cleaner ruined my coat while cleaning (clean) it. 12. The food eaten (eat) by the guests had been prepared by caterers. 13. The film, being (be) a great success, will be made into a film. 14. Only articles written (write) by students will appear in the school's newspaper. 15. Havingspent (spend) all my money, I asked my brother to lend me some. C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Don't forget to turnjoff the oven before you leave the house. leaving Don't forget to turn off the oven before leaving the house. 2. You know, after painting the flat, it looked new. been . You know, having been painted , the flat looked new. 3. The children's performance at the concert was very impressive. audience The aud ience was very impressed by the children's performance at the concert. 4. Well, we decided to walk to work because the bus drivers were on strike. being Well, the bus drivers being on strike, we decided to walk to work. 5. · If you look after it properly, the goldfish will live for at least two years . looked The goldfish will live for at least two years if looked after properly. page 134 _ 6. Unfortunately, I watched TV the whole afternoon and I didn't manage to finish my homework. spent Unfortunately, having spent the whole afternoon watching TV, I didn't manage to finish my homework. 7. Anyone who doesn't pass the test must sit it again. not Anyone not passing the test , must sit it again. 8. I found that working six days a week tired me. was Working six days a week was tiring for me. I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. 1. Don't forge.t to __ turn _ --=...;"'-- off __ turn down: (1) reject , refuse to accept sth (2) reduce the amount of before you go out. sound, heat etc. produced by 2. Guess who turned up at the party! a piece of equipment 3. The teacher told us to turn over the page and begin the turn off: switch off turn on: switch on next exercise. turn out: result in a particular way and 4. Thank you for your offer, but I'm afraid I'll have to have the degree of success turn it down indicated turn over: move sth so that the top part 5. It's dark, why haven't you turned on the lights yet ? is facing downwards 6. If I had known the cake would have turned out like turn up: (1) arrive unexpectedly (2) increase the amount of this, I never would have attempted to make it. sound, heat etc. produced by a piece of equipment B Choose the correct answers. 1. I'm experienced computer programming. @ in b. at c. about 2. There are quite a few people who suffer headaches. a. with @ from c. by 3. I don't think I could cope so much work. @ with b. for c. about 4. Kim believes that German cars are superior Japanese ones. ~ o b. from c. than 5. How did you succeed finding a job so soon? a. with b. about @ in 6. I have difficulty understanding Geometry. a. about @ in 7. John is clever __ making up stories. a. in b. with C£) at 8. Jane is really good painting. @ at b. for c. with 9. The president is capable cancelling the meeting. a. for b. with @ of 10. I'm hopeless SPOltS. a. In eli) at c. with _________________________________________ page 135 - CComplete using the correct form of the words in bold type. lu' t WEATHER PERMITTING The weather is an important topic of conversation for the British, but in 1995 CONVERSE they had more to talk about than usual. In com parison to other years, it was a COMPARE year with very unusual weather patterns. A rainy spring, the wettest ever RAIN recorded, the hottest summer and one of the coldest winters they had ever experienced. In fact, since the beginning of the 1970s, rainfall during storms has increased BEGIN dramaticall y all over the world . As a result, complaints about changing weather COMPLAIN conditions are common. But why are we having all these changes? Climatologists and scientists , after a lot of investigation , agree that SCIENCE, INVESTIGATE global warming is to blame for this. However, they are not all in agreement as to how this will affect us. Warnings given by some climatologists say that if we don 't WARN prepare for droughts and floods, we will face problems like starvation . Others STARVE say that winters will be warmer, so the growth of more crops in more places GROW will be possible. In any case, it seems that we should all be prepared to experience changes in the climate and learn to live with them. D Complete using the correct form of the words given. robbed 1. Many banks in this area have been _-----C.-=-=.:::...=..:=--_ rob (v) : steal money or property from sb kidnapped steal (v): take sth away without one million dollars ransom. permission or intention of stealing giving it back 3. The store detective saw the girls __--'---'-""'--_ kidnap (v): take sb away by force and cosmetics. hold them prisoner in order to demand sth from their family or the government 4. A burglar/thief broke into our house and stole our robber (n): person who steals from a bank, shop or vehicle using video and TV set. force or threats 5. The kidnapper told the police where they were thief (n): person who steals from sb holding the woman. else burglar (n]: person who enters a 6. The robber/thief pointed his gun at the cashier and building illegally, with the demanded all the money. intention of stealing 7. The car thief was caught while breaking into a kidnapper (n): criminal who kidnaps another person car. 8. Research investigation (n): the act of finding out the truth about an event end in divorce. search (n): attempt to find sb or sth by 9. The investigation into the plane crash showed that it carefully looking for them had been caused by computer failure. research (n): the act of studying or examining sth in order to 10. The search for the missing children continued find out facts about it throughout the night. ~ ~ . ~ unit Emphatic/Exclamatory 24 Structures - Inversion A. Emphatic Structures Emphatic structures are used to emphasise a part of the sentence. Statements • It is/was + ... + that/who(m) • That is/was + question word + subject + verb Sue gave Peter a watch for his birthday last week. ---+ That's why he was so upset. - It was Sue that gave Peter a watch for his birthday last week. • Question word + subject + verb + is/was - It was a watch that Sue gave Peter for his birthday last week. What her secret was is something that we'll never - It was Peter that Sue gave a watch to for his birthday last learn. week. • Subject + do/does/did + bare infinitive, in the - It wasfor his birthday that Sue gave Peter a watch last week. Present or Past Simple and Imperative. - It was last week that Sue gave Peter a watch for his birthday. She does eat cereal eve,)' morning. They did get a divorce eventually. Do come with us tonight! Questions • IslWas it + ... + that/who(m)... ? • IslWas that + question word + subject + verb...? Is it your car that is parked outside ? Is that why you don't want to see him again? Is it Angela that/whoim) you are going to invite? • Question word + is/was it that + subject + verb...? • Question word + ever, to express anger, admiration, Why is it that you are so absent-minded? concem, etc. Whatever happened to them? They're late. B. Exclamatory Structures Exclamatory structures express surprise, shock, fear, anger, admiration, etc. Structure Examples What + (alan) + (adjective) +noun What an interesting story! What beautiful houses! What bad behaviour! How + adjective/adverb (+ subject + verb) How beautiful she is! How tactfully they behave! How + adjective + alan + noun How fascinating a story! How + subject + verb How she sings! ...such + (alan) + (adjective) + noun This is such a big house! I've never heard such nonsense! ...so + adjective + alan + noun It was so generous an offer! ...so + adjective/adverb He is so polite! She speaks so calmly! negative question Isn't it funny? Isn't that a pity ? Here/There + verb + noun (inversion) Here comes the Prince of Wales. HerelThere + pronoun + verb There he goes! You + (adjective) + noun You (cruel) murderer! You lucky man! _________________________________________ page 137 C. Inversion • When some words or expressions (usually with a negative or a restrictive meaning) are at the beginning of a sentence, the sentence is formed like a question (the auxiliary is placed before the subject) . This is called inversion and is used for emphasis. Words and expressions Examples Never (before), Rarely, Seldom, Barely, Never in my life had [felt so embarrassed. Scarcely...when, Hardly (ever) ...when, Rarely does he use his credit card. No sooner.. .than No sooner had [ told him the news than everybody in the village knew it! Only Only when you see her will you realise how much she has changed. Not only....but also Only in an emergency should you dial 999. Not only did I lock the door, but I also secured the windows. Expressions with not: Not even once did she look in this direction. Not (even) once, Not often, Not until, etc. Not until I saw him in person did I realise how tall he was. Expressions with no : In no way is he to blame for what happened. On no account, Under no circumstances, By no Under no circumstances would he accept my proposal. means, At no time, In no way, Nowhere, etc. Little Little did he know about the surprise that awaited him. So + adjective/adverb So bad was the concert that we left during the intermission. ..•? Inversion is also used in the following structures: • after so and as to agree with affirmative statements. .? Julie speaks French and so do her parents. (=her parents do, too.) The actors performed brilliantly, as did the dancers. • after neither and nor to agree with negative statements. I don't like baseball. Neither does my brother. (=my brother doe sn't either.) • with should, were, had in condit ional sentences when if is om itted. Should you meet John, give him my best regards. Had there been a telephone nearby, I would have called the police. • in exclamatory sentences beg inning with Here/There when the subj ect is a noun (not a pronoun). Here comes the bus! But: Here it comes! Grammar Practice A Rewrite the sentences using the appropriate emphatic structure to emphasise the words in bold type. 1. We bought the farm last year. It was last year that we bought the farm . 2. He works sixteen hours a day . He does work sixteen hours a day. 3. Craig broke the window. It was the window that Craig broke. or What Craig broke was the window. 4. I bought the seat covers for my new car. It is/ was for my newcar that I bought the seat covers. 5. Is Tom going to buy the food ? Is it Tom that/who is going to buy the food? 6. Chris sold his car to Mary. It was Mary that Chris sold his car to . page 138 _ 7. Who took my CDs? Whoever took my CDs? or Who was it that took my CDs? 8. Is that your briefcase on the table? Is it your briefcase that is on the table? B Complete the sentences using exclamatory structures. 1. They are disciplined dogs. Aren't they disciplined dogs! How disciplined dogs they are!(disciplined the dogs are! What disciplined dogs! They are such disciplined dogs! 2. It was a pleasant surprise. How pleasant the surprise was!(pleasant a surprise! It was such a pleasant surprise!(was so pleasant a surprise! Wasn't it a pleasant surprise! What a pleasant surprise it was! 3. You are a rude person. What a rude person you are! You are such a rude person!/so rude (a person)! How rude (a person) you are! You rude person! 4. This is terrible weather. The weather is so terrible! How terrible the weather is! Isn't this terrible weather!(this weather terrible! What terrible weather this is ! C Choose the correct answers. 1. "I was having a shower when the water was cut off." ______! And I still had shampoo in my hair!" @ So was I b. So I was c. Nor was I 2. "Jane can read and write Italian." "Wendy . And she also speaks French." @ can too b. can so c. can't either 3. "We didn't watch the match last night. " "We _ a. did too ., didn't either c. so did 4. "We'll be visiting Mexico this Christmas." ______ Christine. You could go together." a. Neither will b. So does @ So will 5. "I only buy recycled paper." ______ Harry." @ So does b. Neither does c. So is _________________________________________ page 139 C Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. You should never use a lift immediately after an earthquake. account On no account should you use a lift immediately after an earthquake. 2. We had never listened to such an interesting speech. before Never before had we liste ned to such an interesting speech. 3. They wouldn't reject such an offer. means By no means would they reject such an offer. 4. Julie had just arrived when the lights went out. sooner No sooner had Julie arr ived than the lights went out. 5. I never received good marks in Maths at school. receive Not once did I receive good marks in Maths at school. 6. The waitress told me that the restaurant was about to close and I had scarcely started eating. when Hardly had I started eating when the waitress told me that the restaurant was about to close. 7. He can't leave the court until he has testified. can Not until he has testified can he leave the court. 8. You mustn't interrupt me during the meeting. no Under no circumstances must you interrupt me during the meeting. I Vocabulary Practice A Complete using the correct form of the phrasal verbs given. wash up: watch out: wear out: wash dishes and other kitchen utensils be careful become thin, weak or unsuitable for further use to be worn out: to be tired or bored of sth or sb work out: (1) find a solution to a problem (2) take part in physical exercise watch out 1. You must always _ - - - ' - ~ - - - ' - . = . . . _ for jellyfish when you swim there. work out 2. Could you explain this exercise to me? I just can't ~ ~ - = - = - = - _ the answer. 3. Jack, it's your turn to wash up tonight. 4. I'm always worn out when I get home from work. 6. This is the second pair of shoes you've worn out this month. B Complete using the prepositional phrases given. to one's amazement /surprise: surprised, usually by sth unexpected under arrest: held by the police (as a suspect for a crime) under control: controlled under the impression: believing that this is under pressure: without (a) doubt: without delay: without fail/success: without warning: the case pressured definitely true, undoubtedly immediately, as soon as possible successfully/ unsuccessfu lIy unexpectedly, without letting sb know in advance 1. Without (a) doubt , that's the best film I've ever seen. 2. For some reason, Louise was under the impression that we were going to a Chinese restaurant. 3. Some friends arrived without warning after midnight. 4. To my amazement! ,I passed the test. I thought that I had f '1 d i surprise at e It. 5. We participated in the competition, however without ....;..;...;c-'--__ any success 6. The firemen quickly got the fire unde r control 7. Send this package off without delay . It must get there today. 8. Jack is always under pres s ure before he goes on holiday. He wants to get things finished before he leaves. 9. The policeman told the thief that he was under arrest page 140 _ : ~ : : ~ C Complete using the correct form of the words in bold type. AND THEY'RE STILL STANDING... It is indeed quite an achievement that many ancient buildings are still standing, while a lot ACHIEVE of modern buildings collapse with the slightest movement of the earth. This seems MOVE unacceptable ,considering the advances in technology. As a result, engineers receive a lot ACCEPT of criticism , especially when lives are lost. CRITICISE One of the reasons why ancient buildings still stand is because they are conservative structures. The pyramids are a good example. Their huge weight is spread over a wide area, so WEIGH they cannot topple over. Today, engineers want to create new designs which have never been tested before, so they rely on computers for safety predictions. However, these may be incorrect or misleading and CORRECT could cause the destruction of the building in the future. DESTROY Prevention of disasters is something that engineers should pay more attention to. PREVENT, ATTEND This is sometimes difficult, as costs must be kept down . Perfection cannot always be PERFECT achieved, but safety should be their main priority. o Complete using the words given. 1. I enjoy sitting in the sunshine at outdoor cafes in spring. sunrise (n): when the sun first appears in the sky in the morning 2. I love big windows as they let in a lot of sun light sunset (n) : when the sun disappears from the 3. The length of a shadow depends on the time of day. sky in the evening sunshine (n): light and heat coming from the 4. People gather here in the evening to watch the sunset sun 5. We woke up very early in the morning to watch the sunlight (n): light coming from the sun during sunrise the day lie-:: '1' :""loll. III 1 I If": shade (n) : area protected from bright 6. In summer, it's advisable ': sit :n t he _ ----" shade :.c==.::o--_ sunlight shadow (n): dark shape on a surface caused by sth standing between the light and the surface 7. The climate in Greece is warm a n ~ dry. season (n) : one of the four main periods - each with typical weather 8. The weather forecast for tomorrow is fine and sunny. conditions - into which a year is 9.Myfavour:.o: rte season o - _ - - -- divided climate (n): general weather conditions that characterise a place weather (n): conditions of the atmosphere in one area at a particular time units 22-24 06 Revision I Grammar Practice A Choose the correct answers. 1. the room, I not iced it had been ren ovated. elY Entering b. Entered c. Having been entered 2. The weather was warm, he took some jumpers with him as well. a. on the other hand b. ther efore @ nevertheless 3. buying paint, I bought some paintbrushes. (i) In additi on to b. Furthermore c. As well 4. Jack won't come to the meeting and _ a. Betty won 't too ® neither will Betty c. nor won't Betty 5. ' by a snake, I wa s rushed to hospital. GV Bitten b. Having bitten c. Biting 6. What something nobody knows. a. are his plans is ®hi s plans are is c. are his pl ans that is 7. the facts, she must be guilty. a. In conclusion b. Indeed @ Considering 8. At no time _ _ __ the house. a. left they ®did they leave c. they left 9. The house needs painting, the bedrooms. a. according to b. with reg ard @ in particular 10. "I don 't like football ". a. Neither my sister does (JUNeither docs my sister c. My sister doesn't neither 11. Cars __. in Japan are very reliable. a. having manufactured b. have been manufactured c. manufacturing 12. It is the most film I've ever watched. a. bored 13. Not only _ a. didn' t I type 14. I don 't want to go; _ a. in other words a. when <h)than d. Having entering d. otherwise d. What is more d. Betty won 't neither d. Been bitten d. his plans are it is d. In my opinion d. they did leave d. in conclusion d. Nor doesn't my sister ({j)manufactured d. boredom ~ d d I type d. strangely enough d. while page 142 B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Chris, you 're interested in psychology, aren 't you? find Chris, you find psychology interesting , don't you? 2. In fact, both Mark and Lucy were against the idea. nor In fact, neithe r Mark nor Lucy liked the idea. 3. It was such a cold night last night! so It was so cold (a night) last night! 4. Did Kevin give you those flowers? gave Was it Kevin who/that gave you those flowers ? 5. Mary, who didn't want to be late, left the house an hour earlier. wanting Mary, not wanting to be late , left the house an hour earlier. 6. She had just left when her mother called. sooner No sooner had she left than her mother called. 7. Actually, I drank some coffee last night and I couldn't go to sleep until three in the morning. drunk Actually, having drunk some coffee last night, I couldn't go to sleep until three in the morning. 8. Both Angela and Brian like spaghetti, as far as I know. so Angela likes spaghetti and so does Brian , as far as I know. Vocabulary Practice A Choose the correct answers. 1. You must be crazy. You can't turn an offer like that. (bl down b. back c. out d. over 2. Could you help me with my Maths? I'm having a lot of difficulty solving these problems. a. at (]Vin c. for d. on 3. What do you mean you've out your shoes? You only bought them last month. a. wiped b. watched c. worked ® worn 4. The new manager is taking next month. a. up QYover c.on d. off 5. He attempted to the painting from the gallery but he was caught. a. rob (£) steal c. thief d. kidnap 6. The took the child and called his parents to demand a ransom. (bl kidnapper b. robber c. thief d. burglar 7. I gave the dog the bits of that were left over: a. dish b. course ~ f o o d d. meal 8. Recent has shown that margarine is healthier than butter. a. investigation (]Vresearch c. discover d. search 9. When I have a sore throat, I find it hard to _ a. chew (£) swallow c. SIp d. gulp 10. I like sitting on the beach watching the in the evenings, a. sunshine b. sunrise c. sunlight @ sunset 11. My favourite is summer because I love the sea and sun. a. climate b. place @ season d. weather _________________________________________ page 143 • 12. When he retired, he gardening. a. tried on b. took after <£) took up d. turned up 13. I'd like to a flight to London. a. reserve c. close d. keep 14. Sharon is good languages. She speaks French, German and Italian. a. with b. in c. for @)at 15. They accused me lying. @ of b. with c. for d. for BComplete using the corred form of the words in bold type. 1. John doesn't accept criticism easily. CRITICISE 2. According to recent scientific research, a glass of red wine every day is good for the heart. SCIENCE 3. The beginners will swim in the shallow pool. BEGIN 4. After the teacher's corrections , I rewrote the composition. CORRECT 5. The conditions are acce ptable . I'll sign the contract. ACCEPT 6. The experiment was a complete failure FAIL 7. Swimming across the Channel is a great achievement ACHIEVE 8. Select whatever you like. It's your choice CHOOSE CChoose the corred answers. (1) we are very close, my sister and I are so different! I think she (2) my father. (3) , they both love cooking. They cook together all the time, and I must say, they make some pretty good meals. I, (4) , am a horrible cook. I can't even cook spaghetti! My sister is also very neat, like my dad, (5) I'm very messy. No matter how hard I try, I can't seem to be as organized as her. Also, she is a very strong character and stands up for her beliefs. I'm quite shy and don 't really voice my opinion that often. (6) seeing us side by side, anyone would agree that we resemble each other. (7) , once you get to know us, you'll begin to wonder how it is we (8) so different! 4. a. likewise 7.@However b. Despite eli) on the other hand b. Furthermore c. However c. actually c. Otherwise d. Since d. Indeed d. Likewise 2. a. takes off 5.(i)while 8.@turned out takes after b. so b. turned on c. takes over c. even though c. turned off d. takes up d. whatever d. turned in 3. a. Like 6. a. Before b. Such as b. Though (S)For instance c. While d. Especially @ After Final FeE Test PART 1 For questions 1-12, read the below and decide which answer lA, B, C or D best fits each gap. Mark your answers on the separate answer sheet. . SUMMER HOLIDAYS DON'T MEAN RELAXATION Holidays, holidays, holidays! That's all you hear before summer begins. Everyone is busy planning and booking ahead. Many (1) to their break for months and are in a (2) of excitement for weeks before they leave. People have their cars serviced and go shopping to buy (3) clothes. I suppose it's logical, I (4) after a whole year of work, people want to relax and (5) _ themselves of some stress. However, I have my (6) about summer holidays. It's the time when people vacate the city and go to summer resorts (7) find that everyone else has done the same thing. Places are very crowded. You go to restaurants where you have to (8) to be served, the room you had booked is . next to a nightclub and (9) is expensive. (10) you finally get back, you feel so tired that you need another holiday to get (11) the one you just had. I sometimes wonder if going on holiday is worth all that preparation and (12) ' ANSWER SHEET 1 A look forward B expect C anticipate D wait ITJA B C DI I!!!!!!!!!!! c::=::::J c::=::::J c:::=J 2 A situation B circumstance estate D position 0A B C DI c::=::::J c::=::::J .- c:::=J 3 A correct B relevant C right D appropriate O]A B C DI c::=::::J c::=::::J c::=::::J I!!!!!!!!!! 4 A say B mean C express D remark 5 A relieve B take off C remove D shake off 0 A B C DI I!!!!!!!!!!! c::=::::J c::=::::J c:::=J 6 A uncertainties B hesitations C dilemmas D doubts [£]A B C DI c::=::::J c::=::::J c::=::::J I!!!!!!!!!! 7 A only to B such as C so that D even though [2] A B C DI I!!!!!!!!!!! c::=::::J c::=::::J c:::=J 8 A insist on B call for C demand D command [IJA B C DI c::=::::J c::=::::J I!!!!!!!!!!! c:::=J 9 A whole B everything C entire D total [2] A BC DI c::=::::J I!!!!!!!!!!! c:::::J c:::=J 10 A Until B While C As D When C DI B c::=::::J c::=::::J c::=::::J I!!!!!!!!!! 11 A over B by C off D out of @] A B C DI I!!!!!!!!!!! c::=::::J c::=::::J c:::=J 12 A annoyance B problem C inconvenience D disturbance @]A DI B C c::=::::J c::=::::J I!!!!!!!!!!! c:::=J _________________________________________ page 145 PART 2 For questions 13-24, read the text below and think of the word which best fits each gap. Use only one word in each gap. Write your answers in capital lefters on the separate answer sheet. THE LIFE CYCLE OF THE EMPEROR PENGUIN The Emperor Penguin is the largest penguin, standing over one metre tall. Its life cycle is something extraordinary and rather different (13) that of other animals . The Antarctic summer (Dec-Feb) is the time when the Emperor Penguins have a "holiday" and they feed in the sea. During the month of March, they set off for their long journey south to the place where they breed and lay their eggs. As the long, dark winter arrives, each female lays one egg directly on the ice. The male immediately lifts the egg off the ice onto his feet. He (14) pushes it under his stomach for warmth. The female has completed her task and can now return to the sea to feed, leaving the male with the egg. For over two months, (15) the males huddle together (16) keep warm. (17) other animal except for the penguin can survive in temperatures of -70°C. The chick will hatch during July. That's (18) the female returns bringing food for her chick. By that time the male penguin will have lost about half his body weight, because he won't have eaten (19) for five months. As (20) as the female returns, the male leaves in search of food. For the next six months, both parents take turns looking (21) the chick. (22) the beginning e of the following summer, the (23) family goes to the sea. The adults can at last have a two-month break before (24) cycle begins again. DO NOT ANSWER SHEET WRITE HERE to/from ~ Idbl ~ then I d ~ 1 all ~ Idbl to ~ Idbl @] No Idbl when ~ Idbl anything ~ Idbl soon ~ Idbl after ~ Idbl §] At I d ~ 1 whole §] Idbl another/a/the ~ I d ~ 1 page 146 PART 3 For questions 25-34, read the text below. Use the word given in capitals at the end of each line to form a word that fits in the gap in the same line. Write your answers in capital letters on the separate answer sheet. MAGAZINES Magazines are big business. A large (25) of the population buy them (26) . In fact, some people even get their magazines brought to their home by a (27) service. For others, magazines are an (28) and they even collect them. But magazines are not to my (29) . They have ads promising a (30) appearance with the use of certain products. They also print (31) and unreliable information. Apart from that, they fill their pages with photos of (32) clothes. What a waste of money! I admit that I'll (33) buy one when going on a trip, but short novels or comics are always (34) , as far as I'm concerned. DO NOT ANSWER SHEET WRITE HERE ~ majority Idbl ~ regularly Idbl @] delivery Idbl ~ obsession Idbl ~ liking Idbl ~ desirabl e Idbl [ill inaccurate Idbl @J fashionabl e Idbl ~ occasiona lly Id 3 c:=J 1 ~ preferable Idbl MAJOR REGULAR DELIVER OBSESS LIKE DESIRE ACCURATE FASHION OCCASION PREFER _________________________________________ page 147. "Did you go to the swimming pool yesterday?" Macey asked me. DO NOT ANSWER SHEET WRlTEHERE whether Macey asked to the swimming pool the me whether I had gone 35 0 1 2 1 c::=:::J c::=:::J c::=:::J 1 ~ previous day. 36. He didn't say anything although he was dissati sfied with the service at the hotel. spite He didn't say anything with the service at the hotel. 36 in spite of bein g dissatisli edl his dissati sfaction 36 0 c::=:::J 1 2 c::=:::J c::=:::J 37. I can't stand people interrupting me when I'm studying. rather I'd me when I'm studying. 37 rather pcolc didn 't interrupt 37 0 1 2 c::=:::J c::=:::J c::=:::J 38. We must return the books to the library by Wednesday. taken The books to the library by Wednesday. 39. The house will need painting before we move in. have We'll need before we move in. 40. Mike, I'd like to know the name of the hotel you stayed at. which Mike, at? 41. Look, if she goes to the shopping centre by bus, she' ll be there in ten minutes. take Look, ten minutes to go to the shopping centre by bus. 42. They didn't let us feed the animals at the zoo. allowed We the animals at the zoo. must be taken (hack) 38 0 1 2 1 c::=:::J c::=:::J c::=:::J I ~ ~ to ha ve the house painted 39 ~ e:::b b l 1 §] which hot el did you stay 140 0 1 2 I c::=:::J c::=:::J c::=:::J it will take her @] 41 ~ e:::b b l 1 @] weren't allowed to feed 42 0 1 2 1 c::=:::J c::=:::J c::=:::J I Final ECCE Test I Grammar 1. All applications for the job must in by Friday. a. send b. have sent @ be sent d. have been sent 2. Amy finally got her money problems. a. out of b. around @ over d. away 3. The woman daughter was kidnapped lives next to me. a. who b. who's c. whom @)whose 4. "Are you still going to the party on Friday?" "Yes, something else comes up." @)unless b. in case c. as long as d. supposing 5. He is really interested studying art. a. of b. for c. about @) in 6. Martha, I never knew you were cook! a. a such good @ such a good c. so good d. a so good 7. Do you mind walking me my car? @ to b. in c. at d. until 8. Mom, it's time you that I'm not a little girl anymore. a. be realizing b. are realizing @) realized d. will realize 9. "I'd really like to travel to Africa one day." "You that for years. Why don't you just do it?" a. are saying b. were saying c. say @ have been saying 10. She wondered why _ a. was I crying b. I am crying @ I was crying d. am I crying 11. How long French? a. are you learning @ have you been learning c. do you learn d. have you learned 12. "Is this restaurant always so busy?" "No. Rarely so busy." a. this place being @ is this place c. this place is d. does this place 13. Mike, it's March 1st -the rent is today. a. due until b. due for c. due to @) due 14. The new cinema is Northern Ave. a. at @ on c. under d. of _________________________________________ page 149 15. My parents are quite strict-they never let me _____ out late. @)stay b. to stay c. staying d. having stayed 16. "Where's Grandma?" "She's in the garden the plants." @ watering b. to watering c. to water d. for watering 17. John and Amy have a beautiful daughter. a. two-years-old b. two-year-olds @ two-year-old d. two-years-olds 18. The hotel is close by, but quite cheap, too. a. in addition b. as well as @ not only d. also 19. I don't think there's point in apologizing now. a. little b. such c. very @ any 20. Even though they live nearby, I visit them. a. not ever @ hardly ever c. hardly never d. had never 21. It was book that I couldn't put it down. a. such interesting b. so interesting @ such an interesting d. so interesting a 22. I'm really tired " you talking down to me. @)of b. in c. at d. for 23. "Did you paint the house by yourself?" "No, I professionally." a. have done it b. had done it @ had it done d. got done 24 . can use the pool. You don't have to be a member. @) Anyone b. Every c. Someone d. Each one 25 . who told me about the party on Saturday. a. Alice b. Alice was c. She was Alice @) It was Alice 26. Anne, I wish you drive like a crazy person! a. couldn't @ wouldn ' t c. could d. mustn't 27. Robert be in his room. He left an hour ago. a. mustn't @ can' t c. shouldn't d. might not 28. I don't really know that machine. a. to operate b. operating c. how is operating @) how to operate 29. you follow the directions, you won't have any problem. a. As soon as b. As much as @ As long as d. As though page 150 30. not an easy language to learn. 33. Hurry up! The plane in one hour! a. The Japanese @) leaves b. The Japanese is b. had left c. Japanese are c. would have left @).Japanese is d. has left 31. Why don't you pay attention! You things 34. Let's go to the movies tonight, ? up! a. aren't we a. constantly messed b. don't we (!Dare constantly messing c. won't we c. have constantly messed @) shall we d. constantly messing 35. Twenty minutes of exercise a day stay in 32. Maria decided to have her hair blond. shape. a. dye @) is all you need to @ dyed b. that is need for c. dying c. which is in need of d. to dye d. of which is needed to I Vocabulary 36. My mother always seems about my health. @)concerned b. contained c. involved d.caring 37. This knife is too for me to cut my steak. a. broad b. sharp c. round @) blunt 38. exams is always very stressful for me. a. Giving @ Taking c. Making d. Setting 39. It's a police officer's job to the law. a. ban (li)enforce c. keep d. obey 40. It's not in my best to listen to everything he says. a. advice b. plan @ interest d. wish 41. He took a breath before he dove into the water. a. wide b. strong c. large @ deep 42. The spaghetti you made looks delicious! a. fully b. nicely @ absolutely d. interestingly 43. He was disqualified and unable to in the race. a. oppose b. complete @ compete d. enter _________________________________________ page 15 1 44. Josh can't be serious about moving to 51. She that I go with her to the movies. Africa. a. assisted a. definitely b. persisted b. fairly @ insisted c. simply d. resisted @ possibly 52. I wasn't able to that lecture on Sunday. 45. There were several kidnapping reported a. enroll in the neighborhood. ® attend a. events c. advise ® incidents d. accept c. tragedies n d. news 53. The crime has risen drastically over the past few years. 46. I need you to some cheese for the a. scene macaroni, please. ® rate a. chop c. measure @ grate d. percent c. boil d. peel 54. I knew my sister was in big from the way my mom looked at her. 47. Can you please keep an on my son for a a. problem second? b. difficulty @ eye @ trouble b. arm d. shock c. alarm d. ear 55. Can you please give me a(n) with my shopping bags? 48. An aspirin will definitely help your a. lift headache. b. ride a. fight @ hand b. relax d. arm @ relieve d. recover 56. I can't what it must be like to be so poor. G) imagine 49. I'm starting to feel like my boyfriend is taking me for b. expect c. remember @ granted d. think b. sure c. certain 57. Many different kinds of food sold today have d. definite _____ flavouring added to them. a. fake 50. Alice to have met Johnny Depp in person. b. wrong a. regards @ artificial @ claims d. false c. says d. considers page 152 58. Anne James a happy birthday at his party. a. told CW wished c. offered d. wanted 59. The teacher told the students to their hands before speaking. a. stretch b. apply @ raise d. give 60. He had changed so much, I recognized him. a. never @ barely c. obviously d. virtually 61. I'm not really that with the new software program. a. aware ~ a m i l i a r c. capable d. able 62. I'm afraid the concert will be _ until further notice. @ postponed b. cancelled c. held d. given 63. This room is so ! Can we open a window? a. dirty b. chilly (£) stuffy d. misty 64. In an effort to the ice, she tried telling a joke. a. crack ® break c. melt d. crush 65. His table are horrible! He eats like a pig! a. behaviours b. moods @ manners d. actions 66. The reporter told the celebrity that the interview was offthe _ a. plan b. file @ record d. agenda 67. Her glasses broke when she them on the floor. @ dropped b. spilled c. collapsed d. removed 68. I asked my father if he could give me a to the train station. a.drive b. travel c. pick @ lift 69. She gave a excuse for being late to work. a. risky b. invalid c. useless @ lousy 70. Who's in of this project? a. responsibility @ charge c.head d. direction Dictionary A abbreviation (n): a shortened word or phrase abnor mal (adj): not normal abolish (v): forma lly put an end to sth absent-minde d (adj): forge tful, not paying proper attention to sth accommodation (n): buildings or rooms where people stay accompany (v): go somewhere with sb accomplish (v): succeed in doing sth accordingly (adv) : in agreement with sth, therefore accounts (n): detailed records of all the money received or spent accountant (n): sb whose job is to keep financial records accumulate (v): gather together in an increasing quantity, collect accur ate (adj ): precise, correc t to a very detailed level accustomed to sth (adj): used to sth ache (n): physical pain or discomfort caused by injury or illness achieve (v): succeed in doing sth acknowledge (v): accept or admit that sth exists or is true acquir e (v): get, gain possession of sth actually (adv): in fact adaptable (adj) : adj ustable, changeable additive (n): a subs tance added to food for colouring, flavouring or to make it last longer adequate (adj): enough, sufficient admiration (n): feeling of liki ng and respect for sb or sth adopt (v): start having a new attitude or plan ads (n): advert isement s advance (n): progress, development advisable (adj) : sensible, correct affect (v): influence, cause sb or sth to change in some way affection (n): liking or being fond of someone aller gic reaction (n): becoming ill or getting a rash when you eat, smell or touch sth alternative (adj): other alte rnative (n): possibility of choice between two things amateur (n): sb who does sth as a hobby, not as a job amazement (n): surprise, astonishment ambition (n): wanting very much to do or achieve sth amusement (n): sth you find pleasant or funny (game, pastime etc.) animal rights (n): the belief that ani mals should not be exploited or abused by humans animation (n): films in which drawings or puppets appear to move anniversary (n): the date on which sth special happen ed in some previous year annual (adj) : once a year anthem (n): a forma l song or reli gious hymn written for a spec ial occasion anticipate (v): awai t sth, be prepared for sth to happen apparently (adv) : clea rly, obvi ously appetiser (n): food served at the beginning of a meal, starter appetite (n): desire to eat applaud (v): clap your hands to show approval approach (v): (I ) get closer to sb/ sth (2) deal with a task or problem approval (n) : approv ing of sth, believi ng that it is acceptable approve (v) : like, admire sb or sth approximately (adv): almost, nearly, roughly arch (n): a curved line arrangement (n): plan, preparation for sth arrow (n) : a long thin weapon which is sharp and point ed at the end artistic (adj): good at drawing, painting etc. ash (n): what is left after sth has burnt ashtray (n): a small dish for cigarette ashes assure (v): make sb certain that sth will happen astonish (v) : surprise very much attack (v) : try to hurt or damage sb or sth using violence attempt (v): try, make an effort to do sth attendance (n): being present or regul arly going to a place attitude (n): point of view, approach, opinion, behaviour audience (n): group of people watching or listening to a play, concert, film, etc. autobiography (n) : an accou nt of your life, which you wri te your self availabl e (adj ): that can be found, obtain ed or used await (v) : wait for sth, expect sth award (n): a prize aware (adj) : knowing sth B balanced (adj): having all its diffe rent par ts in correct proportions ban (v) : state offi cially that sth must not be done, shown or used barely (adv): hardly, only j ust, scarcely barn (n): a building on a farm where crops or ani mal food are kept basement (n): a floor of a buil ding built below ground level bazaar (n): sale organised to raise money for charity beforehand (adj): in advance, earlier than sth else bin (n): a container for putting rubbi sh in binding (n): anything that wraps around sth birtbmark (n): a mark on your body that you have since you were born bit (n): small piece blame (v): believe that sb or sth is responsible for sth bad bleach (n): a chemical used for whiteni ng clothes and killing germs bleed (v): lose blood as a result of injury or illness blood pressure (n): the force at which blood flows around your body bloom (v): when the flowe r bud opens board (n): a group of people managing a company or organisation bolt (n): flash of light ning seen as a white line in the sky bound (adj) : tied up securely bravery (n) : brave behaviour, being brave break out (phr v): begin suddenly (war, fire, etc.) breaktbrough (n) : significant developme nt or progres s breath (n): the air you take into and let out of your lungs when you breathe breathalyser (n): a bag or elect ronic device used by the police to test whether a driver has drunk too much alcohol breed (v) : when animals reproduce bright (adj) : strong and notice able, not dark brilliant (adj): very smart, intelli gent broadcast (v): transmit on radio or television broccoli (n): a type of vegetable, green in colour bump into (phr v): meet or come across by chance burden (n): causing you a lot of difficulty or worry by means of (pp) : by way of by nature (pp): having a characteristic or qualit y as P31t of your character C ca lcium (n) : a white minera l found in bones and teeth calmly (adv) : quietl y, peacefully campaign (n): planned set of acti vities car ried out in order to achieve an aim ca ncel (v) : prevent sth arranged from happen ing candidate (n): a person considered for a position or taking an examination capsule (n): a small container with a drug or ot her substance inside it, used page 154 for medic al or scientific purposes cardboard (n): thick, stiff paper used for making boxes chick (n): a baby bird conventional (adj): ordinary, normal cardigan (n): a woollen jumper which is open in the front and can be fastened with buttons carving (n): an object which has been cut out of wood, stone, etc. cauliflower (n): a type of vegetable, white in colour ceremony (n): a formal event , usuall y religiou s chain (n): rings (usually of metal) linked together in a line chairman (n): a person in charge of a committee or organisation challenge (v): invite sb to fight or compete with you in some way challenging (adj): requirin g great effort and determination chapel (n): a small church charge (v): ask sb to pay money for sth that they have bought or for a service charity (n): an organisation which raises money to help people charm (n): sth believed to have magic powers chase (v): to run after sb in order to catch them cheer up (phr v): become more cheerful chickenpox (n): a disease that gives you high temperature and red itchy spots chop (n): a slice of lamb or pork, usually including a rib circumstance (n): situation, condit ion city-state (n): ancient state consisting of a city and smaller towns depend ent on it claim (v): say that sth is true clarify (v): make sth easier to underst and clink (v): make a light sharp ringing sound closet (n): wardr obe coach (n): trainer collapse (v): fall down suddenly colloquial (adj): informal speech combination (n): a mixture of things or qualit ies combine (v): join together, blend, mix comforting (adj) : making you feel less worri ed or unhappy command (n): order comment (v): express your opinion about sth or give an explanation for it commentary (n): a description of an event broadca st on radio or televi sion while the event is taking place commercial (adj) : related to buying or selling goods committee (n): a group of people who meet to make decisions for the organi sation they represent community (n): all the people living in an area compete (v): take part in a game , conte st or fight complete (adj) : containing all the parts sth should contain complexion (n): the colour and general condition of a person's skin complicated (adj): not simple compulsive (adj) : obsessive, not able to stop doing sth wrong or harmful concentrate (v): focus your attent ion on sth, consider sth closely concern (n): worrying about a situation conclude (v): end sth, draw a conclusion about it conference (n): a meet ing at which formal discussi ons take place confide (v): trust sb and tell them your secrets confirmation (n): proof, knowin g that sth is definite conflict (n): seri ous disagreement or argument about sth import ant conformist (adj): behavi ng or thinking like everybody else confront (v): deal with sth, face conscious (adj): awake, alert, aware of sth consciousness (n): being awake or alert conservative (adj): not wi lling to accept change constantly (adv): always, continually construction (n): buildi ng of houses, factories, roads etc. consult (v): ask for specia lised advice consume (v): eat, drink or use up sth consumer (n): a person who buys things or uses services contact (vj.get in touch with sb container (n): anything that can be used for putting things into it (e.g. a box) content (adj) : fairly happy or satisfied content(s) (n): anything that is inside of sth else contract (n): legal agreement , usually invol ving money contrast (n): clear difference between two or more things contribution (n): a sum of money you give in order to help pay for sth convenient (adj) : easy, useful for a part icular purpose converse (v): talk to someone convince (v): persuade, make sb believe sth co-ordination (n): organising the activities of groups so that they work together efficiently corporation (n) : large business or comp any cosmetics (n): substances (e.g. lipstick, powder ) which peopl e use on their face or body in order to look more att ractive cottage (n): a house in the country create (v): invent, design or make sth new credit card (n): a card which allows you to buy goods on credit crisps (n): baked slices of pot ato sold in packets criterion (n): a standard by which sth can be judged criticise (v): express di sapproval of stb or say what is wrong with it crooked (adj) : bent, twisted crops (n): plants (e.g. wheat, potatoes) grown in large quantities crowning (n): placing a crown on one's head cube (n): an obj ect with six square surfaces which are all the same size culture (n): civilisation , customs, life styie custard tart : a sweet dessert D dare (v): have enough courage to do sth dart (n): a small narrow object with a sharp point which can be thrown or shot deal with (phr. v): solve a problem or make a decision about a situation deceive (v): make sb believe sth that is not true in order to gain sth yourself declare (v): (1) state officially (2) say what goods you have bought from abroad in order to pay the right tax deduction (n): drawin g a conclu sion about sth defeat (v): beat your opponent in a battle, game or contest deficiency (n): lack, shortage, not having enough of sth dehydrated (adj) : when the body doesn 't have enough water delivery (n): carrying sth to a destination demolish (v): destroy a buildi ng completely demonstration (n): a march or gathering in which people take part in order to show their opposition to or support for sth deodoriser (n): sth that can hide or remove unpleasant smells depend on (v): rely on deprive (v): prevent sb from having or enjoying sth depth (n): how deep sth is (downwards, backwards, or inwards) desperate (adj): being in such a bad situation that you would try anything to change it detached house (n): not j oined to any other house determination (n): not willing to change your mind about sth you have decided to do devastated (adj ): shocked and very upset by sth device (n): a piece of machinery or a speci al tool used for a particul ar purpose diabetic (n): a person who suffers from diabetes (having too much sugar in their blood ) dialect (n): a form of a language spoken in a particul ar area dictate (v): say or read sth aloud, so that __________________________________________• page 155 others can write it down th digest (v): when the body processes the food we eat sth digital (adj ): systems recording or transmitting information in the form of thousands of very small signals es) dim (adj): not bright, not easy to see dim (v): make or become less bright ne' s direct (v) : control the product ion of a film dirt (n): dust , mud or stain on sth disapprove of sth (v) : not like, not agree e- with or approve of sth disaster (n): a terri ble accident or misfortune discipline (n): obeyi ng laws or rules, worki ng in a controlle d way sth disconnected (adj): not connected or a joined , cut off shot discovery (n): learn ing sth that was not known before disheartening (adj) : dis appointing is dissatisfaction (n): not being satisfied or pleased with sth distant (adj): far away in space or time road distract (v): draw sb's attention away from sth distress (n): a state of extreme suffering or pain distribute (v): hand out or deliver thi ngs to a number of people ving divorce (n): a formal ending of a marriage by law downwards (adv): towards the ground or a lower level ation drain (v): remove any liquid from food, especially after it has been cooked drawback (n): disadvantage ring drought (n): long period of time duri ng which no rain falls 'or drown (v) : die in water due to lack of oxyge n E earplugs (n): small pieces of soft or material which are put into your ear to protect you from noi se or wat er rds, earthquake (n): shaki ng of the ground, usuall y causing destruct ion eating grounds (n): fie lds where to animals can feed eccentric (adj) : sb whose habits or y opinions are differ ent from those of most peopl e ange economise (v) : save up d effective (adj): working well and producing the desired results effort (n): trying hard to do sth election (n): voting in order to choose a person or gro up of people for an offi ci al posi tion elegant (adj) : stylish in appearance and graceful in movement eliminate (v) : remove sth completely, get rid of emblem (n): a design that has been that chosen as a symbol of a country or organisati on embroider (v) : sew a decorative design on a piece of clot h emergency (n): an unexpected difficult or dangero us situation demanding immedi ate act ion emotion (n) : a pers on ' s feelings emperor (n): a man who rul es an empire en able (v) : make it possible for s b to do sth enchanting (adj ): causi ng feelings of del ight or pleasur e encounter (v): come across, meet, experience engaged (telephone line) (adj) : busy, so that you cannot speak to the pers on you are trying to call engagement (n): an arra ngement that sb has made to do sth enthuse (v) : make sb fee l excited or enth usiasti c entire (adj) : whole, complete equip (v) : gi ve sb or sth the tools or the skill they need for a particul ar purpose erode (v) : crack and break, becoming gradually destr oyed escapologist (n) : sb who ent ert ains audiences by escaping from difficult situa tions essay (n): composition establish (v): set up sth evacuate (v) : move people out of a place when in danger eventually (adv): finall y, in the end, after all evidence (n): proof, any thing that causes you to beli eve that sth is true exce ssive (adj): more than necessary execution (v) : killing sb as a punishme nt for a serious cr ime exhausted (v) : tired either physicall y or mentall y expedition (n): an organised journey made for a spec ific purpose (e.g. explorat ion) extinction (n) : the death of all the remaining living me mbers of a species extinguish (v) : put out a fire extraordinary (adj): special, unusual extreme (adj ): great, maximum, very int ense eye shadow (n): make-up for the eyes eyelash (n) : hair gr owing on the upper and lower eyelids eyesi ght (n) : the ability to see eyewitness (n) : sb who was present at an event and can describe what happened F fabric (n): cloth, material fade (v): grad ually become unnoti ced or unimport ant failure (n) : (1) lack of success in sth (2) when sth goes wrong or stops working fairness (n): bei ng reasonable, right and ju st familiarise (v): learn about sth and st art to under stand it fancy (v) : want to have or to do sth fascinated (adj) : charmed, finding sth very interesting and attractive feature-length film (n): a full- length film abo ut a fictional si tuation feeder (n) : a container filled with food for birds or ani mals fello w (n): colleague, person wit h whom you have st h in com mon fence (n): a wooden or metal barrier bet ween two places filthy (adj) : very dirt y financial (adj): relat ed to or invo lving money fire escape (n) : emergency exi t from a building fireproof (adj): sth that won' t catch fire firewood (n) : wood cut into pieces so that it can be burned on a fire firml y (adv): strongly first-aid kit (n): a box containing anything that can be used in medical emergenci es fit (v) : install fi x (v): repair, mend flavour (n): the tast e of a foo d or drink flee (v) : escape, run away from sb or sth fli ght attendant (n): member of the crew of an aero plane, whose job is to look after the pass engers flo at (v) : lie above or j ust below the surface of a liquid flood (n): an overflow of wat er, usuall y due to heavy rai ns floorboards (n) : pieces of timber used to cover floors flo ss (n): soft, very thin pieces of thread used for cleaning between the teeth fluent (adj) : speaki ng a language easil y and correctly flute (n) : a musical ins trument foot step (n): the sou nd of sb walki ng each time their foot touches the ground foreman (n) : an experienced person who supervises other workers fortunate (adj): lucky fortune (n) : luck, what wi ll happen to you in the future foundation (n): an organisation set up for a particular purpose founder (n): the person who started an institution or organisat ion frame (n): a structure that gives shape and support to sth frustrate (v) : upset , make sb angry full-length (adj) : having the complete length function (v) : work, opera te fund (n): amount of money coll ected or saved for a part icular pur pose furthermore (adv): moreover, additi onall y fussy (adj) : very concerned with unimportant details page 156 G garbage (n): rubbish, especially waste from a kitchen garlic (n): small round white bulb of a plant like an onion, with a very strong taste and smell gather (v): come together in a group generate (v): cause sth to begin and develop genuine (adj) : original, authentic, real global (adj): sth that happens in all parts of the world glove (n): piece of clothing which covers your hands and wris ts go off (phr v): (1) make a sudden loud noise (2) become stale, sour or rotten (food, drink, etc.) gold-tipped (adj): the pointed end of sth which is cove red in gold goose (n): a large bird like a duck gossip (n): informal conver sation, often about other peopl e' s privat e affairs goulash (n): a traditional Hungarian dish gradual (adj): occurring in small stages over a long period of time graduate (n): sb who has been awarded a degree at university or college grotesque (adj) : unnatural, unpleasant or out of proportion guarantee (v): make certai n sth will happen guidance (n): help and advice, especially sb older or more experienced than you guilty (adj): unhappy because you have done or think you have done sth wrong or bad gums (n): firm pink flesh inside the mouth, out of which the teeth grow H habitual (adj ): sth done usually or often, typical, characteri stic handicapped (adj): having a physical or mental disability handlebar (n): upper front part of a bicycle for holding and steering hang ar ound (phr v): spend time somewhere or with sb harbour (n): area of the sea at the coast, partly enclosed by land or strong walls and safe for boats harm (v): cause physical injury to sb, usually on purpose harmless (adj) : not dangerous, safe haste (v): act quickl y hatch (v): when an ani mal comes out of its egg by breaking the shell heat er (n): a device used to keep sb or an area warm herb (n): a plant whose leaves are used in cooki ng to add flavour herd (n): a group of animals of one kind that live together hesitate (v): pause slightly while doing or saying sth because you are uncertain or worri ed about it hibernate (v): spend the winter in a state of deep sleep hideout (n): a place where sb hides from the police or the authorities high-pitched (adj) : a high tone of voice hospitality (n): friendly welcoming behaviour towards guests or strangers huddle (v): a number of animals or people sitting or lying close to each other hurricane (n): an extremely violent wind or storm hyperactive (adj) : very active, overactive I ideal (adj): perfect identify (v): recognise, distingui sh ignore (v) : pay no attention to sb or st h illegally (adv): agai nst the law illiterate (n): sb who can' t read or wri te impatient (adj) : not patient imply (v): indi cate or say sth indi rectly, hint at sth impolite (adj): not polite import (v): buy products or raw materials from another count ry for use in your own country impose (v): use your authority to force people to accept sth impression (n): what you think of sb or sth impressive (adj): exciting, amazing improbable (adj ): unlikely to be true or to happen in accordance (pp): accordin g to in progress (pp): still going on incident (n): an event, occurence, sth that happens include (v): make sb or sth a part of a larger whole inconsiderate (adj ): not caring how your words or actions will affect other people, thoughtless inconvenient (adj): causing problems or difficulties increase (v): become greater in the number, level or amount indeed (adv) : in fact indicate (v): point out, show, suggest, impl y indigestion (n): when the stomach cannot process the food easily independence (n): when a country has its own governme nt and is not ruled by another country individual (adj) : relating to one particul ar person, rather than to a large group industrial (adj) : related to or used in industry (factories) inherit (v): receive money or property from sb who has died initially (adv) : at the beginnin g insect repellent (n): a product that can be sprayed in the air or on the body to keep insec ts away insistence (n): strong wish to do sth and refusing to give in install (v): fit a piece of equipment somewhere so that it is ready to be used instructor (n): sb who teaches a skill such as driving or skiing instrument (n): a tool or device used for doing a parti cular task insufficient (adj): not enough insurance company (n): a company into which people pay money so that if anything happens to them, the company pays them out insure (v): pay money to an insurance company intelligence (n): the ability to understand, think and learn quickl y intend (v): decide or plan to do sth intermission (n): short interval between two parts of film, play, concer t, etc. interrupt (v): stop an activity for a period of time intruder (n): sb who goes into a place where they are not supposed to be involve (v): contain, include irrational (adj): not logical irresponsible (adj): not responsible, careless irritation (n): a feeling of annoyance, especially for sth that you cannot easily stop or control isolate (v): separa te from other people physically or socia lly issue (n): topic, theme J judge (v): form an opinion about sb or sth, eval uate, assess jumper (n): a pullover, usually a woollen sweat er junction (n): where roads or railway lines meet and cross justice (n): fairness in the way people are treated K kennel (n): a small wooden house for a dog to live in kid yourself (v): bel ieve sth that is not true knit (v): make sth from wool by using two knittin g needles or machine knot (n): tying a string or rope upon itself L laboratory (n): a place where scientific research is carried out launch (v): start a campaign, etc. law (n): system of rules developed by a society or government in order to deal with crime, business agreements or social relationships layer (n): a flat strip of a materia l lead (n): a soft, grey metal (used in pencils) leak (n): a hole through which liquid or gas can pass leakage (n): when liquid or gas escapes _________________________________________ page 157 • from a pipe or container due to a hole or other fault lean (v): bend your body in a particular direction lecture (n): a talk given in order to teach people about a part icul ar subject legible (adj): clear and easy to read lightning (n): a bright flash of light in the sky duri ng a thunderstorm limit (v): rest rict liquid (n): a substance that flows (not solid or gas) literate (adj) : able to read and write litter (v): throw rubbish on the ground loathing (n): great dislike and disgust locate (v): fi nd out wher e sb or sth is loop (n): curved or circular shape louse (n): small insect living on the bodies of peopl e or animals and bites to feed off their blood loyal (adj) : faithful lunar (adj) : related to the moon lungs (n): two organs inside our chest used for breathing M magistrate (n): an official acting as a j udge in law courts which deal with minor crimes or disputes mainly (adv): primarily, mostly maintain (v) : keep at the same rate or level malaria (n): a ser ious disease carried by mosquitoes malnourished (adj) : not fed properl y mammal (n): species whose females give birth to babies, not eggs mango (n): a tropi cal fruit manifacturer (n): a person or organisation which produces goods in large quantiti es manipulate (v): ski lfully persuade people to do what you want manlike (n): having characteristics similar to human manoeuvre (n): movement from one positi on to another margarine (n): a yellow spread used instead of oil or butter master (n): sb with authority over a servant or slave masterpiece (n): an extremely good work of art measles (n): infectious illness that causes high temperature and red spots measure (n): action carried out by the authori ties in order to achieve a particul ar result measurement (n): the process of measuring an amount or si ze medical (adj) : related to medicine medication (n): pharmaceut ical products used to treat an illness or disease meditation (n): remaining silent and calm, thinki ng about sth carefully and deeply for a long time medium (adj) : average , midway betwee n ex tremes military service (n): service in a country's armed forces mineral (n) : a substance naturally formed in rocks and in the eart h, and also found in small quantities in food and drink minimise (v) : reduce sth to the lowest possible level or prevent it from incr easing beyond that level misfortune (n) : sth unpleas ant or unlucky mislead (v) : give sb a wrong idea about sth mist (n): thin fog mole (n) : dark spot on the skin moral (adj) : behavi ng in a way that you think is right , proper or acceptable mould (v) : form into sth mountaineering (n) : climbing the steep sides of a mountain mud (n) : a sticky mixture of soi l and water mugging (n): attacki ng sb in order to steal their money N narrative (n) : a story or acco unt of a series of events nation (n): the people of a country neat (adj): orga nised, clea n, tidy neglect (v): fail to look after sth properl y networks (n) : companies that broa dcas t radio or television programmes nickname (n) : an informal name nomadic (adj) : travelling fro m place to place rather than living somewhere perm antly nonsense (n) : anything silly or that does not make sense noodle (n): ri bbon- like stri p of pasta noticeable (adj) : obvious nuclear testing (n) : the testing of nuclear power nuclear weapon (n) : weapon that uses nuclear energy nutrition (n): taki ng food into the body and absorbing the subs tances that are necessary for staying healthy o observe (v) : keep an eye on sth, wat ch it carefully obvious (adj) : eas y to see or understand occasion (n): the time when sth happens, instance of sth happening occupy (v): have, hold or use sth occur (v) : happen, take pl ace omit (v): leave out on a daily basis (Pp): done every day on the edge of your seat : ver y inter ested or excited, waiting to see what will happen onwards (adv): moving forw ard, continuing operate (v): work, use operation (n) : surgery opportunity (n): a si tuation in which it is pos sible to do sth, chance opposing (adj) : not the same, completely different optional (adj): sth you can choose whet her you will do it or not , not co mpul sory ordinary (adj) : normal, not special or unu sual origin (n): the beginning of sth outcome (v): the result of an action or situation outer space (n): the area out side the eart h's atmosphere where other planets are overalls (n): piece of clothing covering the whole body overcome (v): deal with a proble m or a feeling successfully, control it overestimate (v): estimate sth too highl y overnight (adv) : immediately, suddenly overseas (adv): abroad, to or from another country overtime (n) : time you spend doing your job in addition to your norma l working hour s overweight (adj ): wei ghing more than is considered healthy ownership (n): owning sth ozone layer (n): part of the ear th' s atmosphere that prot ects us from harmful radi ation p paintbrush (n): a brush used for painting parade (n): a procession of peopl e or vehicles moving through a public place in order to celebrate an impor tant day or event parsley (n): a sma ll plant with curly leaves used for flavouring or decorating foo d passer-by (n): a person walki ng past sb or sth patient (n): sb receivi ng medical treatment from a doctor or hospital pattern (n): repeated or regul ar way in whi ch sth happens or is done peak (n): the highest level of sth peel (v) : remove the skin of a frui t or a vegetable perception (n): underst anding things throu gh the senses perform (v) : carry out an action, especially a complicated task permit (v) : allow sb to do sth or sth to happen persistence (n): continuing to do sth despite the difficul ties persuasive (adj ): capable of maki ng sb beli eve or do sth pessimist (n) : sb who thinks bad things are going to happen pick up (phr v): collect picturesque (adj) : attractive, interesting and unspoil ed pl ace page 158 pierce (v) : make holes through sth pillow (n): a rectangular cushion for resting your head when you sleep pine (n): a type of wood, light in colour pipeline (n) : a large pipe used for carrying oil or gas over a long distance, often underground pitch (v) : put up a tent pity (n): feeling very sorry for sb plaque (n): sth that forms on the surf ace of the teeth and causes gum disease plaster (n): materi al that is put on broken legs or arms in orde r to allow the broken bone to mend pluck (v): pull the strings of a musical instrument with your fingers polar (adj) : related to the ear th's poles policy (n): a set of ideas or plans used as a basis for decisions in poli tics, economics or business polish (v) : make sth shine possess (v) : have or own sth possession (n): anything that you own, that belongs to you post (v) : mail postpone (v): delay, put off pouch (n): a pocket of skin on an animal ' s stomac h in which its baby grows (e.g. a kangaroo) practice (n) : (1) the work a professional does (2) anything done regularly precaution (n) : action taken to avoid a dangerous or undesirable event precede (v) : be in front of sb or sth precisely (adv): exac tly predict (v): say that sth will happen in the future preheat (v) : heat up in advance (e.g. an oven) pret end (v): act in a way that could make people believe that sth is true althoug h it isn' t pride (n): feeling of satisfaction because you have done sth good or well priority (n): the most important thing that must be done or dealt with private (adj) : for one person or small group, not for the general public process (n) : a way of doing sth prohibit (v) : forbid or make sth illegal, ban promote (v): give sb a more impor tant job in the organisation they work for promotion (n): when you are given more important things to do in your j ob and earn more money proper (adj): appropriate, correct, suitable properly (adv) : correctly, satisfac torily, approp riately property (n): (1) anything that belongs to sb (2) a building and the land belonging to it protest (n)/(v): say or show publ icly that you objec t to sth publicity sheet (n): a sheet of paper adver tising certain products publish (v) : pri nt numerous copies of a book or magazine Q qualifications (n): the qualiti es and ski lls necessary for doi ng a task quantity (n): an amo unt of sth quarrel (n): a disagreement, argument queue (n): a line of people, car s, etc. waiting for sth quit (v): stop doing sth, give up R race (n): a group of people of common ancestry rainfall (n): the amount of rain that fall s during a particul ar period raise (n) : an increa se in sb's wages or salary raise (v): (1) bring up a child (2) collect (money, etc.) ransom (n) : money demanded by a kidnapper in order to set free a person they have kidnapped rate (n) : the degree or ext ent to which sth happens rea sonable (adj) : quite good, fair, sensible recognise (v): know who a person is or what sth looks like recommend (v): advise, suggest sth as the bes t choice reconnect (v): connect again re consider (v) : think about sth again and see if it needs changing recover (v): regai n health after being ill rectangular (adj ): a shape with two pairs of equal, para llel sides referee (n): an official who controls a sports match r efreshment sta nd (n): a small shop or stall with an open front selling soft drinks r efuel (v): to fill the petrol tank with more fuel r efugee (n) : sb who has been forced to leave their country due to a war or because of their political or religiou s beliefs regardless of (adj): not affected or infl uenced by sth, not taking sth into considera tion re gards (n): greetings, friendly feelings towards someone re gion (n): large area of land r egret (v): feel sad or disappoint ed because of sth that happened regulation (n): rule controlling people's behaviour or the way sth is done reject (v): (1) not accept sth (2) not agree with sb r elease (v): make sth available for sale or public showi ng reliable (adj) : sb or sth that can be trusted to work well or behave in a desirabl e way relief (n): feeling glad because sth unpl easant has not happened or is no longer happening r elieve (v): make sth less unpl easant, cause sth unpleasant to disappear r ely on (v): depend on sb or sth remain (v): stay in a particular place or condition remove (v): take sth away from where it is renovat e (v): restore a building to good cond ition replace (v) : take the place of sth represent (v) : act on behalf of sb or sth r epresentative (n): sb who acts on behalf of another person or a group of people require (v) : need, demand resent (v): feel bitter and angry about sb or sth reserved (adj): not expressing your feelings r esi gn (v): forma lly announce that you are leaving a job or position resort (n): a place where many people go for holidays response (n): reply, reaction, answer r esponsibility (n): duties that you have because of your j ob or position r estl ess (adj): impatient, finding it difficult to keep still r estore (v) : return sth to its original condi tion r estrict (v) : prevent sb from acting freely r estriction (n) : sth that limits what you can do re strictive (adj) : preventing you from doing sth reverse (adj): the opposi te to sth review (n): report or talk expressi ng your opinion on sth r evival (n): becoming active or popular again r evolution (n): an attempt by a group of people to change the pol itical system of their country by force r evolve (v) : move in a circle around a central point or line r obe (n): a loose piece of clothing which covers all your body and goes down to your toes r oll (v) : move along a surface turning over many times roll er-coaster (n): a small railway that goes up and down steep slopes and people ride for pleasure and excitement roots (n): sb' s background, the place or culture that sb or their family comes from rough (adj) : violent, harsh r oute (n): the way from one place to another r ow (n): a line of people or things rubber (n): strong waterproof elastic substance ruin (v) : damage, spoil, harm runner-up (n): sb who has finished in second place of a race or competition __________________________________________• page 159 • rush (v): go somewhere quickly ruthless (adj): cruel, willing to do anything that is necessary to achieve sth S sacred (adj): holy, believed to have a special connection with God is safeguard (v): protect sb or sth from :l being harmed, lost or badly treated sale (n): the quantity of products sold salmon (n): a soft fish with pink flesh found in the Pacific and Atlantic oceans sample (n): a small quantity of a product showing you what it is like scales (n): machine or device used for weighing people or things b scarcely (adv) : barely, only just, rarely schedule (v): arrange sth to happen at a particular time science-fiction (n): fiction about events taking place in the future or in another part of the universe scratch (v): mark or cut the surface of sth with a rough or sharp instrument screen (n): a flat surface on which pictures or words are shown seabed (n): the ground at the bottom of the sea seat belt (n): a strap that you fasten across your body while sitting in a car or plane for safety seek (v): try to find seldom (adv): rarely select (v): choose self-confidence (n): being confident and sure of yourself selfish (adj): caring only about yourself, not about other people send off (phr v): send sth by post sense (v): become aware of sth sequence (n): a series of things or events occuring one after another in a particular order session (n): a period during which sth takes place (eg. an official meeting or other activity) shallow (adj): not deep shape (n): figure or outline of sth sheet (n): a rectangular piece of paper shelter (n): small building or covered place which will protect people from bad weather or bomb attacks shepherd (n): sb who looks after sheep shoelace (n): a string that ties up a shoe shore (n): the land along the edge of a river, sea or lake Siamese twins (n): twin babies born joined together at some point of their body sickening (adj): making you feel sick side effects (n): the harmful effects of a drug or medicine sigh (v): let out a deep breath, expressing disappointment or tiredness sightsee (v): visit places that are of interest to tourists significance (n): importance significant (adj): very important signify (v): mean, represent sth site (n): place sketching (n): quick drawing without much detail skilful, skillful (adj): doing sth very well skill (n): knowledge and capability enabling you to do sth well skull and crossbones (n): a picture of a human skull over a pair of crossed bones, used to indicate death or danger sky-diving (n): jumping out of an aeroplane and falling through the air using a parachute slant (v): lean to the left or to the right sleeves (n): parts of clothing covering your arms sliding door (n): a type of door which opens and closes by sliding left or right slight (adj): being very small in degree or quantity slippery (adj): sth difficult to walk on because it is wet, smooth or greasy slot (n): a narrow opening in a machine or container in which coins can be inserted (at a) snail's pace (pp): very slowly social worker (n): sb whose job is to give help and advice to people who have serious problems solid (adj): very hard or firm sore (adj): causing you pain and discomfort source (n): the place where sth begins spacious (adj): large in size, with lots of room spectacular (adj) : impressive, breathtaking, fantastic speech (n): a formal talk which sb gives to an audience spice (n): powder or seeds from particular plants, which are put in food to give it flavour spicy (adj): food strongly flavoured with spices spike (n): a long piece of metal with a sharp point spiritual (adj): related to people's deepest thoughts and beliefs split up (phr v): separate spread (v): affect a large area or many people spy (n): sb who obtains secret information about another country or organisation squeeze (v): get the juice out of a fruit or vegetable by pressing it stable (n): a building on a farm where animals are kept stage (n): a step of development stain (n): a mark which is difficult or impossible to remove by washing staircase (n): a set of stairs inside a building stake (n): pointed wooden post standard (n): sth used in order to judge the quality of sth else starch (n): a carbohydrate found in bread, pasta, potatoes, etc. stare (v): look at sb or sth for a long time, often rudely or impolitely startle (v): surprise and frighten slightly starve (v): suffer greatly from lack of food state (v): say or write sth in a formal or definite way status (n): social or professional position steam (n): hot mist that forms when water boils steel (n): a very strong metal made from iron sting (v): when an insect or a plant pricks you and causes you a sharp pain stock (n): a supply of sth store (v): keep things somewhere in order to use them when they are needed storm (n): a lot of rain and high winds strain (n): intense physical or mental effort strategy (n): a general plan in order to achieve sth street directory (n): a book containing maps of the streets of a city strengthen (v): make sth stronger strict (adj): severe, sth that must be obeyed structure (n): the way sth is built or made stuck (adj) : unable to move although you want to get away from a place or situation substantially (adv) : significantly, greatly substitute (v): take the place of sth else subway (n): underground railway suitable (adj): right or appropriate for a job or posi tion suntan lotion: a cream you put on your skin when sunbathing superficial (adj): related to the surface or the most obvious features of sth superior (adj): much better than sb or sth else supernatural (adj): beyond what is considered normal or natural superstition (n): believing in magic or things that are not real or possible supplement (n): a pill containing nutritious elements, taken in order to improve your health or diet supplies (n): food and equipment necessary for sth surface (n): the flat top part of sth surrender (v): not resist or give up the effort to win surround (v): be all around sth survey (n): trying to find out information about a group of people by asking a series of questions survivor (n): sb who continues to live after a disaster, accident or illness page 160 sweat (n): liquid which comes through the skin when you are hot, ill or afraid T tactfully (adv): taking care not to say or do sth that would hurt other people's feelings tactic (n): a method used in order to achieve sth take turns (v): when two people do sth one after the other talkative (adj): talking a lot tap (n): a device that controls the flow of a liquid coming from a pipe t-bar (n): the top of the letter T tear (v): rip or cut sth telephone directory (n): a book listing people's names, addresses and phone numbers in alphabetical order terrify (v): scare, frighten testify (v): give a statement about sth in court thicken (v): become more solid threaten (v): say that you will do sth to sb in order to make them do sth you want thrill (n): great excitement, pleasure or fear throughout (prep): from the beginning till the end thunder (n): a loud noise from the sky coming after a flash of lightning to a certain extent: up to a certain point tolerate (v): put up with sth, accept it although you don't like it tool (n): a useful instrument or piece of equipment topple over (phr v): fall over, collapse totally (adv): completely track (n): the rails along which a train travels train (v): learn different skills in order to do sth transfer (v): cause sb/sth to move to a different place transport (n): means of travelling trapped (adj): unable to escape or move trigger off (phr v): cause sth to happen trillion (n): a number with twelve zeros troublesome (adj): causing trouble trustworthy (adj): very reliable and responsible tube (n): a long hollow object like a pipe tulip (n): a kind of bell-shaped flower tuna (n): large fish living in warm seas and caught for food twist (v): injure your ankle or wrist by turning it too sharply tyre (n): a thick piece of rubber fitted onto the wheels of vehicles U unattended (adj):unwatched, left alone, abandoned unaware (adj): having no knowledge of sth unbearably (adv): in a very unpleasant, painful or upsetting way unbelievable (adj): very good, impressive, extreme, sth that you cannot believe uncertainty (n): doubt, not being sure about what to do unconscious (adj): having lost consciousness, unaware of what is going on underqualified (adj): not qualified enough underwater link (n): connection between two places beneath the water unexpected (adj): sth surprising because you don't expect it to happen universe (n): all the stars and planets unleaded fuel (n): petrol containing less lead in order to protect the environment unlikely (adj): not very probable to happen unrestrained (adj): out of control unsteady (adj): not steady, shaky up to date (i): the newest thing of its kind, valid upward (adj): moving towards a higher point or level urge (v): try hard to persuade someone to do sth utensil (n): anything used to cook with utterly (adv): completely, absolutely V vacation (n): holiday vaccinate (v): give sb an injection in order to prevent them from falling ill vaccine (n): an injection that prevents people from getting a disease vacuum (v): clean sth with a vacuum cleaner value (n): how important or useful sth is values (n): moral principles and beliefs, ethics variety (n): different types of sth vehicle (n): a car, bus, train etc. vet (n): a doctor for animals via (adv): going through a place victim (n): sb who has been hurt or killed victorious (adj): having won a war, struggle or competition violent (adj): using physical force or weapons with the intention to do harm virus (n): a kind of germ that can cause diseases voluntary (adj): sth done or performed willingly W wage (n): payment in return for work or services warehouse (n): a large building where goods are stored warning (n): anything informing people of a possible danger, problem or sth unpleasant warrior (n): a fighter or soldier (especially in past times) wax (v): polish a surface by spreading a thin layer of wax on it weapon (n): a gun, knife or other object used for killing or hurting people or animals well-behaved (adj): with good manners wet (v): get water or some other liquid over sth whatsoever (adv): at all wheat (n): cereal crop grown for food whereabouts (n): the location of sth white lie (n): minor or unimportant lie willing (adj): wanting, not mind doing sth willingness (n): desire, strong wish to do sth wipe (v): clean up with a cloth wise (adj): clever, sensible, reasonable witchcraft (n): use of magic powers, especially evil ones withdraw (v): remove, take sth away witness (v): see sth happen woodshed (n): small building where firewood or garden tools are stored worldwide (adv): all over the world worthwhile (adj): worth the time, money or effort spent on it, enjoyable, useful y yeast (n): a substance which makes bread rise Verbs, Adjectives, Nouns with Prepositions A account for accuse of agree on sth (dis)agree with sb aim at apologise to sb for sth apply to sb for sth (dis)approve of argue with sb about sth arrest sb for sth arrive in/at ask for assure (sb) of absent from accustomed to addicted to afraid of allergic to amazed at/by angry at what sb does angry with sb about sth annoyed with sb about sth anxious about ashamed of attached to (un)aware of (dis)advantage of advice on (in) answer to attack on B beg for begin with believe in belong to benefit from beware of blame sb for sth boast about/of bad at bored by/with bound with brilliant at busy with (put the) blame on sb C care about/for change into collide with come from comment on compare with/to complain to sb about/of concentrate on congratulate sb on sth connect to/with consist of contrast with cope with crash into criticise sb for (in)capable of careful of careless about certain about/of charged with/for clever at close to sb/sth combined with conscious of content with covered in/with crazy about crowded with cruel to curious about (take) care of cheque for comparison between confidence in sb connection between contact between cruelty to/towards cure for D date back to deal with decide on dedicate to demand from depart from depend on describe sb/sth to sb die in (an accident) die of/from differ from dismiss from distinguish between divide between/among divide into do sth about dream about/of delighted with dependent on different from/of disappointed in/by/about/with discouraged from disgusted by/at disqualified from dressed in delay in demand for departure from description of difference between/of difficulty in/with discussion about/on distance of doubt about E enter into escape from excuse sb for sth experiment on/with eager for efficient at engaged to sb/in sth equal to excellent at excited about experienced in (put) effort into sth engagement to sb example of exception to excuse for expert at/in/on F fail in an attempt fail to do sth fight with fill sth with sth else finish with forget about forgive for faithful to familiar to sb familiar with famous for fed up with fond of frightened of full of furious with sb about/at sth failure in/to G glance at good at grateful to sb for sth guilty of generosity toltowards H happen to page 162 hear about/from/of hope to do sth/for marriage to handy for N happy with/about nervous about harmful to hopeless at need for (no) hope of 0 object to I include in obliged to sb for sth inform of insist on objection to invest in opinion of/on involve in opposite of/to identical to P ill with pay for impressed by/with praise sb for sth independent of prefer to inferior to prepare for informed about prevent from interested in protect against/from provide sb with idea of punish for impression on sb put oneself through information about (have no) intention of patient with invitation to pleasant to pleased with J polite to join in popular with joke about proud of puzzled by/at jealous of pity for K preference for knock at/on know of/about Q quarrel with sb about sth keen on keen to do sth qualified for knowledge of quarrel about L R laugh at react to leave for receive from lend to recover from lie to/about refer to listen to regard as live on relieve oneself of look for rely on remind sb of/about sth locked in replace sth with sth else result from/in lack of related to M responsible for mention to mistake sb for reaction to mix with reason for (have a good/bad) relationship with married to reply to mean to reputation for/of responsibility for (make) room for S save sb from separate from shout at smile at/to spend money/time on/in stare at succeed in suffer from suspect sb of sympathise with safe from same as (dis)satisfied with/by scared of sensitive to serious about shocked by/at short of shy of similar to skillful/skilled at (feel/be) sorry about/for superior to surprised by/at suspicious of sympathetic to/towards smell of solution to T thank for think of/about throw at/to translate from/into terrified of thankful for tired of talent for sth (have/be in) trouble with U upset about/by (make) use of W warn sb about/of/against waste time/money on worry about write to sb worried about Prepositional Phrases Ahead ahead of one's time ahead of schedule At at the age of at the airport at the beginning (of) at the bottom of at breakfast/lunch/dinner at the bus stop at the corner at dawn at one's desk at the door at the end (of) at first Before before long By by accident by air/rail/road/sea by appointment by birth by bus/car/plane etc. by chance by cheque by day/night by far by force by hand by heart by land by luck by means of by mistake by now by oneself by phone/post/air mail by one's side by the time by the way For for ages for certain for a change for ever for fear (of) for fun for good (take sth) for granted for hire/sale for instance for the rest of for one's sake for the time being for a while From from experience from memory from now on from time to time In in addition (to) in advance in agreement (with) in answer to in bed in the beginning in brief in case of in cash in charge of in colour in common in comparison with at first sight at a glance at hand at a high speed at a hotel at....km per hour at last at least at a loss at the mat ch at midnight at the moment at most at night at noon at once at peace/w ar in conclusion in good/bad condition/shape in control of in the country in danger in debt in demand in detail in difficulty in the direction of in doubt in the end in fact in fashion at present at random at any rate at the same time at the station at the time at times at the top of at university at the weekend at 23 Oxford St. in favour of in future in general in hand in good/bad health in hospital in a hotel in a hurry in ink/pencil/pen in love (with) in luxury in the meantime in the middle of in the mirror page 164 in a moment in a queue in one's free time in the mood in reality in touch (with) in the morning in return in town in need of in the right/wrong in turn in the north/south in safety in uniform in one's opinion in seconds in use in order/a mess in secret in vain in order to in the shade/sun in a loud/low voice in pain . in short in a way in pairs in a show in the way in particular in sight (of) in a word in the past in a state of in other words in person in the station in writing in pieces in the streets in place of in the suburbs Into in politics in good/bad taste into pieces in practice/theory in tears in prison in a bad temper in private/public in time (for) in progress in no time - - Off on fire on top of off the air on the... floor (of) on tour off duty on foot on the way off the record on the one/other hand on the whole off school/work on holiday on an island Out of On on one's knees out of breath on a ....afternoon/evening on the left/right out of control on the air on one's mind out of danger on arrival on New Year's Day out of date on behalf of on the news out of doors on one's birthday on the outskirts out of fashion on business on one's own out of hand on the contrary on page... out of luck on the corner on the pavement out of order on a... day on the phone out of place on one's death on purpose out of the question on a diet on the radio/television out of reach on duty on sale out of season on earth on second thought(s) out of sight on an excursion/a journey/a tour/a on this / the street (s) out of stock trip etc. on strike out of use on an expedition on time out of work To to one's amazement/surprise to this day Under under control under pressure under age under discussion under strain under arrest under the impression With Without without fail/success with regard to without delay without warning with a view to without (a) doubt _________________ Derivatives NOUN VERB ADJECTIVE/ADVERB ability inabilit disabilit enable, disable able, unable, _ iLcce Jill1ce'-acceRtabilitY. acceRt C!m)acceRtable>-b: _ accident accidental>-lY _ achievement achieve achievable action, activity, activation, actor , actress, acting act, activate active, activated addition, additive add additional>-ly admiration, admirer admire admirable>-ly, admiring>-ly admission, admittance admit admissible dis advantageous adventure, adventurer adventurous>-ly advertisement advertiser advert advertisin advertise advertised"-- _ advice , adviser, advisability advise advisable. advisory -'agr"' ee"' -" alarm amaze "'-- aRIlli' -' argue arrive comfort, ...:comfort _ comRarison, cOIDRarability comRare comRetition comRete £Q1]1[Jlain t corrml ain'- -:---:-_-:-__-:--:7" _ conclusion c_onglude:- c_o_nc!!!Siye>-ly, _c_onc!uding--:- _ confidence confide confident>-ly, confidentia!>-I,O-y _ connection connect connecting, connecte"-'d"---- _ consideration consider considerable>-ly, (in)considerate>-ly, considered astonishment astonish attendance, attendant, attention attend attraction, attractiveness attract automation beginning begin behaviour behave belief, believer believe bore, boredom bore breath, breathing, breather breathe choice choose combination combine converse correct encourage, discourage cr,-, e", tu , '-'i-'.ty, _ :=.c a",". r"" e CL v create crime, criminal, criminality criminal>-ly critic, criticism criticise critical, criticising crowd crowd crowded curiosity curious>-ly dang er endanger _ "- darkened @y, daylight daily death die dead, deadly, deathly decisivenee.£s£.s _ deRendant, (in)deRendence, deRendency deRend dependent>-ly, descriRtion describe descriRtive>-ly destroyer, destruction destroy destruclive>-lY. _ development, developer develop developing, develoR-"ed "'---- _ page 166 NOUN VERB differ discussion discuss econo_mj se economic-,- esonolTlicEl:c:lY _ educate educatedLeducatLo_na.l>-ly .l- _ emgloyer, emgloyeeL(un)emgloyment employ (un)unemQlQyed, employable endiI1K end eDilless>-ly _ energy energise energetic>-ally enjoy ment enjgy _ enthusf _ eguipment eguip eg.!!iQp=ed =- ,--- _ excitement excite exciting>-ly, excited>-ly, excitable existence exist existent, non-existent, existing _ • expectation, expectancy expect (un)exRected>-ly, _ eXQfrienc.Y el(.Rerienced, inexperienced, exp..=:e=ri=e=n""ti=a",l. _ expla nilti..o_n _ fail f'iik c!.,..f].iJing _ fashion_ _ fashion fashionable>-l y fa..Y,.our favo!!r favourable>-lj', _ five five, fifth fool, foolishness fool ._ _ . _ fortune, misfortune fortunate>-ly, unfortunate>-ly free freeze ________ ss, friendshio befriend ___________grow harm heighten - helplessness hel p' _ hunze""'r.,..-..,..,....---,-_ ....,...-,--.,..,....-_ ______-'-' h." u.!j ng er ---,-----,.,..-,--__ llUll listic idea, )dei\lisation, igealism, idea idealise _ illness ill image, imagination imagine immediate>-ly imQortance important>-ly imRression impress irrmIove !mRr:9...Y.ed information, informer inform informative>-ly !!!lillY injure injured in:mection, insRector insR..=:e=c,,-t in§!1r1!.Ilf.e,j Ds_urer ins ure ins!!rede:... intention,i ntent in...Y.entio..Q , inventor invent inventive investigate jealousy jealous>-ly laugh, laughing,.lill!ghter _ laugh length lengthen _ _... life, living,liveliness live 1Qgk logical>-ly loser, lo!is lose luck luckv>-l _ iQ.tentioIl J!J>-lj', i .ntel).t>-ly, investigative, investigatoJ-Y _ _ _ _ _ _ _ marry .nt move ______motorise murder naturalise nerve 11 QReration,oR"'e=ra "'t =o.o...r .@§)order Q!jgin, ori,.t:g""in ""aOo-,I=itc./-y _________-=o=riginate _________-=°Rerate order _ _ normalise ,_,_, __ _ ____________________________________________ page 167 NOUN VERB ADJECTIVE/ADVERB _ _ ____ _ prac'-"ti'-"s-"-e -J< redic'_'_ t _ _ -= _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ Plevent... _ profess _ ____ _ _ ___ __ risk __-'-s=av:'-' ee-_-:--_ (dis)satisfy _ -ZC= secure sense _ _ _ ___ _ _ _ _ _ _ __ ___ ___ _______shone"'n' -' ------'= "-' ,'-" _ ____________ -"th"' in'-.'-' k"- threaten ___ti!:L. _ train _ (mis)understand use va pago 168 NOUN VERB ADJECTIVE/ADVERB warm th, warmer warm warm>-ly warning warn waming>-l y, warned week , weekday, weekend weekl weight weigh weighty, weightless wisdom Irregular Verbs INFINITIVE PAST PAST PARTICIPLE INFINITIVE PAST PAST PARTICIPLE be was/were been lie lay lain bear bore born (e) light lit lit beat beat beaten lose lost lost become became become make made made begin began begun mean meant meant bend bent bent meet met met bind bound bound pay paid paid bite bit bitten put put put blow blew blown read read read break broke broken ride rode ridden bring brought brought ring rang rung build built buil t rise rose risen burn burntlburned bumtlbumed run ran run buy bought bought say said said burst burst burst see saw seen catch caught caught seek sought sought choose chose chosen sell sold sold come ca me come send sent sent cost cost cost set set set creep crept crept sew. sewed sewn/s ewed cut cut cut shake shook shaken deal dealt dealt shine shone shone dig dug dug shoot shot shot do did done show showed shown draw drew drawn shut shut shut dream dreamt/dreamed dreamt/dreamed sing sang sung drink drank drunk sink sank sunk drive drove dri ven sit sat sat eat ate eaten sleep slept slept fall fell fallen smell smelt/smelled smel t/smelled feed fed fed speak spoke spoken feel felt felt speed sped sped fight fought fought spell spelt/spelled spelt/spelled find found found spend spent spent fly flew flown spill spilt/ spilled spilt/spilled forget forgot forgotten split split spli t forgive forgave forgiven spoil spoilt/spoiled spoilt/spoiled freeze froze frozen spread spread spread get got got stand stood stood give gave given steal stole stolen go went gone stick stuck stuck grow grew grown sting stung stung hang hung hung strike struck struck have had had sweep swept swept hear heard heard swear swore sworn hide hid hidden swim swam swum hit hit hit take took taken hold held held teach taught taught hurt hurt hurt tear tore torn keep kept kept tell told told kneel knelt knelt think thought thought knit knitlknitted knitlknitted throw threw thrown know knew known understand understood understood lay laid laid wake woke woken lead led led wear wore worn lean leant/leaned leant/leaned weave wove woven learn learnt/learned learntllearned weep wept wept leave left left win won won lend lent lent withdraw withdrew withdrawn let let let write wrot e written _______________________________________ page 169 Contents Revision Test 1 170 Revision Test 2 : 173 Revision Test 3 176 Revision Test 4 179 Revision Test 5 182 Revision Test 6 185 Final FCE Test 188 Final ECCE Test 192 Keys to Tests 197 units 1-4 Revision Test 01 I Grammar Practice A Choose the correct answers. 1. As part of my job, I a. travel abroad a lot. b. am travelling c. will travel d. had travelled 2. Every Friday, my fa ther a. is taking b. takes us out to ea t. c. has been taking d. wi ll take 3. Alice a. was buyi ng her first car in 1981. b. wi ll be buyi ng c. bought d. buys 4. Hurry up! The bus a. leaves b. wi ll be leaving _ c. had left d. is leaving 5. We you when we have the final resul t. a. will inform b. will have informed c . are informing d. informed 6. Mu m the foo tball ma tch when the power wen a. had been wat chin g b. used to wa tch t out. c. wa s wa tching d. will watch 7. Don ' t WOlTy ! I a. '11 fix everything. b. fix c. '11 be fixin g d. had bee n fixing 8. Mary a. has told me a sec ret abo ut her pas t yesterday. b. told c. is tell ing d. wi ll tell 9. Josh a. drove for about 2 hours when he realised his ca b. had been driving r was low on gas. c. has been driving d. will have been driving 10. the answer to that que stion? a. Are you known b. Hav e you known c. Do you know d. Had you known B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Hel en rarely goes to the theat re. not Helen the theatre very often. 2. I am considering visi ting my cousi ns in Ca nada next summer. thinking I my cousins in Canada next summer. 3. When Nicky finished studying, it was nearly 3 am. by Nicky 3 am. 4. I was washing my car when suddenly there was an explosion in the nearby factory. something I was was hing my car whe n in the near by factory. 5. It is likely to rain today. think I _ today. ------------------------- I Vocabulary Practice page 171 I A Choose the correct answers. 1. It was Sue's birthday, so she a. asked for b. asked out a friend to celebrate. c. asked in d. asked with 2. After thinking about it, he finall y a. came along b. came into to accept the offer. c. came across d. came round 3. I remember Sall y a. reporting something about a party on Saturday. b. me ntioni ng c. expressing d. prai sing 4. My boss a. ren ted me because he thought I was worthy of the job. b. let c. hired d. lent 5. Mary a. broke into wi th her boyfriend last week. b. broke down c. broke in d. broke up 6. I couldn't help but a. look the huge birthmark on her hand. b. notice c. see d. watch 7. Do you think you can take Thursday off from a. job b. work ? c. duty d. task 8. I can' t do two things _ a. at last b. at leas t c. at the same time d. at first 9. I was surprised a. about her reaction. b. by c. with d. of 10. How were your test a. results , Brian? b. solut ions c. effects d. consequences B Complete using the correct form of the words in bold type. 1. My mo ther is a primary school _ 2. What is your ki nd of music? 3. I am not good at making _ TEACH FAV OUR DECIDE 4. He is a basketball player. PRO FESSION 5. She wants to have a wedding. TRADITION page 172 C Choose the correct answers. Last week, a thief (1) my house. He (2) all of my jewellery, along with my television set and my stereo. (3) , I thought I had left the door unlocked by mistake. But then, I (4) at the window and realised the glass was broken. I called the police right away, but they weren't very helpful. They just told me to avoid keeping expensive things in the house. Now, I (5) buying an alarm to keep this from happening again. 1. a. broke up 4. a. noticed b. broke into b. mentioned c. broke out c. regarded d. broke down d.looked 2. a. stole 5. a. had considered b. will steal b. consider c. steals c. am considering d. was stealing d. be considering 3. a. At least b. At first c. At most d. At present units 5-8 Revision Test 02 - ce I Grammar Practice ,v, AChoose the correct answers. 1. You lie so much. Try to be more honest. a. couldn' t b. wouldn't c. shouldn't d. can't 2. You're a good student John. You don't need that hard . a. study b. to study c. studying d. to have been studying 3. I prefer to playing football. a. swimmi ng b. to swim c. swim d. to be swimming 4. Alice, I borrow your car? a. will b. would c. must d. could 5. Don 't you remember Lucy last week ? a. meet b. to meet c. meeting d. to meeting 6. I get you another glass of water? a. Shall b. Would c. Mustn't d. Can't 7. Maria suggested on a short camping holiday. a. to go b. go c. going d. to going 8. I left my keys at home because the y're not in my bag. a. must have b. can have c. would have d. could have 9. Where' s Harry ? I find him anywhere. a. wouldn't b. might not c. will not d. can' t 10. You have to be careful not anything insulting. a. to say b. to have said c. to be saying d. saying B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in totaL) 1. I needed some milk, so I went to the supermarket. get I went to the supermarket some milk. 2. Sue will make an effort to get there on time . try Sue there on time. 3. Juli e didn't lock the door when she left her house. without Julie the door. 4. Karen, I'd like you to help me with the washing-up. will ! Karen, with the washing-up? 5. Simon, let's go to an amusement park. how Simon, to an amusement park? page 174 I Vocabulary Practice A Choose the correct answers. 1. Laura a. gets along well with everyone. b. gets away c. gets by d. gets over 2. Why don' t you try walking to work a. for a walk b. for ages ? It's not that far away after all! c. for a change d. for ages 3. Don' t forget to leave a a. donation b. tip for the waiter. c. allowance d. loan 4. What a. fine is used in Australia? b. bill c. income d. currency 5. He tries to a. give away to the communi ty by donating money to charity . b. give back c. give in d. give out a. crew 6. The on the cruise ship was very helpful and frien dly. b. staff c. team d. group 7. All the a. hos ts at the dinner party were seated upo n arrival. b. visitors c. guests d. emp loyees 8. You can never a. count on Sarah to be on time. She 's always late. b. count in c. co unt out d.countup 9. I called him by the wrong name a. by heart b. by force _ c. by chance d. by mistake 10. They a. fell in two years ago and haven' t spoken to each other since then. b. fell out c. fell behind d. fell off B Complete using the correct form of the words in bold type. 1. The reports show that it was a year for the company. 2. She is tall, thin and extremely . Don' t you think? SUCCESS ATTRACT 3. She is so that she cries every time she sees a romantic film. SENSE 4. He didn ' t get the job because he didn' t have the necessary _ QUALIFY 5. The two countries didn' t manage to reach an _ AGREE _________________________________________ page 175 C Choose the correct answers. My sister was sick for a whole month. She had no energy and had (1) in bed all day. She (2) go to school, so she (3) in her classes. The doctor told her she (4) eat well and drink a lot of fluids. Feeling ill is not very fun, so I spent my time (5) to cheer her up as much as I could. I bought her little presents and kept her company. We watched a lot of DVDs together, listened to music, and read magazines. Overall, she had a positive attitude the entire time even though it took such a long time for her to (6) her illness. 1. a. stay 4. a. should b. to stay b. might c. to be staying c. may d. staying d. would 2. a. couldn't 5. a. to try b. can't b. trying c. wouldn't c. try d. mustn't d. to have tried 3. a. fell down 6. a. get by b. fell out b. get on with c. fell for c. get over d. fell behind d. get away units 9-12 Revision Test 03 I Grammar Practice A Choose the correct answers. 1. We are looking for a. the different place to go on holiday this year. b. one c. a d. an 2. I didn't find a. either of the two books interesting. b. neither c. both d. a few 3. student has their own locker. a. Some b. Any c. Every d.No 4. She is girl in the entire class. a. smarter b. smarter than c. the smart d. the smartest 5. Even if! tried my hardest, I could never run as as him. a. fast b. fastest c. faster d. the fastest 6. my brothers play sports. a. Neither b. None c. Both of d. Some 7. Feel free to visit us day next week. a. no b. a few c. most d.any 8. I won't eat spicy. a. everything b. any c. anything d. nothing 9. time I eat too much, my stomach starts to hurt. a. Some b. Every c. Most d.Many 10. He behaved at the patty. a. bad b. worst c. badly d. worse B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. Although she acts very well , she has never had a leading role. good Despite being , she has never had a leading role. 2. In some countries, the ox is used for pulling vehicles or carrying things. are In some countries, for pulling vehicles or carrying things. 3. The Economist is published every week. a The Economist magazine. 4. Two hours later , David had swum six miles, but Julie had only swum three. twice Two hours later, David had swum Julie. 5. The book was less interesting than I thought it would be. as The book I thought it would be. _________________________________________ page 177 I Vocabulary Practice AChoose the correct answers. 1. a. Hold on my bag for a minute, will you? b. Hold on to c. Hold up d. Hold out 2. He a. kept off making fun of her even thou gh she was crying. b. kept out c. kept on d. kept up 3. Short ski rts are a. in fashion b. in favour this seas on. c. in detail d. in common 4. I could tell from a distance that tho se diamonds wer e a. fals e b. untrue c. fake d. imitat ion _ 5. She was so upset that she a. handed in b. hung about the phone on him. c. hung on d. hung up b. in case 7. Her table a. habits are horrible ! She' s so messy! b. behaviours c. manners d. manner 8. Try not to a. confess b. reveal the secret to anyone. c. admit d. displ ay 9. I don 't think that hat a.goesahead b. goes out your outfit. c. goes on d. goe s with 10. Eating healthil y can a. avoid b. prevent you from gaining weight. c. keep up d. reduce BComplete using the correct form of the words in bold type. 1. He gave a brilliant _ PERFORM 2. Nowada ys, children are exposed to from a very early age . VIOLENT 3. His is bec omin g mor e and more hostile. BEHAVE 4. They say that" kill ed the cat. " CURIOUS 5. After a lot of , he made the right deci sion . THINK page 178 C Choose the correct answers. History is a subject that has always interested me. Even as (1) little girl, I loved going to museums and reading about ancient civilisations. In school, I was (2) student in my History class. I always paid attention and got really good grades. After high school, I discussed it with my parents and decided to (3) and study archaeology in college. Now, I work as (4) archaeologist and I absolutely love my job. Every time I meet a young person with a dream, I always encourage them to pursue their passion. There is no (5) feeling than doing what you love. 1. a. the 4.a.a b. a b. an c. c.one d.one d. the 2. a. the best 5. a. greater b. better b. great c. best c. greatest d.good d. the greatest 3. a. go out b. go on c. go with d. go ahead • • units 13-16 e V I 10 Test 04 I Grammar Practice A Choose the correct answers. 1. They looked at a. their b. another and laughed. c. each ot her d. every other 2. My handb ag a. is stolen b. stole yes terday morning. c. was stolen d. was stealing 3. Tricia's hair a. dyed by the hairdresser. b. was dyed c. had dyed d. were dyed 4. My mum a. had me clean my room yesterday. b. had me cleaned c. had me cleaning d. is having me clean 5. I remember a. to have b. having my pict ure taken by you. c. to be having d. had a. We 6. cat is friendlier than yours. b. Ours c. Our d. Us 7. Please help a. eac h other to more food - there's plenty. b. ourselves c. us d. yourselves 8. You wouldn't be wet if you an umbrella with you. a. had taken b. took c. take d. will take 9. If 1 you , I wouldn ' t get upset over something so insignificant. a. am b. had been c. were d. was being 10. If you New York, make sure to see the Empire State Building. a. visited b. have visited c. had visited d. should visit B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. They say that he is a millionaire. said He a mill ionaire. 2. If you want eve ryone to understand you, speak more clearly. yourself If you want to , speak more clearly. 3. I have to send the application form by Friday. be The application form by Fri day. 4. If you happen to see Dr Turner, give him my regards . should If Dr Turner, give him my regards. 5. Someone broke Gary's front teeth while he was playing football. had Gary whi le he was pl aying football. page 180 I Vocabulary Practice A Choose the correct answers. 1. Even though he's missing a leg, he leads a(n) life. a. common b. usual c. normal d. boring 2. Can you please _ the word 'destiny' in the dictionary? a. look over b. look up c. look into d. look after 3. We _ that you stay the night. We won't take ' no' for an answer. a. persist b. resist c. push d. insi st 4. He doesn 't reall y like meat - , beef. a. in pieces b. in particular c. in general d. in order 5. Despite his appearance, he's really not as as he seems. a. tough b. difficult c. hard d. demanding 6. He spoke so softly that it was difficult to what he was saying. a. make for b. make up c. make out d. make in 7. The Egyptians buil t the Pyramids. a. ancient b. antique c. elderly d. old 8. lowe John a lot of money and I still haven 't _ a. paid him off b. paid him back c. pulled him over d. pull ed him down 9. , the actor looks a lot shorter than he is on screen. a. In secret b. In private c. In theory d. In reality 10. He is the onl y ance stor of the King. a. live b. living c. alive d. livel y B Complete using the correct form of the words in bold type. 1. I don't go out on weekdays. NORMAL 2. He gav e us a vers ion of the story. DIFFER 3. He stood there in the , with the lights off. DARK 4. These snakes are _ POISON 5. There was an expression of on his face. BORE __________________________________________ page 181 C Choose the correct answers. Nowadays, more and more children (1) in homes where two languages are spoken. Langu age experts have found that children can learn two languages at the same time and that they can't really tell the difference between (2) . (3) they speak more than two languages, they can still easily switch from one language to the other. According to Dr Emma Redmond, children are not confused by using two languages once they have learnt when and with whom they should use each language. However, the most important thing is to let children learn in an environment free from pressure - a relaxin g and supportive (4) . (5) they love Power Rangers, then they should feel free to talk about their favourite heroes in either of the two languages. 1. a. are raised 4. a. another b. rai se b. whatever c. are raisin g c. ones d. had been raised d. one 2. a. themselves 5. a. When b. it b. If c. them c. On condition d. us d. Providing 3. a. Unle ss b. In case c. Whether d. Even if units 17-21 Revision Test 05 I Grammar Practice A Choose the correct answers. 1. _ he has a car, he hardly ever drives it. a. Although b. Despite c. No matter d. However 2. _ her brave effort, she never made it to the final round. a. While b. Even though c. Despite d. Whatever 3. She speaks to him as if she him for years. a. has known b. will know c. is known d.knew 4. I wish you walk so fast. I can't keep up with you. a. wouldn't b. couldn't c. shouldn't d. mustn't 5. Lisa would rather in tonight. She doesn't feel like going out. a. be staying b. stay c. had stayed d. have been staying 6. My sister suggested away for the weekend. a. go b. going c. gone d. to be going 7. The painting is in the museum is really famous. a. whom b. whose c. that d. who 8. She fell down she was getting off the bus. a. until b. as c. after d. before 9. He that he would pick me up from work tomorrow. a. says b. is saying c. has been saying d. said 10. They've got a nice house, ? a. haven't they b. they haven't c. won't they d. have they B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. "Drop your gun at once!" the police officer shouted at the robber. ordered The police officer _ his gun at once. 2. "If only I could explain everything," she sighed. wished She _ everything. 3. Is the castle open to visitors? know Do you _ open to visitors? 4. I finished reading the book and then I went to bed. until I didn't go to bed _ the book. 5. That man stole the woman's purse and he is now leaving the shop. that The the shop stole the woman's purse. _________________________________________ page 183 I Vocabulary Practice A Choose the correct answers. 1. Alice recentl y a lot of weight. a. put aside b. put on c. put up d. put out 2. She always gets when speaking in fron t of a large group of people. a. nervous b. mad c. wild d. irritable 3. She was of her horrible behaviour. a. timid b. embarassed c. shy d. ashamed 4. Why don't you those new trousers I bought you? a. try in b. try out c. tryon d. try up 5. He ran and hid behind a tree in order to be _ a. out of reach b. out of danger c. out of control d. out of breath 6. You must first the water before adding the rice . a. fry b. bake c. roas t d. boil b. debate d. dialogue 8. He a small bird with the car. a. ran away b. ran int o c. ran out of d. ran over 9. Can you please the clothes that are on the bed? a. wrap b. fold c. tie d. fas ten 10. I John as one of my closest friends. a. think b. consider c. suppose d. regard B Complete using the correct form of the words in bold type. 1. _ _ _____ __ is the pri mary concern of our automobile company. SAFE 2. He leads a very lifestyle. HEALTH 3. Put your at the bottom of the page. SIGN 4. Do you have heating in your flat? CENTRE 5. Japanese cars are said to be very _ RELY page 184 C Choose the correct answers. Suppose you lived in a small town, (1) you miss the city? Many people would rather live in the peaceful suburbs than deal with the crowded, noisy streets of the cit y. At least that's what I thought. I had lived in New York City for 3 years, and after a while, I couldn' t (2) the noise and pollution. It was causing me to be a very (3) person. So, I considered the option of moving to the suburbs. Now, after five years of living away from the city, I kind of miss it. I've got a new neighbour (4) just moved from the city. She says that she misses the city too sometimes. So now, we arrange to go into the city every now and then. I guess you can' t have your cake and eat it too, (5) ? 1. a. could 4. a. who b. should b. which c. would c. of which d.do d. whose 2. a. put aside 5. a. do you b. put on b. can you c. put up c. shall you d. put up with d. can' t you 3. a. mad b. wild c. irrit able d. furious units 22-24 Revision Test 06 I Grammar Practice AChoose the correct answers. 1. People her always manage to get what they want. a. such b. like c. as d. except for 2. his behaviour, it is no wonder he was fired. a. Considering b. According to c. As a result d. Particul arl y 3. " I don 't like coffee" . " I , but I lik e tea." a. don 't ei ther b. neither don 't c. do too d. do so 4. Lisa had a headache, _ she de cided to stay in bed. a. not only b. but c. so d. besides 5. the film critic, the film is not wo rth watching. a. Regarding b. Concerning c. In contrast to d. According to 6. home, she reali sed she had left her house keys at work. a. To dri ve b. Dri ving c. She dri ves d. She drove 7. behind at work, he decided to stay late. a. To have fall en b. Having fell c. Having to fall d. Having fallen 8. No sooner had I opened the door the telephone began ringi ng . a. when b. until c. than d. but 9. The audience was utt erl y by the pl ay. a. boring b. bore c. bored d. a bore 10. She is rude and mean. I can' t understand wh y you' re fri ends with her. a. neither b. either c. both d. not only B Using the words given and other words, complete the second sentence so that it has a similar meaning to the first sentence. Do not change the word given. (Use 2-5 words in total.) 1. It is such a nice day tod ay! so It today! 2. He ne ver told me lies . once Not me lies. 3. Jason was the only person who didn't agree with the proposal. except Ev ery one with the proposal. 4. Sonia didn't enj oy he rsel f at the theatre, as the play made her feel rather depressed. was Son ia thought and didn't enjoy her sel f at the theatre. 5. One of the thin gs we still don't know is the time of the accident. occured What one of the things we still don't know. page 186 I Vocabulary Practice A Choose the correct answers. 1. He can 't cope all the workload. a. about b. with c. in d. for 2. Don't forget to a table for four for Friday evening. a. book b. hire c. reserve d. call 3. He was arrested murder. a. of b. by c. with d. for 4. Try not to more than one project at work. You'll get overwhelmed. a. take after b. take on c. take up d. take off 5. She her soda becau se she was thirsty. a. chewed b. swallowed c. gulped d. bit 6. Don't forget to the light s before you leave the house. a. tum up b. tum on c. tum off d. turn down 7. The little girl was on her way back from school and hasn't been seen since. a. robbed b. kidnapped c. stol en d. taken 8. How often do you at the gym? a. work out b. wear out c. wash up d. watch out 9. Even though everyone was panicking, he tried to keep the situation _ a. under pressure b. under arrest c. under the impression d. under control 10. I prefer to sit under the umbrella in the _ a. sunrise b. shadow c. shade d. sunlight B Complete using the correct form of the words in bold type. 1. The best again st weight gain is exercise. PREVENT 2. His death was a great for everyone. LOSE 3. In the , she didn 't like him. BEGIN 4. Sometimes you have to pay to the details. ATTEND 5. Documentaries can be very _ INFORM _________________________________________ page 187 C Choose the correct answers. Does your busy lifestyl e leave you feeling (1) ? A balanced diet can help you feel more energetic for longer. (2) what you may think, eatin g a wide variety of low-fat, high energy foods like fruit, vegetabl es and lean protein can help immensely. (3) eating right , it' s important to do things for yoursel f. (4) , after a tiring day at work, give your self a treat. Take a bubble bath, read, or listen to (5) music. Also, don't forget to get six to eight hours of sleep each night. And, most importantly, try to take it easy! 1. a. exhausted 4. a. However b. exhausting b. Not onl y c. being exhausted c. Parti cul arly d. exhaustion d. For instance 2. a. Althou gh 5. a. relaxation b. Despite b. relax c. Whatever c. relaxed d. Whereas d. relaxing 3. a. Also b. In addition to c. Especially d. In fact Final FeE Test I PART 1 For questions 1-12, read the text below and decide which answer (A, B, C or D) best fits each gap. Mark your answers on the separate answer sheet. A MEMORY My first day at school is a memory which will always stand (1) in my mind. I entered the gate and stared at the tall grey building. I put (2) my anxiety and kept walking. Students were talking to friends (3) they hadn't seen all summer. They briefly glanced my way, not paying (4) attention. I felt out of place, wishing I could be somewhere more familiar. Then the bell rang. It was time for me to go to class. I walked down the corridor, trying to balance the (5) of books I was holding and trying to lose myself in the (6) . I reached the classroom and took a deep breath. My mouth was dry. My heart pounding. I entered the room and all twenty-four pairs of eyes fell upon me, taking in every detail of my _________ (7) . I had never felt so uncomfortable in all my life. Someone called out, "Why do we always get the new teachers? They never know what they're doing!" he (8) . The comment made me feel even worse. I tried to remember all the things I had learnt during my training, (9) nothing came to mind. In practice, everything seemed different. I quickly had to think of something to (10) . In the end, I did. I don't really recall what, but somehow I _________ (11) to get through the lesson. I surely didn't (12) my reactions that first day at school. But looking back now, I can laugh about the whole thing. I suppose everyone goes through something like this on their first day at work. ANSWER SHEET 1 A by B out C up for D on [!] ABC D ==== 2 A aside B away C off D out ~ ABC D ==== 3 A whose B why C which D whom ~ ABC D ==== 4 A plenty B very C too D much ~ ABC D ==== 5 A heap B bundle C pile D bunch ~ ABC D ==== 6 A viewers B audience C spectators D crowd ~ ABC D === = 7 A image B picture C appearance D view [!] ABC D === = 8 A disapproved B blamed C accused D criticised ~ ABC D ==== ~ ABC D 9 A however B instead C despite D otherwise ==== ~ ABC D 10 A remark B speak C say D tell ==== ~ ABC D 11 A capable B managed Cable D succeeded ==== ~ ABC D 12 A wait B see C look forward D anticipate ==== _________________________________________ page 189 IPART 2 For questions 13-24, read the text below and think of the word which best fits each gap. Use only one word in each gap. Write your answers in capital letters on the separate answer sheet. FISH AND CHIPS Fried fish and chips, which happens (13) be a national food for the Britons, has been around (14) over 100 years. No one knows exac tly (1S) fish and chips came about; it's still a mystery. (16) , it is known that fried fish was ___ _ _ _ _ __(17) sale in the streets of London in the 1830s. Chips (18) thought to have been introduced in the 1870s. When fish and chip shops started, they spread quickl y and soon (19) an important part of worki ng-class life. (20) popul ar were they that you were sure to find a fish and chip shop on every second or third street corner in industrial towns. It was convenient, hot food and more importantl y, cheap. The fish and chips was always wrapped in newspaper in order to be kept warm on the (21) home. Today, fish and chips is still part of the Br itish culture and some families still have it for lunch or dinner. It ' s also a tourist attraction. Restaurant chains have been opened, (22) . They even wrap up the fish and chi ps in imi tation newspaper. However, this custom is under threat. More and more traditional fish and chip shops end (23) closi ng down (24) year. Wi ll this Bri tish custom slowly disappear? DO NOT ANSWER SHEET WRITEHERE ~ =13=1 [!!I 14 I == 15 I ~ == ~ = 16=1 ~ 17 I = = Q!] 18 I == [!![ 19 I == 20 I ~ = = 21 I ~ = = [E] ~ 2 = 1 23 I ~ == 24 I ~ == page 190 I PART 3 For questions 25-34, read the text below. Use the word given in capitals at the end of each line tQ form a word that fits in the gap in the same line. Write your answers in capital letters on the separate answer sheet. FLYING FISH It may seem (25) but some fish actuall y do fly. The y are fish of BELIEVE the Exocoetid ae family and are (26) found in. tropical waters. FREQUENT They have the (27) to travel up to 400 metres in the air, using ABLE their fins. Their (28) in and out of the water are very elegant. MOVE Why do they fly? Well, for their own (29). PROTECT It's a matter of (30) if they want to avoid predators like NECESSARY dolphins, in the water. (31) though, the safety the air offers is SURPRISE questionable, as (32) fish-eat ing birds may be flying overhead. THREAT And if the flying fish get really (33) , there is always the LUCK ____ _ _ _ __ (34) that a predator may be waiting at the landing point. POSSIBLE DO NOT ANSWER SHEET WRITE HERE 125 1=28= 1= 33= _________________________________________ page 191 I. I would really like to have a good relationship with my ANSWER SHEET parents, but I don't. got - - ------ - I wish my parents. 36. The puzzle was too difficult for anyone to solve. 136 bJ so The puzzle was could solve it. 37. I'd buy a car but I'm unemployed. -----'-------==-=:..=J out If! , I'd buy a car. 38. Today at Debbie was constantl y talking about her trip to Hungary. nothing Today at work, Debbie her trip to Hungary . ------'-------== = 39. I prefer to eat spicy food. preference I spicy food. 40. The workers demolished the old building on Parker Street yesterday. pulled The old building on Parker Street by the workers yesterday. 1 41. Ted finds it difficult to study more than four hours a day. [!!! 41 0 1 21 === used Ted more than four hours a day. 42. "Don't take the car because I need it," my brother said. told My brother the car because he needed it. Final ECCE Test I Grammar 1. Let me introduce you __ my husband Alex. a. at b. by c. to d. with 2. You should take an umbrella if it outside. a. is raining b. rained c. would rain d. will rain 3. My sister Jane is afraid I dogs. a. about b. of c. from d. with 4. He really wanted abroad during his senior year. a. study b. studied c. studying d. to study 5. "I just lost my job!" ''I'm so sorry _ a. to hear that b. that I heard c. for what I heard d. to have that heard 6. In the end, Sarah had our help . a. nothing to need of b. all need of c. little need of d. to need 7. It's always difficult deciding to cook for dinner. a. that's b. what c. not d. why 8. By the time you get my letter, 1 town . a. will leave b. am leaving c. had left d. will have left 9. Your test results should arrive day now. a. each b. on a c. any d. one 10. That's the couple for 1 sometimes babysit. a. who b. whom c. them d. what 11. Take a flashlight, you will not be able to see anything in the dark. a. unless b. otherwise c. however d. despite 12. "Do you want to come with us to the beach this weekend?" "I wish , but I have too much studying to do." a. I could b. I did c. I would d. I had 13. there before, I didn 't want to go again. a. To have been b. Because of being c. Having been d. To having been ------- page 193 14. You can borrow my car as long as you _ 21. We don't get visitors this time of year: drink and dri ve. a. often a. do not b. never b. will not c. sometimes c. can not d. rarely d. must not 22. I can't run you . 15. my alarm clock didn't ring, I woke up a. as fast as on time. b. so fast a. Despi te c. so faster that b. Despite of d. the fas ter of c. However d. Even though 23. He li ves in an apartment, is by the sea. a. it 16. She must be the most beautiful woman 1 _ b. tha t a. ever have seen c. what b. have never seen d. where c. have ever seen d. wi ll ever see 24. you say, I still wo n't bel ieve yo u. a. Forever 17. "I' rn really sleepy." b. However "So I. Le t's go to bed." c. W hatever a. do d. Wherever b. was c. did 25. Banks on public holi days. d. am a. are clos ed b. are closing 18. I hardly eat junk foo d. c. wi ll be cl osin g a. ever d. to be closed b. never c. rarely 26. Don' t he sitate to ca ll me _ of an emergency . d. rather a. provide d b. as long 19. I bought a dress the same color yours . c. thou gh a. of d. in case b. to c. as 27. I have very respect for people who litter. d. with a. a littl e b. little 20. "W here' s Lucy?" c. few "S he 's out _ d. a few a. shopping b. to shopping 28 . point in arguing. It 'll only make the c. go shopping si tuation worse. d. for shopping a. It' s no b. It isn' t c. There' s no d. There isn't page 194 29. I can't belive you've never heard __ Britney Spears! a. about b. off c. from d. of 30. Since they broke up, they've stopped _ each other. a. to call b. having called c. having to call d. calling 31. My brother is than me. a. much elder b. much older c. more older d. more old 32. You'll never believe who I ran _ at the supermarket! a. out b.up c. down d. into 33. Hardly when she told him to be quiet. a. he spoke b. he had spoken c. had he spoken d. has he spoken 34. " suitcase is this?" "It's Lena's." a. What b. Which c. Whom d. Whose 35. to being loud, he's also very rude. a. In addition b. In spite c. Even though d. Regardless I Vocabulary 36. I made a(n) with the doctor for 39. My friend Sally is to chocolate. She eats Wednesday afternoon. way too much of it! a. event a. obsessed b. meeting b. devoted c. date c. addicted d. appointment d. absorbed 37. The boss asked Allan to work overtime and he 40. I'll be out all afternoon running _ ____ accepted. a. tasks a. anxiously b. errands b ambitiously c. affairs c. carefully d. events d. willingly 41. He went down in history as a tyrant, 38. The crime he committed will cause him to spend the hated by all. rest of his life behind . a. merciful a. jail b. ruthless b. poles c. forgetful c. iron d. forgiving d. bars _________________________________________ page 195 42. Isn't there room for the suitcases in the ? a. hood b. trunk c. bumper d. dashboard 43. Mike, can I your car? Mine has broken down . a. borrow b. own c. rent d. get 44. The woman refused to the man's offer to drive her home. a. deny b. comply c. accept d. agree 45. The five star hotel on the beach is _ recommended. a. largely b. highly c. very d. a lot 46. That skirt is way too on me! a. tense b. tight c. hard d. tough 47. The slower you eat, the better you _ a. munch b. swallow c. snack d. digest 48. Laura took on the homeless man and gave him some change. a. shame b. sorrow c. pity d. grief 49. John his mother he would never lie to her again. a. determined b. reminded c. assured d. certified 50. That scene in the movie was so funny that the whole theatre into laughter. a. burst b. cried c. went d. dropped 51. Even if he worked all night, there was still no way he could meet the _ a. finish line b. timing c. end d. deadline 52. The of his house has risen greatly. a. value b. worth c. expense d. merit 53. I really can't the way he laughs. a. enjoy b. listen c. stand d. approve 54. Don't worry, we'll figure something out ; after all, where there is a there is a way. a. hope b. wish c. will d. desire 55. It took her years to her sister's death. a. go through b.puton c. give away d. get over 56. Did Elise decide to quit her job? a. definitely b. highly c. probably d. possibly 57. Can you please tell me if the price of the meal ____ tax? a. embodies b. holds c. consists d. includes page 196 58. My math test results were a real _ a. fight b. disaster c. tragedy d. battle 59. As I was walking down the street, I an old friend of mine. a. came up b. found out c. ran into d. gave up 60. The dress fits you perfectly, but I don't think the color you. a. matches b. suits c. goes d. looks 61. My teacher won 't be back from her until next Tuesday. a. trip b. excursion c. excavation d. travel 62. The man gave me a detailed of what happened on his trip. a. story b. interpretation c. account d. explanation 63. There was a en) on the elevator door saying that it was out of order. a. warning b. caution c. emergency d. notice 64. Despite its appearance, the plane was _ new. a. simply b. fairly c. deeply d. highly 65. An increasing number of credit card holders _ a. overpay b. overspend c. overprice d. overcharge 66. I goodbye as I dropped her off. a. showed b. turned c. pointed d. waved 67. He sat quietly the whole time and didn't a single word. a. yell b. shout c. utter d. murmer 68. Is there a reason you feel so ? a. red b. blue c. green d. white 69. Don't press that button! It will the alarm. a. ring b. load c. energize d. activate 70. After the play, the stood up and applauded. a. observers b. viewers c. audience d. listeners _________________________________________ page 197 Key to Revision Tests - la Vocabulary Practice Vocabulary Practice Vocabulary Practice A. A. A. 1. b 1. 1. b 1. a 2. c 2. d 2. c 3. a 3. b 3. b 4. c 4. c 4. d 5. d 5. d 5. b 6. c 6. b 6. a 7. c 7. b 7. c 8. b 8. c 8. a 9. d 9. b 9. d 10. b 10. a 10. b B. B. B. 1. performance 1. teacher 1. successful 2. viol ence 2. favourite 2. attr acti ve 3. behaviour 3. decisions 3. se nsitive 4. cur ios ity 4. professional 4. quali fi cati on s 5. tho ught 5. traditi onal 5. agree me nt c. C. C. 1. b 1. b 1. b 2. a 2. a 2. a 3. d 3. b 3. d 4. b 4. d 4. a 5. a 5. c 5. b 6. c REVISION TEST 1 REVISION TEST 2 REVISION TEST 3 Grammar Practice Grammar Practice Grammar Practice A. A. A. 1. a 1. c 1. c 2. b 2. b 2. a 3. c 3. a 3. c 4. d 4. d 4. d 5. a 5. c 5. a 6. c 6. a 6. c 7. a 7. c 7. d 8. b 8. a 8. c 9. b 9. d 9. b 10. c 10. a 10. c B. B. B. 1. does not go to 1. to ge t 1. a good actres s 2. am thinking of visiting 2. will try to be 2. oxen are used 3. had fin ished studyi ng by 3. left the house wi thout locking 3. is a weekl y 4. something ex plode d 4. will you help me 4. twi ce as far as 5. think it will rain 5. how about goi ng 5. wa sn 't so/ as int eresting as page 198 REVISION TEST 4 REVISION TEST 5 REVISION TEST 6 Grammar Practice Grammar Practice Grammar Practice A. A. A. 1. c 1. a 1. b 2. c 2. c 2. a 3. b 3. d 3. a 4. a 4. a 4. c 5. b 5. b 5. d 6. c 6. b 6. b 7. d 7. c 7. d 8. a 8. b 8. c 9. c 9. d 9. c 10. d 10. a 10. c B. B. B. 1. is said to be 1. ordered the robber to drop 1. is so nice (a day) 2. make yourself understood 2. wished she could explain 2. once did he tell 3. must be sent 3. know if the castle is 3. except (for) Jason agreed 4. you should see 4. until I (had) finished reading 4. the play was depressing 5. had his front teeth broken 5. man that is now leaving 5. time the accident occurred is Vocabulary Practice Vocabulary Practice Vocabulary Practice A. A. A. 1. c 1. b 1. b 2. b 2. a 2. c 3. d 3. d 3. d 4. b 4. c 4. b 5. a 5. b 5. c 6. c 6. d 6. c 7. a 7. a 7. b 8. b 8. d 8. a 9. d 9. b 9. d 10. b 10. d 10. c B. B. B. 1. normally 1. Safety 1. prevention 2. different 2. healthy 2. loss 3. darkness 3. signature 3. beginning 4. poisonous 4. central 4. attention 5. boredom 5. reliable 5. informative C. C. C. 1. a 1. c 1. a 2. c 2. d 2. b 3. d 3. c 3. b 4. d 4. a 4. d 5. b 5. b 5. d ______________________________________ page 199 • Key to Final FCE/ECCE Tests FCETEST Part I 1. B-out 2. A-aside 3. D-whom 4. D-much 5. C-pile 6. D-crowd 7. C-appearance 8. D-criticised 9. A-however 10. C-say 11. B-managed 12. D-anticipate Part 2 13. to 14. for 15. how 16. However 17. on 18. are 19. became 20. So 21. way 22. too 23. up 24. each/every Part 3 25. unbelievable 26. frequently 27. ability 28. movements 29. protection 30. necessity 31. Surprisingly 32. threatening 33. unlucky 34. possibility Part 4 35. I got on well with 36. so difficult that no one 37. wasn't/weren't out of work 38. did nothing but/except talk about 39. have a preference for 40 . was pulled down 41. is not used to studying 42. told me not to take ECCE TEST GRAMMAR 1. c 2. a 3. b 4. d 5. a 6. c 7. b 8. d 9. c 10. b 11. b 12. a 13. c 14. a 15. d 16. c 17. d 18. a 19. c 20. a 21. a 22. a 23. b 24. c 25. a 26.d 27 . b 28. c 29.d 30. d 31. b 32.d 33.c 34. d 35. a VOCABULARY 36.d 37.d 38.d 39.c 40 . b 41. b 42. b 43. a 44. c 45. b 46. b 47 .d 48 . c 49. c 50. a 51. d 52. a 53.c 54. c 55. d 56. a 57. d 58. b 59. c 60. b 61. a 62. c 63. d 64. b 65. b 66. d 67. c 68. b 69. d 70 . c SAMPLE COpy NOT FOR SALE Up er-Intermediate - 82 Teacher' Book Grammar & Vocabulary Practice systematically teaches grammar and vocabulary and helps students develop all skills necessary to succeed in the Revised Cambridge FCE Examination, the Michigan ECCE and other exams. The Student's Book includes: The Teacher's Book includes: • a variety of grammar and • The Student's Book vocabulary exercises with the Key overprinted • revision units and practice tests • Photocopiable tests • a glossary • appendices with prepositions, prepositional phrases and derivatives IS BN10:960-443-261-3 ISBN13 :978-960-443-261-S JUJl L615 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/doc/145557536/Grammar-and-Vocabulary
CC-MAIN-2016-50
refinedweb
84,686
84.37
How To Become An Android App Developer: Getting Started In Android Software Mobile App Development Making Android Apps If you are a complete beginner and haven't got the first clue about Android or Java development or any sort of computer programming, I recommend you take a look at 'How To Not Become An Android Developer' first, so that you know what to expect when setting up your development environment. On the other hand you could choose to go down the easy route and take heed of the advice in my article entitled 'How To Make Your Own Android Apps' - this is not recommended if you plan to take your Android software development to a professional standard, although the paid subscription plans do provide a very convenient and cost effective solution, considering the price of paying a professional Android app developer. Getting Started Android is based on Java, therefore in order to develop Android apps you will need a Java IDE (Integrated Development Environment). Most developers choose Eclipse as their IDE although JetBrains IntelliJ IDEA is another excellent IDE which I prefer to use myself. Once you have this software installed you are almost ready to start developing Java applications. However, first you also need to ensure that you have all the necessary Java utilities installed on your system. This means you will also need the Oracle Java SDK (Software Development Kit) and the Java Virtual Machine (JVM) also known as the Java Run-time Environment. Without the Java Virtual Machine your applications will be unable to run on your system. One you have the above software installed and have configured your system, this will then allow you to develop Java applications. However, in order to develop Android applications you need one more vital piece of software - the Android SDK. Alternatively, you may choose to develop your applications on your Android device which actually makes getting setting up a lot easier. In order to develop Android apps on your Android smartphone or tablet device you need just one piece of software called AIDE (Android Integrated Development Environment) which can be downloaded from Google Play (Android Market). By developing directly on your Android device you will also have the advantage of being able to test your apps without having to set up a virtual device (emulator), as you would on a PC. Creating A New Project When you create a new Android project in your IDE, the project will automatically be given the correct folder/file structure which should look similar to the image on the right. In order to develop your first Android project you will need to understand what the files/folders are there for. For your first project you will mainly need to concentrate on the 'res' folder, the 'src' folder and the AndroidManifest.xml file. The 'res' folder: This is where your resources go. Generally this will be things like page layouts, global string data (more on this later) and user interface. All these files are stored in XML format. The 'src' folder: This is the folder where all the Java source files (known in Java as activities) are stored. This is where the underlying Java code of your Android app will be stored; the code that makes your app functional. The AndroidManifest.xml file: You may have noticed that whenever you install an Android application on your device, the app tells you what permissions it requires before being installed. Any permissions required by your application must be declared in the AndroidManifest file. In addition, whenever your app uses an intent (more on this later), an intent filter must also be declared in the AndroidManifest file. Developing Your First Android App After creating a new Android project, you should have been presented with a tab displaying the Java code contained within the MainActivity.java file. If you have not, then go into the 'src' folder and double-click on the MainActivity file so that the code is displayed. The code should look something like this: package com.companyname.appname import android.app.*; import android.os.*; import android.os.*; import android.view.*; import android.widget.*; public class MainActivity extends Activity { /** Called when the activity is first created. */ @override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } The only lines in the code that you really need to be concerned with at this point is the line that says: setContentView(R.layout.main); To explain, what this line does is set the layout of the MainActivity screen. The actual layout is stored in the main.xml file which is contained in the resources (res) folder. The 'R' which is referenced in the code refers to an automatically generated file that indexes all the resources that your application uses. The 'R' file should never be edited manually. The MainActivity java class is the screen that will first launch when your app is opened after being installed and is therefore often used as a splash screen. However, for the sake of this tutorial we will use the main.xml file as a user interface which displays upon launching the app. Creating The User Interface When your application is launched the information contained within the main.xml file is displayed on the screen. Go into the 'res' folder then the 'layouts' folder and double-click or open the 'main.xml' file so that a tab opens and/or the XML code displays on the screen. The main.xml file will contain code that looks something like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <TextView android: </LinearLayout> Notice that within the <TextView> tag, a string resource named 'hello' is called from the Strings.xml file which is stored in the 'values' folder. The 'values' folder is stored inside the 'res' folder. If we open up the Strings.xml file we can see a line of code that says something like: <string name="hello">Hello World, MainActivity!</string> So, essentially, when your app is launched the MainActivity file opens up and imports information from the main.xml file which then tells the activity to display the text which is stored in the "hello" string (ie "Hello World, MainActivity!"). If you changed the line of code to say: <string name="hello">This is my app</string> then the text "This is my app" would be displayed on the screen instead. A string is simply a way of storing information and can be named anything you choose. To create the user interface we are going to use three buttons which you will need to draw yourself - Start, Options and Quit. For the sake of learning you can use a program as simple as MSPaint if you wish. However, you will need to consider the fact that Android devices come in various sizes and screen resolutions and for this reason, inside the 'res' folder there are also folders named 'drawable-hdpi', 'drawable-ldpi' and 'drawable-mdpi'. As the folder names suggest, they are for high definition, low definition and medium definition images in order to cater for various screen resolutions. When you have finished drawing your three button images, save them as either JPG or PNG files and place a copy of each image in all three of the 'drawable' folders ensuring that the files names have the appropriate .JPG or .PNG file extension. Make sure to name the files start, options and quit. It should be pointed out that Java is case-sensitive so you should be extra careful when writing your code. Also, images should be of the highest resolution/size possible so that Android can cater better for the various device screen sizes when your app runs on them. Displaying your three button images on the opening screen of your app is simple. All you need to do is add the following code to the main.xml file: <ImageButton android: <ImageButton android: <ImageButton android: As you can probably see, the <ImageButton> tag sets the height and width of each button and the android:src command retrieves each button image from the relevant 'drawable' folder. Make sure to save your project. Upon running your application, as long as the above procedures have been followed correctly, your three image buttons will be displayed on the screen - Congratulations! However, your buttons are not yet operational... but you have learned how to display images and text. Making the buttons functional is actually slightly more complicated and needs a bit more explanation so I have explained how to make them functional in another article (see link below). Next: Making The Buttons Functional © 2012 Sparkster Publishing Pretty nice post for android development newbies, it will be great if you could share an article elaborating step by step process of setting up and configuring machine for android app development. Melissa hey man im really interested in this. can i really make an app from my android and will i need anything else for my computer. im looking for a new laptop asap. sparkster Can all of these tools be obtained FREE? And are there any special requirements for your computer development system? Thanks Excellent work sparkster. I would love to learn how to develop Android apps. I did read your article on how not to be a developer. After reading that I gave it more consideration. I will be on the look out for your other articles on Android. 8
https://hubpages.com/technology/Become-An-Android-Developer-Getting-Started-In-Android-App-Development
CC-MAIN-2017-47
refinedweb
1,566
52.49
I wanted to create something that took advantage of the 3d world available in Minecraft and decided to see if I could make some 3d fractals. Fractals are repeating patterns which when observed at different scales appear the same - I know that sounds like rubbish, but that's what they are! These are the 3d fractal tree's I created in Minecraft: This is what a 2d fractal tree looks like: I found some python turtle code to create the 2d tree at interactivepython.org/runestone/static/pythonds/Recursion/graphical.html: import turtle def tree(branchLen,t): if branchLen > 5: t.forward(branchLen) t.right(20) tree(branchLen-15,t) t.left(40) tree(branchLen-15,t) t.right(20) t.backward(branchLen) def main(): t = turtle.Turtle() myWin = turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") tree(75,t) myWin.exitonclick() main() Its recursive, which means that a function calls itself, so in the example above the tree() function calls itself passing a smaller and smaller branch until the branch gets smaller than 5 and the function doesn't call itself any more and exits. Recursion is the basis of all fractals, its how you get the repeating patterns. I modded this code to use my Minecraft Graphics Turtle and rather than create 2 branches each time the function is called it creates 4 branches - 2 facing north to south and 2 facing east to west. #Minecraft Turtle Example import minecraftturtle import minecraft import block def tree(branchLen,t): if branchLen > 6: if branchLen > 10: t.penblock(block.WOOD) else: t.penblock(block.LEAVES) #for performance x,y,z = t.position.x, t.position.y, t.position.z #draw branch t.forward(branchLen) t.up(20) tree(branchLen-2, t) t.right(90) tree(branchLen-2, t) t.left(180) tree(branchLen-2, t) t.down(40) t.right(90) tree(branchLen-2, t) t.up(20) #go back #t.backward(branchLen) #for performance - rather than going back over every line t.setposition(x, y, z) #create connection to minecraft mc = minecraft.Minecraft.create() #get players position pos = mc.player.getPos() #create minecraft turtle steve = minecraftturtle.MinecraftTurtle(mc, pos) #point up steve.setverticalheading(90) #set speed steve.speed(0) #call the tree fractal tree(20, steve) The other change I made was to change the block type so that the shorter branches (the ones at the top) are made of leaves and the ones at the bottom are made of wood. I created these on the full version of Minecraft using Bukkit and Raspberry Juice, so I could take hi-def pictures but the same code works on the raspberry pi. If you want to have a go, download the minecraft turtle code from github.com/martinohanlon/minecraft-turtle and run the example_3dfractaltree.py program: sudo apt-get install git-core cd ~ git clone cd ~/minecraft-turtle python example_3dfractaltree.py I also made a fractal tree made out of random colours, check out example_3dfractaltree_colors.py.
http://www.stuffaboutcode.com/2014/07/minecraft-fractal-trees.html
CC-MAIN-2017-17
refinedweb
503
67.65
Welcome to Infrastructure Week July 2018! New articles and tools every day this week. Everybody knows the netstat tool, but do you know these fun facts too? netstatis part of a package called net-toolswhich includes: arp hostname ifconfig ipmaddr iptunnel mii-tool nameif netstat plipconfig rarp route slattach statistics - what the heck is a plipconfig? Well, it optimizes the performance of your parallel port — I sure am glad my 2018 server with 288 cores and 8 TB RAM has plipconfig. - double fun fact: stackoverflow has zero questions about plipconfig— it must be a very intuitive and easy to use utility! - the net-toolscodebase was written in the mid 90s - meaning: pre-C99, probably by people who still didn’t even trust or believe in C89 yet. - 25 years later, the entire codebase still looks like dirty old C - plus it’s included by default on millions of machines - and, surprise!, the entire project ended up mostly abandoned - people are still trying to correct “90s dirty C” idioms in the code to this day - maint of the package is now seemingly just ad-hoc by OS package maintainers whenever they find a problem or modern Linux incompatibility TOC: and, as always, you can ignore all the hard work I put into this write up and just jump right to the code. What If We Replaced 90s C netstat With Python? We’re going to focus on one tool in the net-tools package: netstat. It’s full of poorly formatted code you’d be (hopefully) fired for if you wrote today, but we’ll cover that towards the end so people don’t get scared or scarred up front. netstat -nape netstat -p is one of its most useful features: it shows you which pid and process name is listening on a port. Example: netstat -nape |grep LISTEN It gives us all listening IP:Port combinations along with their pid and process names (scroll to the right where the style falls off). Unfortunately, we see some limitations: - look at the nginx process name: it’s nginx: master p netstathas a fixed-length 20 character buffer for process names. Thanks, 90s! - also, since the output is so short, you don’t get full paths. - any process by any user in any directory could call itself “sshd” and you wouldn’t notice the difference based on the extremely truncated output netstatprovides. - the output is wide. really wide. not very terminal friendly. - the output doesn’t appear to be ordered by anything useful? Not by pid, not by IP, not by port. - oh, and root. netstatmust be run as rootto generate the IP:Port to pid/name mappings. That’s not cool. Plus, the output has six columns we don’t care about! My first attempt at making the output more useful was: netstat --numeric-hosts --listening --program --tcp --inet --inet6 |awk '{if (NR > 2) {printf "%-4s %-20s served by %-20s\n", $1, $4, $7} }' | sort -k 5,5 -n: A little better! We are now sorted by pid and the bad columns are gone, but the process names are still truncated and netstat must still be run as root to generate them at all. Still not good enough for our needs though. It’s [Almost] Code Time Replacing netstat -p requires figuring out how netstat matches IP:Ports to pids and why it requires root to show the mapping. A quick look through the code tells us: netstatreads the pid mappings from /proc/[pid]/fd/*, but each of those directories requires rootpermission to enter (unless you own the pidyourself). - why? it’s a security issue to let anybody directly access the open FDs/inodes of any random process - but why must those directories be consulted? - Linux only exposes which pids are using which inodes as a /proc/symlink in those directories. There’s no other way to discover the mappings. - Those symlinks look like this ls -latrh /proc/*/fd/* l-wx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/3 -> /dev/kmsg lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/2 -> /dev/null lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/1 -> /dev/null lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/0 -> /dev/null lr-x------ 1 root root 64 Jul 11 18:33 /proc/1/fd/18 -> /run/utmp lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/39 -> socket:[14648] lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/38 -> socket:[878100] lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/37 -> anon_inode:bpf-prog lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/32 -> anon_inode:bpf-prog lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/31 -> anon_inode:bpf-prog lrwx------ 1 root root 64 Jul 11 18:33 /proc/1/fd/30 -> anon_inode:bpf-map lrwx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/9 -> /dev/kmsg lrwx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/8 -> anon_inode:[eventpoll] l-wx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/7 -> /dev/kmsg lrwx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/6 -> socket:[14675] lrwx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/5 -> socket:[14681] lrwx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/4 -> socket:[14679] lrwx------ 1 root root 64 Jul 11 18:33 /proc/408/fd/36 -> /var/log/journal/aa7c9b37491043cca93eed3d1d242ed6/user-1000.journal Each of those is a symlink where the link name itself tells you the actual inode used by the process. What use is an inode? Well, the inodes of each listening IP:Port socket are freely available to any user in /proc/net/{tcp,udp}{,6}. Here’s a sample of /proc/net/tcp: Don’t you like how they stopped naming columns towards the end? What are those extra 7 fields? Don’t you worry your pretty little head about it. Just let those fields be fields and you be you. Those IP addresses do look a bit off. Let’s ask Erlang to convert those hex IP addresses back into individual bytes for us: And, if you hadn’t guessed before, hex 0100007F is little endian 127.0.0.1. If we tell Erlang about the byte orientation up front, it can fix it for us: The port numbers are easy to decipher too (oddly, Linux provides the port numbers in network byte order while the IP addresses aren’t. thanks, Linux!): or if you are tired of Erlang: or if you want some Python flavor: whew, so now we know: - We can get every IP:Port active on the system, both incoming and outgoing, from: /proc/net/tcp /proc/net/udp /proc/net/tcp6 /proc/net/udp6 - We can pick listening addresses (using the st(ate) column) and save the inodecolumn. - We can read every open fd in the system by walking /proc/[pid]/fd/* - If a symlink points to a socket:[INODE], then - parse the symlink, extract the inode number, compare to our previously retrieved inode list from /proc/net/{tcp,udp}{,6}. - then we can read /proc/[pid]/cmdlinefor each pidwe matched to get the full command line (instead of being limited to a 20 character buffer like 90s netstat C code). - Finally, we can do any remaining formatting/sorting/filtering for presentation. We can do all those steps in Python easily, right? It’s walking some directories, matching some files against other files, then printing the output we actually want. Let’s do this. Intermission! Want more infrastructure content? Join our infrastructure mailing list right now! Now It’s Python Coding Time The netstat source uses C APIs for directory walking by: opendir(3)of /procto walk the pid directories - so, readdir(3)for each directory entry - if readdirreturns a pid directory, run another opendir()to walk the pid/fddirectory. - now readdir()again to walk the fd entries - then call readlink(3)trying to find socket:[INODE]entries. It’s a lot of system calls for file operations even though it’s running through procfs. We could copy the netstat algorithm exactly using Python’s os.walk() API. So, that’s what I did the first time through. I used os.walk() and it took 500ms to generate results (30x slower than old netstat, not cool). But, this is the future and we have better APIs: if we replace 20 lines of looping os.walk() code with one line of glob.glob("/proc/*/fd/*"), our runtime drops from 500ms to 70ms. Read Dem Files Even though we can get a nice quick file listing with globohmyglob! we still have to os.readlink() on every filename returned by the glob. create map of inode->list of pids Capturing every processes socket inode->pid mapping becomes: Note at the end how we append the pid to our map of inodes->[pid]. netstat -p doesn’t have the ability to show us every process listening on a socket, but with forking servers and perhaps even REUSEPORT, multiple processes can listen on the same socket, but you’d never realize that from reading netstat -p output. We’re already better than netstat — we can report the truth of our system instead of having our output lie to us because unmaintained C code from 1993 can’t handle the modern world. look up the command line for each pid Now, with our list of pids, we can look up each command line: i… i… inodes! Where did the inodes dict come from? We didn’t populate that yet! inodes was the result of parsing /proc/net/{tcp,udp}{,6}, which is as simple as: Simple enough? We also use functions ipv4() and ipv6() to parse the hex IPs from /proc/net to readable formats: def ipv6(addr): """ Convert /proc IPv6 hex address into standard IPv6 notation. """ # turn ASCII hex address into binary addr = codecs.decode(addr, "hex") # unpack into 4 32-bit integers in big endian / network byte order addr = struct.unpack('!LLLL', addr) # re-pack as 4 32-bit integers in system native byte order addr = struct.pack('@IIII', *addr) # now we can use standard network APIs to format the address addr = socket.inet_ntop(socket.AF_INET6, addr) return addr def ipv4(addr): """ Convert /proc IPv4 hex address into standard IPv4 notation. """ # Instead of codecs.decode(), we can just convert a 4 byte hex # string to an integer directly using python radix conversion. # Basically, int(addr, 16) EQUALS: # aOrig = addr # addr = codecs.decode(addr, "hex") # addr = struct.unpack(">L", addr) # assert(addr == (int(aOrig, 16),)) addr = int(addr, 16) # system native byte order, 4-byte integer addr = struct.pack("=L", addr) addr = socket.inet_ntop(socket.AF_INET, addr) return addr And we’re done! We now have a dict called inodes containing every listening IP:Port on our system. All that’s remaining is to draw the rest of the fscking owl format it how we want, which gives us: Proto Listening PID Process udp 192.168.122.10:bootpc 441 /lib/systemd/systemd-networkd tcp 127.0.0.53:domain 493 /lib/systemd/systemd-resolved udp 127.0.0.53:domain 493 /lib/systemd/systemd-resolved tcp 192.168.122.10:ssh 579 /usr/sbin/sshd -D udp 127.0.0.1:323 581 /usr/sbin/chronyd udp6 ::1:323 581 /usr/sbin/chronyd tcp 158.69.158.251:http 620 nginx: master process /usr/sbin/nginx -g daemon on; 2893 nginx: worker process 2894 nginx: worker process 2895 nginx: worker process 2896 nginx: worker process tcp 158.69.158.251:https 620 nginx: master process /usr/sbin/nginx -g daemon on; 2893 nginx: worker process 2894 nginx: worker process 2895 nginx: worker process 2896 nginx: worker process tcp 0.0.0.0:smtp 908 /usr/lib/postfix/sbin/master -w 11580 smtpd -n smtp -t inet -u -c -o stress= -s 2 tcp6 :::smtp 908 /usr/lib/postfix/sbin/master -w 11580 smtpd -n smtp -t inet -u -c -o stress= -s 2 tcp 127.0.0.1:epmd 968 /opt/otp/17.5/erts-6.4/bin/epmd -daemon tcp 127.0.0.1:7781 987 /opt/otp/17.5/erts-6.4/bin/beam.smp -- -root /opt/ tcp 127.0.0.1:40001 987 /opt/otp/17.5/erts-6.4/bin/beam.smp -- -root /opt/ tcp 127.0.0.1:8888 1029 /opt/otp/17.5/erts-6.4/bin/beam.smp -- -root /opt/ tcp 127.0.0.1:40002 1029 /opt/otp/17.5/erts-6.4/bin/beam.smp -- -root /opt/ tcp 127.0.0.1:7780 8445 /opt/otp/17.5/erts-6.4/bin/beam.smp -- -root /opt/ tcp 127.0.0.1:40000 8445 /opt/otp/17.5/erts-6.4/bin/beam.smp -- -root /opt/ oooooh so pretty! no unnecessary columns, sorted by primary pid number, reports multiple listeners controlling one socket… Plus: colors! We’re using blue for private/local IPs and red for other. Double Plus: terminal-width aware printing so we never wrap lines! But, sadly, because of Linux design choices, the only place we can discover the pid mappings is by running as root to read /proc/[pid]/fd/* entries. How can we get around such a restriction so everybody can run the netstat of the people? seizethemeansofnetstatting! Let’s Make A Module The problem with finding system-wide inode to pid mappings is simple: Linux never created an interface to discover them without opening O(N) directories and reading symlink targets of O(k) files. Oh, and those directories can only be opened by root or the process owner. Whoops. But, just because Linux never created such an interface doesn’t mean we can’t create one for ourselves! Let’s write a simple Linux kernel function to list every inode belonging to every pid: The code prints a line of {pid} {short process name} {inodes*} for each task/pid on the system. We run our function by turning it into a Linux kernel module using both the simplified seq_file and procfs APIs to: - create an entry in /proc - tell Linux how to run our function when anybody reads /proc/pid_inode_map static int pid_inode_map_open(struct inode *inode, struct file *file) { return single_open(file, generate_mapping, NULL); } static const struct file_operations ops = {.owner = THIS_MODULE, .open = pid_inode_map_open, .read = seq_read, .llseek = seq_lseek, .release = single_release}; int __init pid_inode_map_init(void) { proc_create("pid_inode_map", 0, NULL, &ops); return 0; } Load Module, See Results! After loading the module, cat /proc/pid_inode_map shows lines like: With our custom mapping of pids to their inodes, we can adjust the netstat replacement to take advantage of one-stop- shopping-mapping. Replacing glob with Custom Proc Parsing Let’s read /proc/pid_inode_map once instead of parsing O(N*k) symlinks: We save thousands of system operations by generating one file any user can read instead of needing root to go through every fd of every process. Our approach of parsing a pre-generated file at /proc/pid_inode_map is 40% faster than iterating all the pids and fd symlinks every time we want a network status. Hey Linux, give us a built-in pid to inode mapping by default! Code for all the Python scripts plus the Linux kernel module is at mattsta/netmatt. C Thy Shame Jumping back a bit, let’s look at some netstat.c code. Code has not been modified to protect the guilty. It actually is formatted like this. This is in netstat.c still shipping in your Linux net-tools package in 2018: Did you notice the excerpt has an unterminated while loop? Do you see it? If you want to follow along at home, you can get the source with apt-get source net-tools. What if I spend 0.03 seconds to run it through modern automated formatting tools? 90s C code has plenty of weird properties, but the strangest is an absolute refusal to use proper indentation combined with a massive lack of visual whitespace. Though, even in 2018 backwards people still argue “brevity” is the highest form of coding. Never write in 4 lines what you can technically manipulate your compiler into accepting as 1 line, even if you just remove all the whitespace and brackets and indentation. We call these people CDs (C Dolts) and they should be monitored carefully to minimize ongoing damage to the time stream. Making 90s C code is easy: - cram everything close together - align most everything to the left with no indentation - never — never! — use brackets if your if, for, or whileonly has one result statement - as a bonus, lie using indentation about what your ifdoes, like the inexcusably bad if (lnamelen == -1)statement below. - look, it has a ‘continue’ but then everything below is still indented like it applies to the if statement! Gotta love 25 year old abandoned code running on millions of machines around the world.; If your eyes haven’t exploded from code stress yet, count the unterminated flow control statements. Do you see? Let’s clean this up again using 0.03 seconds of automated tooling:; } In the original code section, did you notice if (!cmdlp) { was unterminated? No, you didn’t notice, because they refused to use indentation in 1993 and nobody has fixed it in the subsequent 25 years. 90s C is basically the pinnacle of the Write Once, Read Never Again coding movement and must be ridiculed at all costs. Riddikulus! Conclusion What did we learn today? netstatis part of net-tools net-toolsis a mostly abandoned set of Linux utilities from the mid 90s - Linux doesn’t let non- rootusers discover pidto [inodes]metadata netstatactually under-reports which pids own which sockets netstatonly lists one pid even though sockets can be owned by multiple pids - But we can write a Linux kernel module to generate the mapping anyway! seizethemeansofnetstatting! - The 90s Linux utility C code is awful and needs to be either adopted and completely re-formatted, re-reviewed, and brought up to modern standards, or outright abandoned. - We can write much safer system utilities in Python - they are fast enough - they are safe enough - they are readable enough - and doggone it, people like me. -Matt — @mattsta — ☁mattsta Still want more infrastructure content? Join our infrastructure mailing list right now! Really do it this time! If you liked the C teardown, you’ll love our new series: Your Code Is Bad And You Should Feel Bad. Get pre-release announcements by signing up here: Stay tuned for more Infrastructure Week July 2018! New articles and tools every day this week.
https://www.tefter.io/bookmarks/85721/readable
CC-MAIN-2019-47
refinedweb
3,126
62.88
timer_getoverrun, timer_gettime, timer_settime - per-process timers [CX] #include <time.h> -1-2008 , timer_create XBD <time.h> First released in Issue 5. Included for alignment with the POSIX Realtime Extension. The timer_getoverrun(), timer_gettime(), and timer_settime() functions are marked as part of the Timers option. The [ENOSYS] error condition has been removed as stubs need not be provided if an implementation does not support the Timers option. The [EINVAL] error condition is updated to include the following: "and the it_value member of that structure did not specify zero seconds and nanoseconds." This change is for IEEE PASC Interpretation 1003.1 #89. The DESCRIPTION for timer_getoverrun() is updated to clarify that "If no expiration signal has been delivered for the timer, or if the Realtime Signals Extension is not supported, the return value of timer_getoverrun() is unspecified". The restrict keyword is added to the timer_settime() prototype for alignment with the ISO/IEC 9899:1999 standard. IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/140 is applied, updating the ERRORS section so that the mandatory [EINVAL] error (``The timerid argument does not correspond to an ID returned by timer_create() but not yet deleted by timer_delete()") becomes optional. IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/141 is applied, updating the ERRORS section to include an optional [EINVAL] error for the case when a timer is created with the notification method set to SIGEV_THREAD. APPLICATION USAGE text is also added. The timer_getoverrun(), timer_gettime(), and timer_settime() functions are moved from the Timers option to the Base. Functionality relating to the Realtime Signals Extension option is moved to the Base. return to top of pagereturn to top of page
https://pubs.opengroup.org/onlinepubs/9699919799.2008edition/functions/timer_gettime.html
CC-MAIN-2021-39
refinedweb
280
56.86
Grial UI Kit: Building Beautiful Xamarin.Forms Apps, Faster Leonardo This post was guest authored and contributed by Leonardo Viacava. Leo is co-founder and CTO of UXDivers, creators of Grial UI Kit and Gorilla Player. UXDivers specializes in designing and coding engaging mobile experiences using Xamarin technologies. Grial UI Kit Grial UI Kit provides XAML templates, custom controls, helpers and resources that accelerate the creation of Xamarin.Forms apps. We make it dead simple for .NET developers to build beautiful cross-platform apps, fast. Let’s take a look at how Grial UI Kit can help you build a great app. Below you can see an overview of the screens for a Tea Shop app called Clayton. The app took us 20 minutes to build, this blog took us much longer to write 🙂 After you read this blog, watch this video to see the complete process described below at normal speed. Creating a Beautiful App in Minutes Creating the App Grial based apps are created with our Grial Wb Admin site, which allows you to create and manage your apps. There are 5 simple steps to create your app: - Register your App. Select your license and create the app. - App Name. Give your app a name 🙂 - Project Setup. Enter the solution name, project name, namespace, assembly name and bundle identifier. All of these are auto-suggested based on the app name. - Screens. Choose any, and as many, screens from our 90+ cataloge to kick start your app. - Icon and Theme. Upload a high-resolution image of your app icon. Grial Wb Admin automatically generates all the required icon resolutions for iOS and Android. Select a theme to use. You can use the theme as it is, or choose to customize its accent color to match your brand’s look and feel. Now, you can download the Visual Studio solution ready to run, and you can start working on your app. The downloaded Grial solution uses your specified names, app icon and theme. It includes all your selected screens plus any accessory views used by those screens. You can add more screens later if you need to. Watch it in Action Watch the video below to see the 5 steps wizard creation process using Grial Web Admin and the download and running of the Clayton app with Visual Studio. Downloading the Solution The downloaded Visual Studio solution includes: - XAML files for the selected screens and all accessory views - The App Theme - A View Model for each page - Sample data in JSON format - All helpers/resources required by the app to work The solution also references a NuGet package called UXDivers.Grial that contains Grial custom controls, effects, custom renderers, and more. It also includes other popular community NuGet packages (e.g. Xamarin.Essentials, Xamarin.FFImageLoading, Newtonsoft.Json). In the video, the downloaded app uses a master-detail navigation that includes a link for each page. You can tweak the code to add or remove links. Using Gorilla Player The options to customize your app pages are endless. You can remove or add sections, create new ones by combining parts of existing ones, or just keep them as they are. Preview your XAML file customizations instantly using Grial’s best friend: Gorilla Player (pre-configured for all Grial apps, read more about Gorilla in this previous post). A note on Data: Grial pages have no hardcoded data, all data comes from View Models through data bindings. The View Models read Grial’s sample data from JSON files, which means manipulating the data of your prototypes is super easy. Once the prototype is ready, connect the View Models to the real data source with no impact to the XAML code of your pages. Customizing the App Watch the video below to see how we used Gorilla Player to customize the Clayton Tea Shop app. Note the following: - XAML customization. We customized (1) the e-commerce main page EcommerceMainPage, (2) the product detail page ProductDetailPageand (3) the walkthrough WalkthroughIllustrationPage. - The search bar from the navigation bar was removed and page title changed. - The product color picker was also removed as it did not apply to the Tea Shop domain. Page title was changed and other minor tweaks were made. - Adjusted images and texts. - Data manipulation. The DesignTimeData.jsonfile (where Gorilla Player stores its design-time data) was updated. Making the data for the e-commerce main page ( EcommerceMainPage) and the product detail page ( ProductDetailPage) relevant to the Tea Shop context. To get the running prototype as shown in the video, you also need to update the Grial JSON sample data files for the EcommerceMainPage. - Navigation. We removed the unnecessary screens from the master page by updating the MainMenuViewModelclass. Set the e-commerce main page ( EcommerceMainPage) as the app’s initial page. And used a modal page to display the introductory walkthrough ( WalkthroughIllustrationPage) right after the app starts. The image below gives an overview of the screens transformed by this first round of tweaks. Adding a New Functionality Let’s say you love green tea. How do you explore the full category without going into each item individually while still getting more product details than its name and photo? You add a See All button to the categories in the main page ( EcommerceMainPage) and a command to navigate to the ProductCatalogPage passing the correspondent category items. To tailor it further, we modified the XAML file of the list items template ( ProductsCatalogItemTemplate) to remove the Save/Compare/Share buttons, adjust the image aspect, and include the item’s price. Well… clearly there’s still work to do before you would consider the app done. For instance, some screens are missing and the View Models are reading sample data instead of data from a backend. In any case, what we wanted you to see is how fast you can build a beautiful, cross-platform app using Xamarin.Forms and Grial UI Kit. For a tour of the full 20 minutes process, at normal speed, check this video. Note: the videos show only the iOS app, but the Android app looks just as great. Grial UI Kit 3 Grial UI Kit 3 is the latest, and greatest version of Grial yet. With over 160 fully themeable, customizable and extensible XAML files, building beautiful Xamarin.Forms apps is now faster than ever. This version comes with: - 15 custom controls, including data grid, video player, tab control, card view, and checkbox. - Gradients support, everywhere. - Animations for a more engaging experience. - 6k scalable icons. - Responsive Helpers to simplify building multi-form factor layouts. - Built-in localization support, with instant runtime switch. - Right-to-Left support for all views, with instant runtime switch. - 6 predefined, yet customizable themes. - Fast project setup with Grial Web Admin. Learn More To learn more about Grial, please visit grialkit.com, for more technical and detailed information go to docs.grialkit.com. Download the Demo app, available in iOS and Android, to experience what you can build with Xamarin.Forms and Grial UI Kit. All the videos shown here are available in this playlist. We’d love to hear your feedback on Twitter @grialkit. Its a pitty, that it is way to expensive (for an indi dev).300$ for the “small” version if you want to develop and release an no-cost app is … well … not a good deal 🙁
https://devblogs.microsoft.com/xamarin/grial-ui-kit-xamarin-forms/
CC-MAIN-2021-10
refinedweb
1,223
65.32
Re: "Single sign on page doesn't look secure" --> well it isn't :> Bug Description So the new ubuntu came out (11.10) (well done!) and I decided to play with the new ubuntu store software manager program. So it turns out that previously a bug was reported saying that "Single sign on page doesn't look secure", https:/ I placed an entry in /etc/hosts to redirect login.ubuntu.com to the address of an ISP and attempted to "buy a piece of software" via the ubuntu software center ... well instead of viewing the login.ubuntu.com page I got the ISP's web page ... I haven't reviewed the code yet, but I doubt the code is doing sufficient ssl validation ... tldr: this is a bad thing because user's who expect to login to ubuntu safely(with ssl :) ) and buy software are at risk. Right, so my guess was correct ... I have described a basic test case for "compromising" a remote system below (by adding your own repository & new gpg key for apt to trust to a mitm'ed $victim). 1. point login.ubuntu.com at your local machine. 2. Adjust the contents in the file found under "FILE CONTENTS" below to fit with your pgp key, repository location and other respective fields. Then make the file available under the web root at /en/+openid/ FILE CONTENTS: --------------- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:// <html> <head> <title></title> </head> <body> <script type="text/ function changeTitle(title) { document.title = title; } function success() { changeTitle( function cancel() { changeTitle('{ "successful" : false }') } </script> <h1>Purchase test page</h1> <p> To buy Frobunicator for 99$ you need to enter your credit card info</p> <p> Enter your credit card info </p> <p> <input type="entry"> </p> <input type="button" name="test_button2" onclick= /> <input type="button" name="test_button" value="Buy now" onclick= /> <script> </body> </html> ------------ //The file contents is mostly a copy paste from the source code(of software center), except that I have added <script> 3. Try to "buy" some software from the ubuntu software center. Note: your user will be prompted to enter their password so as to install the "purchased software". The ppa information and corresponding pgp key will have been added under /etc/apt/ in the respective files. 4. ??? 5. :/ TLDR: The man in the middle flaw in the software-center package can be leveraged to "compromise" the system of an ubuntu user who is trying to buy software via the software-center. This shows (on the example url https:/ Here is what needs to be done to fix it for s-c only: === modified file 'softwarecenter --- softwarecenter/ +++ softwarecenter/ @@ -26,6 +26,10 @@ import sys import urllib from gi.repository import WebKit as webkit +# ensure we have a ssl-ca-file set, libsoup/webkit will *not* set this up +# automatically +session = webkit. +session. from gettext import gettext as _ But this really feels like it should be fixed on a libsoup level, not on a individual applications level. Fwiw, with the above I get a handshake error from the regular software- $ gnutls-cli --x509cafile /etc/ssl/ failing. Once that is fixed we can deploy the above fix for oneiric. Awesome! There appears to be no API to set the default soup session in python-webkit for natty and maverick. So either we need a ctypes based solution (I will look into that) or fix it at the libsoup level (which while I will lead to regressions would still prefer over fixing all individual applications). All fixes depend on that cert issue with gnutls mentioned in comment #5 for {software- I filed RT #48544 for the admins about this. Of course we need to inspect the other webkit/pywebkit using apps and ensure they setup libsoup correctly too. Please use CVE-2011-3150 for the issue in software-center. The gnutls-cli problem is now fixed, it turned out that it was a cert-chain ordering problem. Here is something that we should propose to upstream for P. I actually would really like to have it in a security update as well, but I can see that its controversial. At the same time IMO it simply does not make sense to have a settings "ssl-strict" and "ssl-ca-file" and only when settings the later the former is honored. I also think that ssl-strict and no ssl_ca_in_creds should be a failure, I will attach a seperate patch. This is a patch that forces ssl-strict to fail if the credentials can not be verified (i.e. missing cert). This is actually only needed when ssl-ca-file is NULL because with no ssl-ca-file the GTlsCertificate With the previous patch (that adds a default value to ssl-ca-file this should actually not be needed anymore. Having said that, I think ssl-strict==True and ssl-ca-file==NULL should simply be a failure (and this is what this patch archives). When are the various fixing going to be pushed out ? (soon I hope). s/fixing/fixes/ Hello David! Thanks for your question. I will leave the answer to this to the security team, AIUI they want to scan the archive for more users of webkit/webkitgtk that uses invalid ssl cert checking by default. The two other ones that come to my mind are the banshee and rythmbox amazon and ubuntuone store plugins. Both take credit card information so fixing them is also pretty important. Wouldn't the diff you attached above against libsoup fix the other issues? IMHO, I would like to see this fixed sometime within the next two weeks due to the nature of the bug. While leaking cc details is bad, it isn't as bad as code / repository injection. Hi David, Sorry for the delay in publishing this. We are currently investigating other applications that use SSL in the archive, and are finding more issues that are similar. Publishing this now will cause people to search for other applications that have similar issues, so we need to get them all fixed at the same time. This will take a while as in some cases, server side fixes are needed. Thanks for your comprehension in this matter. This bug was fixed in the package software-center - 5.0.2ubuntu0.1 --------------- software-center (5.0.2ubuntu0.1) oneiric-security; urgency=low * SECURITY UPDATE: MITM via incorrect ssl cert validation (LP: #874242) - softwarecenter/ libsoup property so ssl cert validation works. - CVE-2011-3150 -- Marc Deslauriers <email address hidden> Fri, 18 Nov 2011 08:29:21 -0500 Now that the update is out, any objections for trying to get my libsoup to upstream? Michael: No, please do! Okay, could anyone clarify what happened to the patch for libsoup? I'm wondering if we can expect libsoup to load CA files by default in the future, or if problems like this one in Software Center should be reported mercilessly until they're all fixed in their respective applications. Is there a separate bug report where people can track the API problem that mvo's patches cover? I need to confirm / check if this will give $man in the middle the ability to get remote code execution. From a quick review of the source code, it looks like this is possible ... (see softwarecenter/ ui/gtk3/ views/purchasev iew.py) .
https://bugs.launchpad.net/ubuntu/+source/software-center/+bug/874242
CC-MAIN-2019-47
refinedweb
1,225
62.27
Erigon Erigon is an implementation of Ethereum (aka “Ethereum client”), on the efficiency frontier, written in Go. NB! In-depth links are marked by the microscope sign (🔬) Disclaimer: this software is currently a tech preview. We will do our best to keep it stable and make no breaking changes but we don’t guarantee anything. Things can and will break. 🔬 Alpha/Beta versions difference: here System Requirements For an Archive node of Ethereum Mainnet we recommend >=3TB storage space: 1.8TB state (as of March 2022), 200GB temp files (can symlink or mount folder <datadir>/etl-tmpto another disk). Ethereum Mainnet Full node (see --prune*flags): 400Gb (April 2022). Goerli Full node (see --prune*flags): 189GB on Beta, 114GB on Alpha (April 2022). BSC Archive: 7TB. BSC Full: 1TB. Polygon Mainnet Archive: 5TB. Polygon Mumbai Archive: 1TB. SSD or NVMe. Do not recommend HDD – on HDD Erigon will always stay N blocks behind chain tip, but not fall behind. Bear in mind that SSD performance deteriorates when close to capacity. RAM: >=16GB, 64-bit architecture, Golang version >= 1.18, GCC 10+ 🔬 more details on disk storage here and here. Usage Getting Started git clone --recurse-submodules -j8 cd erigon make erigon ./build/bin/erigon Default --snapshots=true for mainnet, goerli, bsc. Other networks now have default --snapshots=false. Increase download speed by flag --torrent.download.rate=20mb. 🔬 See Downloader docs Use --datadir to choose where to store data. Use --chain=bor-mainnet for Polygon Mainnet and --chain=mumbai for Polygon Mumbai. Modularity Erigon by default is “all in one binary” solution, but it’s possible start TxPool as separated processes. Same true about: JSON RPC layer (RPCDaemon), p2p layer (Sentry), history download layer (Downloader), consensus. Don’t start services as separated processes unless you have clear reason for it: resource limiting, scale, replace by your own implementation, security. How to start Erigon’s services as separated processes, see in docker-compose.yml. Optional stages There is an optional stage that can be enabled through flags: --watch-the-burn, Enable WatchTheBurn stage which keeps track of ETH issuance and is required to use erigon_watchTheBurn. Testnets If you would like to give Erigon a try, but do not have spare 2TB on your drive, a good option is to start syncing one of the public testnets, Görli. It syncs much quicker, and does not take so much disk space: git clone --recurse-submodules -j8 cd erigon make erigon ./build/bin/erigon --datadir goerli --chain goerli Please note the --datadir option that allows you to store Erigon files in a non-default location, in this example, in goerli subdirectory of the current directory. Name of the directory --datadir does not have to match the name of the chain in --chain. Mining Disclaimer: Not supported/tested for Polygon Network (In Progress) Support only remote-miners. - To enable, add --mine --miner.etherbase=...or --mine --miner.miner.sigkey=...flags. - Other supported options: --miner.extradata, --miner.notify, --miner.gaslimit, --miner.gasprice, --miner.gastarget - JSON-RPC supports methods: eth_coinbase , eth_hashrate, eth_mining, eth_getWork, eth_submitWork, eth_submitHashrate - JSON-RPC supports websocket methods: newPendingTransaction - TODO: - we don’t broadcast mined blocks to p2p-network yet, but it’s easy to accomplish - eth_newPendingTransactionFilter - eth_newBlockFilter - eth_newFilter - websocket Logs 🔬 Detailed mining explanation is here. Windows Windows users may run erigon in 3 possible ways: Build executable binaries natively for Windows using provided wmake.ps1PowerShell script. Usage syntax is the same as makecommand so you have to run .\wmake.ps1 [-target] <targetname>. Example: .\wmake.ps1 erigonbuilds erigon executable. All binaries are placed in .\build\bin\subfolder. There are some requirements for a successful native build on windows : - Git for Windows must be installed. If you’re cloning this repository is very likely you already have it - GO Programming Language must be installed. Minimum required version is 1.18 - GNU CC Compiler at least version 10 (is highly suggested that you install chocolateypackage manager – see following point) - If you need to build MDBX tools (i.e. .\wmake.ps1 db-tools) then Chocolatey package manager for Windows must be installed. By Chocolatey you need to install the following components : cmake, make, mingwby choco install cmake make mingw. Important note about Anti-Viruses During MinGW’s compiler detection phase some temporary executables are generated to test compiler capabilities. It’s been reported some anti-virus programs detect those files as possibly infected by Win64/Kryptic.CIStrojan horse (or a variant of it). Although those are false positives we have no control over 100+ vendors of security products for Windows and their respective detection algorythms and we understand this might make your experience with Windows builds uncomfortable. To workaround the issue you might either set exclusions for your antivirus specifically for build\bin\mdbx\CMakeFilessub-folder of the cloned repo or you can run erigon using the following other two options Use Docker : see docker-compose.yml Use WSL (Windows Subsystem for Linux) strictly on version 2. Under this option you can build Erigon just as you would on a regular Linux distribution. You can point your data also to any of the mounted Windows partitions ( eg. /mnt/c/[...], /mnt/d/[...]etc) but in such case be advised performance is impacted: this is due to the fact those mount points use DrvFSwhich is a network file system and, additionally, MDBX locks the db for exclusive access which implies only one process at a time can access data. This has consequences on the running of rpcdaemonwhich has to be configured as Remote DB even if it is executed on the very same computer. If instead your data is hosted on the native Linux filesystem non limitations apply. Please also note the default WSL2 environment has its own IP address which does not match the one of the network interface of Windows host: take this into account when configuring NAT for port 30303 on your router. Beacon Chain Erigon can be used as an execution-layer for beacon chain consensus clients (Eth2). Default configuration is ok. Eth2 relies on availability of receipts – don’t prune them: don’t add character r to --prune flag. However, old receipts are not needed for Eth2 and you can safely prune them with --prune.r.before=11184524 in combination with --prune htc. You must enable JSON-RPC by --http and add engine to --http.api list. (Or run the JSON-RPC daemon in addition to the Erigon) If beacon chain client on a different device: add --http.addr 0.0.0.0 (JSON-RPC listen on localhost by default) . Once the JSON-RPC is running, all you need to do is point your beacon chain client to <ip address>:8545, where <ip address> is either localhost or the IP address of the device running the JSON-RPC. Erigon has been tested with Lighthouse however all other clients that support JSON-RPC should also work. Authentication API In order to establish a secure connection between the Consensus Layer and the Execution Layer, a JWT secret key is automatically generated. The JWT secret key will be present in the datadir by default under the name of jwt.hex and its path can be specified with the flag --authrpc.jwtsecret. This piece of info needs to be specified in the Consensus Layer as well in order to establish connection successfully. More information can be found here Multiple Instances / One Machine Define 5 flags to avoid conflicts: --datadir --port --http.port --torrent.port --private.api.addr. Example of multiple chains on the same machine: # mainnet ./build/bin/erigon --datadir="<your_mainnet_data_path>" --chain=mainnet --port=30303 --http.port=8545 --torrent.port=42069 --private.api.addr=127.0.0.1:9090 --http --ws --http.api=eth,debug,net,trace,web3,erigon # rinkeby ./build/bin/erigon --datadir="<your_rinkeby_data_path>" --chain=rinkeby --port=30304 --http.port=8546 --torrent.port=42068 --private.api.addr=127.0.0.1:9091 --http --ws --http.api=eth,debug,net,trace,web3,erigon Quote your path if it has spaces. Dev Chain 🔬 Detailed explanation is DEV_CHAIN. Key features 🔬 See more detailed overview of functionality and current limitations. It is being updated on recurring basis. More Efficient State Storage Flat KV storage. Erigon uses a key-value database and storing accounts and storage in a simple way. 🔬 See our detailed DB walkthrough here. Preprocessing. For some operations, Erigon uses temporary files to preprocess data before inserting it into the main DB. That reduces write amplification and DB inserts are orders of magnitude quicker. 🔬 See our detailed ETL explanation here. Plain state. Single accounts/state trie. Erigon uses a single Merkle trie for both accounts and the storage. Faster Initial Sync Erigon uses a rearchitected full sync algorithm from Go-Ethereum that is split into “stages”. 🔬 See more detailed explanation in the Staged Sync Readme It uses the same network primitives and is compatible with regular go-ethereum nodes that are using full sync, you do not need any special sync capabilities for Erigon to sync. When reimagining the full sync, with focus on batching data together and minimize DB overwrites. That makes it possible to sync Ethereum mainnet in under 2 days if you have a fast enough network connection and an SSD drive. Examples of stages are: Downloading headers; Downloading block bodies; Recovering senders’ addresses; Executing blocks; Validating root hashes and building intermediate hashes for the state Merkle trie; […] JSON-RPC daemon Most of Erigon’s components (sentry, txpool, snapshots downloader, can work inside Erigon and as independent process. To enable built-in RPC server: --http and --ws (sharing same port with http) Run RPCDaemon as separated process: this daemon can use local DB (with running Erigon or on snapshot of a database) or remote DB (run on another server). 🔬 See RPC-Daemon docs For remote DB This works regardless of whether RPC daemon is on the same computer with Erigon, or on a different one. They use TPC socket connection to pass data between them. To use this mode, run Erigon in one terminal window make erigon ./build/bin/erigon --private.api.addr=localhost:9090 --http=false make rpcdaemon ./build/bin/rpcdaemon --private.api.addr=localhost:9090 --http.api=eth,erigon,web3,net,debug,trace,txpool gRPC ports 9090 erigon, 9091 sentry, 9092 consensus engine, 9093 torrent downloader, 9094 transactions pool Supported JSON-RPC calls (eth, debug , net, web3): For a details on the implementation status of each command, see this table. Run all components by docker-compose Docker allows for building and running Erigon via containers. This alleviates the need for installing build dependencies onto the host OS. Optional: Setup dedicated user User UID/GID need to be synchronized between the host OS and container so files are written with correct permission. You may wish to setup a dedicated user/group on the host OS, in which case the following make targets are available. # create "erigon" user make user_linux # or make user_macos Environment Variables There is a .env.example file in the root of the repo. DOCKER_UID– The UID of the docker user DOCKER_GID– The GID of the docker user XDG_DATA_HOME– The data directory which will be mounted to the docker containers If not specified, the UID/GID will use the current user. A good choice for XDG_DATA_HOME is to use the ~erigon/.ethereum directory created by helper targets make user_linux or make user_macos. Check: Permissions In all cases, XDG_DATA_HOME (specified or default) must be writeable by the user UID/GID in docker, which will be determined by the DOCKER_UID and DOCKER_GID at build time. If a build or service startup is failing due to permissions, check that all the directories, UID, and GID controlled by these environment variables are correct. Run Next command starts: Erigon on port 30303, rpcdaemon on port 8545, prometheus on port 9090, and grafana on port 3000. # # Will mount ~/.local/share/erigon to /home/erigon/.local/share/erigon inside container # make docker-compose # # or # # if you want to use a custom data directory # or, if you want to use different uid/gid for a dedicated user # # To solve this, pass in the uid/gid parameters into the container. # # DOCKER_UID: the user id # DOCKER_GID: the group id # XDG_DATA_HOME: the data directory (default: ~/.local/share) # # Note: /preferred/data/folder must be read/writeable on host OS by user with UID/GID given # if you followed above instructions # # Note: uid/gid syntax below will automatically use uid/gid of running user so this syntax # is intended to be ran via the dedicated user setup earlier # DOCKER_UID=$(id -u) DOCKER_GID=$(id -g) XDG_DATA_HOME=/preferred/data/folder DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 make docker-compose # # if you want to run the docker, but you are not logged in as the $ERIGON_USER # then you'll need to adjust the syntax above to grab the correct uid/gid # # To run the command via another user, use # ERIGON_USER=erigon sudo -u ${ERIGON_USER} DOCKER_UID=$(id -u ${ERIGON_USER}) DOCKER_GID=$(id -g ${ERIGON_USER}) XDG_DATA_HOME=~${ERIGON_USER}/.ethereum DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 make docker-compose Makefile creates the initial directories for erigon, prometheus and grafana. The PID namespace is shared between erigon and rpcdaemon which is required to open Erigon’s DB from another process (RPCDaemon local-mode). See: If your docker installation requires the docker daemon to run as root (which is by default), you will need to prefix the command above with sudo. However, it is sometimes recommended running docker (and therefore its containers) as a non-root user for security reasons. For more information about how to do this, refer to this article. Windows support for docker-compose is not ready yet. Please help us with .ps1 port. Grafana dashboard docker-compose up prometheus grafana, detailed docs. Prune old data Disabled by default. To enable see ./build/bin/erigon --help for flags --prune How much RAM do I need - Baseline (ext4 SSD): 16Gb RAM sync takes 6 days, 32Gb – 5 days, 64Gb – 4 days - +1 day on “zfs compression=off”. +2 days on “zfs compression=on” (2x compression ratio). +3 days on btrfs. - -1 day on NVMe Detailed explanation: ./docs/programmers_guide/db_faq.md Default Ports and Protocols / Firewalls? erigon ports Typically, 30303 and 30304 are exposed to the internet to allow incoming peering connections. 9090 is exposed only internally for rpcdaemon or other connections, (e.g. rpcdaemon -> erigon). RPC ports Typically, 8545 is exposed only internally for JSON-RPC queries. Both HTTP and WebSocket connections are on the same port. Typically, 8551 (JWT authenticated) is exposed only internally for the Engine API JSON-RPC queries. sentry ports Typically, a sentry process will run one eth/xx protocol (e.g. eth/66) and will be exposed to the internet on 30303. Port 9091 is for internal gRCP connections (e.g erigon -> sentry). Other ports Optional flags can be enabled that enable pprof or metrics (or both) – however, they both run on 6060 by default, so you’ll have to change one if you want to run both at the same time. use --help with the binary for more info. Reserved for future use: gRPC ports: 9092 consensus engine, 9093 snapshot downloader, 9094 TxPool How to get diagnostic for bug report? - Get stack trace: kill -SIGUSR1 <pid>, get trace and stop: kill -6 <pid> - Get CPU profiling: add --pprof flagrun go tool pprof -png\?seconds\=20 > cpu.png - Get RAM profiling: add --pprof flagrun go tool pprof -inuse_space -png > mem.png How to run local devnet? 🔬 Detailed explanation is here. Docker permissions error Docker uses user erigon with UID/GID 1000 (for security reasons). You can see this user being created in the Dockerfile. Can fix by giving a host’s user ownership of the folder, where the host’s user UID/GID is the same as the docker’s user UID/GID (1000). More details in post Run RaspberyPI Getting in touch Erigon Discord Server The main discussions are happening on our Discord server. To get an invite, send an email to tg [at] torquem.ch with your name, occupation, a brief explanation of why you want to join the Discord, and how you heard about Erigon. Reporting security issues/concerns Send an email to security [at] torquem.ch. Team Core contributors (in alpabetical order of first names): Alex Sharov (AskAlexSharov) Alexey Akhunov (@realLedgerwatch) Andrea Lanfranchi(@AndreaLanfranchi) Andrew Ashikhmin (yperbasis) Artem Vorotnikov (vorot93) - Eugene Danilenko (JekaMas) Igor Mandrigin (@mandrigin) Giulio Rebuffo (Giulio2002) Thomas Jay Rush (@tjayrush) Thanks to: All contributors of Erigon All contributors of Go-Ethereum Our special respect and graditude is to the core team of Go-Ethereum. Keep up the great job! Happy testing! 🥤 Known issues htop shows incorrect memory usage Erigon’s internal DB (MDBX) using MemoryMap – when OS does manage all read, write, cache operations instead of Application (linux , windows) htop on column res shows memory of “App + OS used to hold page cache for given App”, but it’s not informative, because if htop says that app using 90% of memory you still can run 3 more instances of app on the same machine – because most of that 90% is “OS pages cache”. OS automatically free this cache any time it needs memory. Smaller “page cache size” may not impact performance of Erigon at all. Next tools show correct memory usage of Erigon: vmmap -summary PID | grep -i "Physical footprint". Without grepyou can see details section MALLOC ZONE column Resident Sizeshows App memory usage, section REGION TYPE column Resident Sizeshows OS pages cache size. Prometheusdashboard shows memory of Go app without OS pages cache ( make prometheus, open in browser localhost:3000, credentials admin/admin) cat /proc/<PID>/smaps Erigon uses ~4Gb of RAM during genesis sync and ~1Gb during normal work. OS pages cache can utilize unlimited amount of memory. Warning: Multiple instances of Erigon on same machine will touch Disk concurrently, it impacts performance – one of main Erigon optimisations: “reduce Disk random access”. “Blocks Execution stage” still does much random reads – this is reason why it’s slowest stage. We do not recommend run multiple genesis syncs on same Disk. If genesis sync passed, then it’s fine to run multiple Erigon on same Disk. Blocks Execution is slow on cloud-network-drives Please read In short: network-disks are bad for blocks execution – because blocks execution reading data from db non-parallel non-batched way. Filesystem’s background features are expensive For example: btrfs’s autodefrag option – may increase write IO 100x times Gnome Tracker can kill Erigon Gnome Tracker – detecting miners and kill them. the –mount option requires BuildKit error For anyone else that was getting the BuildKit error when trying to start Erigon the old way you can use the below… XDG_DATA_HOME=/preferred/data/folder DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 make docker-compose
https://golangexample.com/erigon-an-implementation-of-ethereum/
CC-MAIN-2022-40
refinedweb
3,096
54.93
A package for testing http clients on flutter or the Dart vm. The following example forces all HTTP requests to return a successful empty response in a test enviornment. No actual HTTP requests will be performed. class MyHttpOverrides extends HttpOverrides { HttpClient() createClient(_) { return new HttpTestClient((request, client) { // the default response is an empty 200. return new HttpTestResponse(); }); } } void main() { // overrides all HttpClients. HttpOverrides.global = new MyHttpOverrides(); group('HttpClient', () { test('returns OK', () async { // this is actually an instance of [HttpTestClient]. final client = new HttpClient(); final request = client.getUrl(new Uri.https('google.com')); final response = await request.close(); expect(response.statusCode, HttpStatus.OK); }); }); } Add this to your package's pubspec.yaml file: dependencies: http_test_client: ^0.0.1 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:http_test_client/http_test_client.
https://pub.dartlang.org/packages/http_test_client
CC-MAIN-2018-51
refinedweb
157
52.36
CSE-IT Contact Info Keller Hall - Room 1-201 Office Hours: M-F 8:00 AM - 5:00 PM 612-625-0876 csehelp@umn.edu Or use the red phone in the labs. CGI Tutorial and FAQ Writing Scripts Setting up a CGI script can be extremely frustrating. While the basic concepts are simple, there are many steps, and missing any of them will cause your CGI script to fail. The following steps should be sufficient to get your first CGI script up and running in your home directory. Note that this tutorial only covers getting a CGI script working in our environment. It doesn’t say anything about how one writes CGI scripts that do anything useful. Create your .www directory The first step is to check the permissions on your home directory and create a .www directory within it. Read Create Your .www Directory to do this. Create your CGI script Now that your .www directory has been created and you have set the permissions correctly, it’s time to create your first CGI script. To do this, open a text editor (pico, vi, emacs, xemacs, etc.) and copy and paste the code found in one of the examples found below (use one of the examples in the language you plan to write your future CGI programs). For example: % cd ~/.www % pico test-cgi.cgi This will call up the pico text editor and allow you to enter your CGI script. Please note, you can use any text editor to create the test file, e.g. xemacs, emacs, vi, etc. Example Code Python #!/soft/python-2.7/bin/python import cgi import cgitb cgitb.enable() # for troubleshooting #print header print "Content-type: text/html" print print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" print "<!DOCTYPE html>" print "<html>" print "<head>" print "<title>Python CGI test</title>" print "</head>" print "<body>" print "<p>Hello, world!</p>" print "</body>" print "</html>" Perl #!/usr/bin/perl -w use CGI; $cgi = new CGI(); print $cgi->header(); print '<?xml version="1.0" encoding="UTF-8"?>'; print '<!DOCTYPE html> <html> <head> <title>Perl CGI test</title> </head> <body>'; print ' <p> Hello world! </p>'; print ' </body> </html> '; Ruby #!/usr/bin/ruby puts "Content-type: text/html" puts puts "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" puts "<!DOCTYPE html>" puts "<html>" puts "<head>" puts "<title>Ruby CGI test</title>" puts "</head>" puts "<body>" puts "<p>Hello, world!</p>" puts "</body>" puts "</html>" Bash #!/bin/bash echo "Content-type: text/html" echo "" echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE html> <html> <head> <title>Bash CGI test</title> </head> <body> <p> Hello World! </p> </body> </html>" Once the code has been copied to your text editor, save the file and exit. Set file permissions Before you can run your cgi script, you need to set the permissions so that it is executable, otherwise you will get an error % chmod 700 test-cgi.cgi Test your CGI scripts Now that you have created your CGI scripts, it is time to test them. Point your favorite web browser at the following URL:<your_username>/test-cgi.cgi If you get an Internal Server Error, double-check that you followed all the steps above. If you still can’t get it to work, contact Systems Staff. Disclaimer Policy University of Minnesota policy requires that the following disclaimer appear on all personal pages and on all student organization pages. It will be automatically appended to pages that you create: "The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota." Note: Make sure that your CGI scripts and the directories that your CGI scripts are in are not group or world writable, otherwise our server will not execute them. For security reasons you should never make your files or directories world writable and you should have a good understanding of the security implications before you make any files or directories group writable. This is especially true of web-accessible files and directories. Do the owner and group of my CGI script matter? Yes! - The CGI script and the enclosing directory must be owned by you. - The group of the file and the enclosing directory must be the same as your default group. To find your default group use the id command. The value returned for gid will be your default group. (number and name) Failing to set the owner and group correctly will result in an Internal Server Error. How can I tell if my CGI script is producing the correct output? Run your script from the command line. Simply cd to the directory containing the script, and type ./<scriptname.cgi>, where <scriptname.cgi> is the name of your CGI script. The first line of output returned should be: Content-Type: text/htm followed by a newline and then the output of your script. If the above line is not produced, or it's not followed by a blank line and then some content, an Internal Server Error will be displayed. Also, you might find that the script produces the following prompt when you run it: (offline mode: enter name=value pairs on standard input) If this happens, type control-D and the output of the script will be displayed. Where can I find the Apache error logs? Check the Apache Error Logs Page for information on where to find and how to access error logs. What else can I do if I'm still getting Internal Server Errors? Most CGI-related problems are caused by one of the above requirements not being met. Also, be sure to check the Apache Error Log to see what error message is being generated. If you have double-checked this page and you are still experiencing problems getting your scripts to run, contact Systems Staff. What do I do if I get an error when I try to run a script on my Windows computer? If you are trying to run a script on a Windows computer, you may get an error that looks similar to this: [date][error][client] suexec failure: could not open log file [date][error][client] fopen: Permission denied [date][error][client] Premature end of script headers: ruby.cgi First, Check to make sure you don't have any strange newlines. It could be that you have Windows newline characters that are causing problems. SSH to one of our Solaris machines and type the following command: % dos2unix <<file>> <<file>> This command will convert Windows newline characters to UNIX ones and clear up the error.
https://cseit.umn.edu/knowledge-help/cgi-tutorial-and-faq
CC-MAIN-2018-47
refinedweb
1,104
73.68
UID — Create unique identifier constants Version 0.24 (April 16, 2009) use UID "foo"; # define a unique ID use UID BAR=>BAZ=>QUX=>; # define some more print foo==foo; # true print foo==BAR; # false print foo=="foo"; # false do_stuff(foo 42, BAR "bar", BAZ "foo"); # similar to do_stuff(foo=>42, BAR=>"bar", BAZ=>"foo") # except the UID foo can be unambiguously distinguished from the string "foo" The UID module lets you declare unique identifiers — values that you can be sure will not be coincidentally matched by some other value. The values are not "universally" unique (UUIDs/GUIDs); they are unique for a single run of your program. Define the identifiers with " use UID" followed by one or more strings for the names of the IDs to be created. " use UID foo" will create a unique constant called foo that is a UID object: any value equal to foo must be foo itself (or a copy of it). No other UID (in the same process) will be equal to foo. UIDs can be compared to each other (or to other values) using either == or eq (or != or ne, of course). A typical use of UID objects is to form a named pair (like FOO=>42), but note that the pair-comma ( =>) implicitly quotes the preceding word, so FOO=>42 really means "FOO"=>42, using the string "FOO" rather than the UID FOO. However, a comma is not always needed; you can say simply FOO 42 and often get the same effect as FOO, 42. Here is an example that uses UIDs for the names of named parameters. Let's suppose we have a function ( do_stuff) that takes for its arguments a list of items to do stuff to, and an optional list of filenames to log its actions to. Using ordinary strings to name the groups of arguments would look something like this: do_stuff(ITEMS=> $a, $b, $c, $d, $e, FILES=> $foo, $bar); The function can go through all the args looking for our "ITEMS" and "FILES" keywords. However, if one of the items happened to be the string "FILES", the function would get confused. We could do something such as make the arguments take the form of a hash of array-refs (a perfectly good solution, albeit one that requires more punctuation). Or we could use UIDs (which actually allows for slightly less punctuation): use UID qw/ITEMS FILES/; do_stuff(ITEMS $a, $b, $c, $d, $e, FILES $foo, $bar); Now the function can check for the UID FILES unambiguously; no string or other object will match it. Of course, you can still use FILES where it doesn't make sense (e.g., saying do_stuff(ITEMS $a, FILES, $c, $d, FILES $foo, $bar); but you can't make something else that is intended to be different but that accidentally turns out to be equal to FOO. UIDs work by defining a subroutine of the given name in the caller's namespace. The sub simply returns a UID object. Any arguments that you feed to this sub are returned as well, which is why you can say FOO $bar without a comma to separate the terms; that expression simply returns the list (FOO, $bar). (However, beware of imposing list context where it's not wanted: FOO $bar puts $bar in list context, as opposed to FOO, $bar. Also, if you are passing UIDs as arguments to a function that has a prototype, a scalar prototype ( $) can force the UID to return only itself, and a subsequent arg will need to be separated with a comma.) These subroutines work very much as do the constants you get from use constant. Of course, this means that the names chosen must be valid symbols (actually, you can call things almost anything in Perl, if you're prepared to refer to them using circumlocutions like &{"a bizarre\nname"}!). A UID overloads stringification to return a value consisting of its name when used as a string (so use UID foo; print foo will display " «foo»"). You can also treat it as a scalar-reference to get a string with the fully-qualified name (that is, including the name of the package in which it lives: print ${+foo} # e.g. "«main::foo»"). The comparison operators == and eq and their negations are also overloaded for UID objects: comparing a UID to anything will return false unless both sides are UIDs; and if both are, their blessed references are compared. (Not the values the references are referring to, which are simply the UIDs' names, but rather the string-values of the refs, which are based on their locations in memory — since different references will always have different values, this guarantees uniqueness.) You tried to make a UID out of something like an array-ref or an object. The module is looking for a string or strings that it can define in your namespace, and will skip over this arg. A subroutine (or constant, or other UID, or anything else that really is also a sub) has already been declared with the given name. UID prevents you from redefining that name and skips over it. You put (what appear to be) arguments after a UID, but the UID is in scalar context, thus only a single value can be used (not the UID plus its arguments). The solution is probably to put a comma after the UID, or strategically place some parentheses, to separate it from the following item, rather than letting it take that item as an argument. You tried to operate on a UID with an operator that doesn't apply (which is pretty much all of them). UIDs can be compared with == or eq, but you can't add, subtract, divide, xor them, etc. No particular bugs are known at the moment. Please report any problems or other feedback to <bug-uid at rt.cpan.org>, or through the web interface at. Note that UIDs are less useful for hash keys, because the keys have to be strings, not objects. You are able to use a UID as a key, but the stringified value (its name) will actually be used (and could conceivably be accidentally duplicated). However, there are modules that can give you hash-like behaviour while allowing objects as keys, such as Tie::RefHash or Tie::Hash::Array or Array::AsHash. There are other places where Perl will want to interpret a UID (like any other sub name) as a string rather than as a function call. Sometimes you need to say things like +FOO or FOO() to make sure FOO is evaluated as a UID and not as a string literal. As mentioned, hash keys are one such situation; also => implicitly quotes the preceding word. Note that &FOO will work to force the sub interpretation, but is actually shorthand for &FOO(@_), i.e. it re-passes the caller's @_, which is probably not what you want. Comparing a UID to something else ( FOO==$something) will correctly return true only if the $something is indeed (a copy of) the FOO object; but comparing something to a UID ( $something==FOO) could return an unexpected result. This is because of the way Perl works with overloaded operators: the value on the left gets to decide the meaning of == (or eq). Thus putting the UID first will check for UID-equality; if some other object comes first, it could manhandle the UID and compare, say, its string value instead. (It probably will work anyway, if the other code is well-behaved, but you should be aware of the possibility.) While FOO $stuff is slightly cleaner than FOO($stuff) or FOO=>$stuff [which would be an auto-quoted bareword anyway], remember that FOO $a, $b is actually implemented as a function call taking $a and $b as arguments; thus it imposes list context on them. Most of the time this doesn't matter, but if the item coming after a UID needs to be in scalar context, you may need to say something like FOO, $stuff or FOO scalar $stuff. The user should have more control over the warnings and errors that UID.pm spits out. <plato at cpan.org> Thanks to Tom Phoenix and others who contributed to use constant. This module is free software; you may redistribute it or modify it under the same terms as Perl itself. See perlartistic.
http://search.cpan.org/dist/UID/lib/UID.pm
CC-MAIN-2014-52
refinedweb
1,394
65.46
major components in Sencha Cmd is its compiler. This guide describes how to write code that gets the most out of the compiler and prepares for future framework-aware optimizations. The following guides are recommended reading before proceeding further: Sencha Cmd compiler is not a replacement for tools like these: These tools solve different problems for JavaScript developers and are very good at the world of JavaScript, but have no understanding of Sencha framework features such as Ext.define for declaring classes. The role of the Sencha Cmd compiler is to provide framework-aware optimizations and diagnostics. Once code has passed through the Sencha Cmd compiler, it is ready for more general tools. These kinds of optimizations have shown to significantly improve the "ingest" time of JavaScript code by the browser, especially on legacy browsers. For the compiler to provide these benefits, however, it is now important to look at the coding conventions that the compiler can "understand" and therefore optimize for you. Following the conventions described in this guide ensure that your code is positioned to get the most from Sencha Cmd today and in the future. The dynamic loader and the previous JSBuilder have always made certain assumptions about how classes are organized, but they were not seriously impacted by failure to follow those guidelines. These guidelines are very similar to Java. To recap, these guidelines are: Ext.definestatement at global scope. Ext.define("MyApp.foo.bar.Thing", ...is "Thing.js". Ext.define("MyApp.foo.bar.Thing", ..., the source file is in a path ending with "/foo/bar". Internally, the compiler views source files and classes as basically synonymous. It makes no attempt to split up files to remove classes that are not required. Only complete files are selected and included in the output. This means that if any class in a source file is required, all classes in the file will be included in the output. To give the compiler the freedom to select code at the class-level, it is essential to put only one class in each file. The Sencha Class System provides the Ext.define function to enable high-level, object oriented programming. The compiler takes the view that Ext.define is really a form of "declarative" programming and processes the "class declaration" accordingly. Clearly if Ext.define is understood as a declaration, the content of the class body cannot be constructed dynamically in code. While this practice is rare, it is valid JavaScript. But as we shall see below in the code forms, this is antithetical to the compiler's ability to understand the code it parses. Dynamic class declarations are often used to do things that are better handled by other features of the compiler. For more on these features, see the Sencha Compiler Reference. The compiler understands these "keywords" of this declarative language: requires uses extend mixins statics alias singleton override alternateClassName xtype For the compiler to recognize your class declarations, they need to follow one of the following forms. Most classes use simple declarations like this: Ext.define('Foo.bar.Thing', { // keywords go here ... such as: extend: '...', // ... }); The second argument is the class body which is processed by the compiler as the class "declaration". Note: In all forms, call Ext.define at global scope. In some use cases the class declaration is wrapped in a function to create a closure scope for the class methods. In all of the various forms, it is critical for the compiler that the function end with a return statement that returns the class body as an object literal. Other techniques are not recognized by the compiler. To streamline the older forms of this technique described below, Ext.define understands that if given a function as its second argument, that it should invoke that function to produce the class body. It also passes the reference to the class as the single argument to facilitate access to static members via the closure scope. Internally to the framework, this was the most common reason for the closure scope. Ext.define('Foo.bar.Thing', function (Thing) { return { // keywords go here ... such as: extend: '...', // ... }; }); Note: This form is only supported in Ext JS 4.1.2 and later and Sencha Touch 2.1 and later. In previous releases, the "Function Form" was not supported, so the function was simply invoked immediately: Ext.define('Foo.bar.Thing', function () { return { // keywords go here ... such as: extend: '...', // ... }; }()); This form and the next are commonly used to appease tools like JSHint (or JSLint). Ext.define('Foo.bar.Thing', (function () { return { // keywords go here ... such as: extend: '...', // ... }; })()); Another variation on immediately called "Function Form" to appease JSHint/JSLint. Ext.define('Foo.bar.Thing', (function () { return { // keywords go here ... such as: extend: '...', // ... }; }())); The class declaration in its many forms ultimately contains "keywords". Each keyword has its own semantics, but there are many that have a common "shape". The extend and override keywords only accept a string literal. These keywords are also mutually exclusive in that only one can be used in any declaration. The following keywords all have the same form: requires uses alias alternateClassName xtype The supported forms for these keywords are as follows. Just a string: requires: 'Foo.thing.Bar', //... An array of strings: requires: [ 'Foo.thing.Bar', 'Foo.other.Thing' ], //... mixins Using an object literal, the name given the mixin can be quoted or not: mixins: { name: 'Foo.bar.Mixin', 'other': 'Foo.other.Mixin' }, //... Mixins can also be specified as a String[]: mixins: [ 'Foo.bar.Mixin', 'Foo.other.Mixin' ], //... This approach relies on the mixinId of the mixin class but also allows the receiving class to control the mixin order. This is important if the mixins have overlapping methods or properties and the receiving class wants to control which mixin supplies the overlapping methods or properties. staticsKeyword This keyword places properties or methods on the class, as opposed to on each of the instances. This must be an object literal. statics: { // members go here }, // ... singletonKeyword This keyword was historically only used with a boolean "true" value: singleton: true, The following (redundant) use is also supported: singleton: false, In Ext JS 4.1.0 and Sencha Touch 2.0, Ext.define gained the ability to manage overrides. Historically, overrides have been used to patch code to work around bugs or add enhancements. This use was complicated with the introduction of the dynamic loader because of the timing required to execute the Ext.override method. Also, in large applications with many overrides, not all overrides in the code base were needed by all pages or builds (for example, if the target class was not required). All this changed once the class system and loader understood overrides. This trend only continues with Sencha Cmd. The compiler understands overrides and their dependency effects and load-sequence issues. In the future, the compiler will become even more aggressive at dead-code elimination of methods replaced by an override. Using managed overrides as described below enables this optimization of your code once it's available in Sencha Cmd. Below is the standard form of an override. The choice of namespace is somewhat arbitrary, but see below for suggestions. Ext.define('MyApp.patches.grid.Panel', { override: 'Ext.grid.Panel', ... }); With the ability to use Ext.define to manage overrides, new idioms have opened up and are actively being leveraged. For example in the code generators of Sencha Architect and internal to the framework, that break apart large classes like Ext.Element into more manageable and cohesive pieces. Overrides as patches are the historical use case and hence the most common in practice today. Caution: Take care when patching code. While the use of override itself is supported, the end result of overriding framework methods is not supported. All overrides should be carefully reviewed whenever upgrading to a new framework version. That said, it is, at times, necessary to override framework methods. The most common case for this to fix a bug. The Standard Override Form is ideal in this case. In fact, Sencha Support will at times provide customer with patches in this form. Once provided, however, managing such patches and removing them when no longer needed, is a matter for the review process previously mentioned. Organize patches in a namespace associated with the top-level namespace of the target. For example, "MyApp.patches" targets the "Ext" namespace. If third party code is involved then perhaps another level or namespace should be chosen to correspond to its top-level namespace. From there, name the override using a matching name and sub-namespace. In the previous example: Ext -> MyApp.patches).grid.Panel When dealing with code generation (as in Sencha Architect), it is common for a class to consist of two parts: one machine generated and one human edited. In some languages, there is formal support for the notion of a "partial class" or a class-in-two-parts. Using an override, you can manage this cleanly: In ./foo/bar/Thing.js: Ext.define('Foo.bar.Thing', { // NOTE: This class is generated - DO NOT EDIT... requires: [ 'Foo.bar.custom.Thing' ], method: function () { // some generated method }, ... }); In ./foo/bar/custom/Thing.js: Ext.define('Foo.bar.custom.Thing', { override: 'Foo.bar.Thing', method: function () { this.callParent(); // calls generated method ... }, ... }); Naming Recommendations: Foo.bar.ThingOverrideor Foo.bar.ThingGeneratedso that the parts of a class collate together in listings. A common problem for base classes in object-oriented designs is the "fat base class". This happens because some behaviors apply across all classes. When these behaviors (or features) are not needed, however, they cannot be readily removed if they are implemented as part of some large base class. Using overrides, these features can be collected in their own hierarchy and then requires can be used to select these features when needed. In ./foo/feature/Component.js: Ext.define('Foo.feature.Component', { override: 'Ext.Component', ... }); In ./foo/feature/grid/Panel.js: Ext.define('Foo.feature.grid.Panel', { override: 'Ext.grid.Panel', requires: [ 'Foo.feature.Component' // since overrides do not "extend" each other ], ... }); This feature can be used now by requiring it: ... requires: [ 'Foo.feature.grid.Panel' ] Or with a proper "bootstrap" file (see Workspaces in Sencha Cmd ... requires: [ 'Foo.feature.*' ] Naming Recommendation: requiresand usesin an Override These keywords are supported in overrides. Use of requires may limit the compiler's ability to reorder the code of an override. callParentand callSuper To support all of these new uses cases, callParent was enhanced in Ext JS 4.0 and Sencha Touch 2.0 to "call the next method". The "next method" may be an overridden method or an inherited method. As long as there is a next method, callParent will call it. Another way to view this is that callParent works the same for all forms of Ext.define, be they classes or overrides. While this helped in some areas, it unfortunately made bypassing the original method (as a patch or bug fix) more difficult. Ext JS 4.1 and later and Sencha Touch 2.1 and later provides a method named callSuper that can bypass an overridden method. In future releases, the compiler will use this semantic difference to perform dead-code elimination of overridden methods. Starting in version 4.2.2, overrides can declare their compatibility based on the framework version or on versions of other packages. This can be useful for selectively applying patches that are safely ignored when they are incompatible with the target class version.+' ] } ] }, //... }); For details on version syntax, see the checkVersion method of Ext.Version. As Sencha Cmd continues to evolve, it continues to introduce new diagnostic messages to help point out deviations from these guidelines. A good place to start is to see how this information can help inform your own internal code style guidelines and practices.
https://docs.sencha.com/cmd/7.0.0/guides/cmd_compiler.html
CC-MAIN-2019-43
refinedweb
1,959
58.79
Hi, I have written a program in python, and am looking to translate it into c++ code, here is the program: import random # You've got to guess 4 numbers between 0 and 30, if you get it right the program will output "WINNER" and tell you the computer's numbers x = random.randint(0,30) y = random.randint(0,30) z = random.randint(0,30) t = random.randint(0,30) randnum = [x, y, z, t] print "Enter 4 numbers between 0 and 30:" for l in range(1, 5): prompt = str(l) + " -->" choice = int(raw_input(prompt)) if choice in randnum: print "WINNER" break # ----------- else: print "LOSER" print "The Computer's Numbers Were:" print "---",x,"---", y,"---", z,"---", t,"---" exit
https://www.daniweb.com/programming/software-development/threads/132543/converting-a-python-programme-to-c
CC-MAIN-2017-09
refinedweb
119
59.64
The C++ Twilio help library simplifies the process of making requests to the Twilio REST API, generating TwiML and validating HTTP request signatures using C++. Source. Type ‘make’ to build the library. ‘make examples’ to build the examples, ‘make unittests’ to build the unit tests suite and run it. Don’t forget to include Utils.h, Rest.h and TwiML.h at the top of your source code and to use the twilio namespace: “using namespace twilio;”. The following code examples are based on a restaurant dish recommendation service using SMS for communication. We will go through the following examples: 1- Receiving and replying to a SMS asking for a restaurant dish recommendation. 2- Sending a daily recommendation to a list of subscribers using SMS. 3- Retrieving the list of SMS we sent. We are going to use the C++ std namespace in the rest of the code: “using namespace std;”. We need to define the following constants: // Twilio REST API version const string API_VERSION = "2010-04-01"; // Twilio Account Sid const string ACCOUNT_SID = "XXXX"; // Twilio Auth Token const string ACCOUNT_TOKEN = "XXXX"; // Twilio SMS URL const string SMS_URL = "";. Utils utils (ACCOUNT_SID, ACCOUNT_TOKEN); // vars should contain the POST parameters received. It is a vector of Var structures: key/value. vector<Var> vars; vars.push_back(Var("AccountSid", "xxxx")); vars.push_back(Var("Body", "xxxx")); // ... add all POST parameters received // signature is the hash we received in the X-Twilio-Signature header bool valid = utils.validateRequest(signature, SMS_URL, vars); if(!valid) // ... handle invalid request here Then we need to reply with our dish recommendation. We use the classes TwiMLResponse and Sms to help us generate the XML. TwiMLResponse response; // Set SMS text based on what the user asked, which can be found in the "Body" POST parameter. Sms sms ("Gigantic Burger at Twilio at 501 Folsom St San Francisco"); response.append(sms); // ... reply with response.toXML() response.toXML() returns the following: <Response> <Sms> <![CDATA[Gigantic Burger at Twilio at 501 Folsom St San Francisco]]> </Sms> </Response>. Rest rest(ACCOUNT_SID, ACCOUNT_TOKEN); // Fill up the POST parameters vector vector<Var> vars; vars.push_back(Var("From", "xxx-xxx-xxxx")); vars.push_back(Var("Body", "Deluxe Ramen at Twilio at 501 Folsom St San Francisco")); vars.push_back(Var("To", "")); string res; // Go through the list of subscribers and issue a POST request for each one. for(unsigned int i = 0; i < subscribers.size(); i++) { // vars[2] refers to the "To" parameter vars[2].value = subscribers[i]; res = rest.request("/" + API_VERSION + "/Accounts/" + ACCOUNT_SID + "/SMS/Messages", "POST", vars); // "res" contains the XML response returned by the Twilio server } Retrieving the list of SMS messages we sent and their status We need to issue a GET request using the following URL: /2010-04-01/Accounts/{AccountSid}/SMS/Messages. We use the class Rest to help us with the GET request. Rest rest(ACCOUNT_SID, ACCOUNT_TOKEN); // Fill up the GET parameters vector vector<Var> vars; vars.push_back(Var("From", "xxx-xxx-xxxx")); // we can also set "To" and "DateSent" to filter more string res; res = rest.request("/" + API_VERSION + "/Accounts/" + ACCOUNT_SID + "/SMS/Messages", "GET", vars); “res” should contain the list of SMS sent. <TwilioResponse> <SMSMessages page="0" numpages="6"...> <SMSMessage> <Sid>SM800f449d0399ed014aae2bcc0cc2f2ec</Sid> <DateCreated>Mon, 10 Dec 2010 03:45:01 +0000</DateCreated> ... </SMSMessage> ... </SMSMessages> </TwilioResponse> Note that pagination might need to be handled if the number of SMS messages is too large for one HTTP response. See for more details. There is a lot more you can do using the Twilio C++ library so go ahead and have fun with it. Do I have to create a sms web page on my own server for the c++ desktop application to access the SMS messages that are sent to my Twilio account? Link | November 30th, 2011 at 5:26 pm @Bryan To access the SMS sent to your account, the Twilio API URL is used which is by default. Take a look at section 3 of the tutorial for more details. Link | January 2nd, 2012 at 3:43 pm
http://www.laurentluce.com/posts/c-twilio-rest-and-twiml-helper-library/
CC-MAIN-2018-17
refinedweb
664
66.84
Choose between Azure messaging services - Event Grid, Event Hubs, and Service Bus Azure offers three services that assist with delivering event messages throughout a solution. These services are: Although they have some similarities, each service is designed for particular scenarios. This article describes the differences between these services, and helps you understand which one to choose for your application. In many cases, the messaging services are complementary and can be used together. Event vs. message services There's an important distinction to note between services that deliver an event and services that deliver a message. Event An event is a lightweight notification of a condition or a state change. The publisher of the event has no expectation about how the event is handled. The consumer of the event decides what to do with the notification. Events can be discrete units or part of a series. Discrete events report state change and are actionable. To take the next step, the consumer only needs to know that something happened. The event data has information about what happened but doesn't have the data that triggered the event. For example, an event notifies consumers that a file was created. It may have general information about the file, but it doesn't have the file itself. Discrete events are ideal for serverless solutions that need to scale. Series events report a condition and are analyzable. The events are time-ordered and interrelated. The consumer needs the sequenced series of events to analyze what happened. A message is raw data produced by a service to be consumed or stored elsewhere.. Comparison of services Event Grid Use the services together In some cases, you use the services side by side to fulfill distinct roles. For example, an e-commerce into a data warehouse. The following image shows the workflow for streaming the data. Next steps See the following articles: - Asynchronous messaging options in Azure - Events, Data Points, and Messages - Choosing the right Azure messaging service for your data. - Storage queues and Service Bus queues - compared and contrasted - To get started with Event Grid, see Create and route custom events with Azure Event Grid. - To get started with Event Hubs, see Create an Event Hubs namespace and an event hub using the Azure portal. - To get started with Service Bus, see Create a Service Bus namespace using the Azure portal. Feedback
https://docs.microsoft.com/en-us/azure/event-grid/compare-messaging-services?WT.mc_id=ondotnet-hashnode-cephilli
CC-MAIN-2020-05
refinedweb
394
64.71
Hi! It's me again and this is a decoder! The goal: And I'm trying to make a program that solves logical problems related to the decoder device. For that I need a loop that write true/false into a boolean[][] based on the rules. Say we have a decoder with 3 inputs. That means that it has 8 outputs (2^(numberOfInputs) = 8). I need a method to write this (example of 3 inputs): |0|0|0| |0|0|1| |0|1|0| |0|1|1| |1|0|0| |1|0|1| |1|1|0| |1|1|1| Notice the third column (actually called column 0, the middle one would be 1, the most left one 2). 2^0 (0 being the column "name") is 1, so the rule is: from top to bottomw write one 0, then one 1, again one 0 and one 1). In column 1, 2^1 = 2, so write two 0s, then two 1s and repeat. In column 2, 2^2 = 4, so write four 0s, then four 1s. Column 3 would be 2^3 = 8, so eight 0s, then eight 1s. The code: package Decoder; import java.util.Scanner; public class Decoder { public static void main(String[] args) { Decoder M = new Decoder(); int inputs, outputs; Scanner S = new Scanner(System.in); System.out.print("Enter number of inputs: "); inputs = Integer.parseInt(S.nextLine()); outputs = (int) Math.pow(2, inputs); // derived from rule boolean[][] table = new boolean[outputs][inputs]; System.out.println("Decoder: " + inputs + "/" + outputs); table = M.defaultTable(outputs, inputs); M.printTable(table, outputs, inputs); } public boolean[][] defaultTable(int inputs, int outputs) { boolean[][] Y = new boolean[inputs][outputs]; int counter = 0; int someNumber = 0; for (int i = outputs - 1; i > -1; i--) { int step = (int) Math.pow(2, counter); for (int j = 0; j < inputs; j++) { if (step == someNumber) { // THIS Y[j][i] = true; // IS someNumber = 0; // THE PROBLEM AREA } someNumber++; } counter++; } return Y; } public void printTable(boolean[][] Y, int izlazi, int ulazi) { // Standard method for printing a 2D array. for (int i = 0; i < izlazi; i++) { for (int j = 0; j < ulazi; j++) { if (Y[i][j] == true){ System.out.print("|1"); }else { System.out.print("|0"); } } System.out.println("|"); } } } The problem: I need method "defaultTable" (lines 23-40) to respect the complement of two (1, 2, 4, 8, 16 etc). I already got it to move in a correct sequence (start at top left cell, work downwards), but I can't figure out how to asign values into the boolean[][] while moving in the "complement of two"-way. Just a hint! No direct solutions please! :D Thanks, Pob Edited by Pobunjenik: typo
https://www.daniweb.com/programming/software-development/threads/452559/decoder-simulator-calculator-complement-of-2-problem
CC-MAIN-2018-22
refinedweb
440
73.88
BEER BEAR BEAD BEAK BEAT BELT WELT WILT WILE WINE Let's write a simple program that calculates word ladders for a simplified version of the game where each change can only change a single letter at a time (rather than allow deletes and inserts too). Finding a word ladder can be thought about as a graph problem. Each node is a word, and each edge represents a connection to another valid word. The graph below is a partial representation of the graph starting with BEER. The real graph is much more complicated! First things first, how do we build the graph? For starters we need to know if two words are neighbours or not. The following simple functions determine the difference between two strings. Remember that I'm only working on the simplest possible distance metric at the moment, that is allowing a single character to change. neighbour :: String -> String -> Bool neighbour x y = difference x y == 1 difference :: String -> String -> Int difference [] [] = 0 difference (x:xs) (y:ys) | x == y = difference xs ys | otherwise = 1 + difference xs ys difference _ _ = error "Two strings must be the same length" Next thing we need to grab is a huge list of words. We'll store these words in a Set because we'll want to test for membership frequently (an O(lg(N)) operation. An alternative would be to use a perfect hash (this is an option because the dictionary is fixed). This would give O(1) lookup times, and it looks like there is (as almost always) a library on Hackage that does just that. The simple distance metric chosen means we can limit the number of words based on the size of the input word. import qualified Data.Set as S type WordSet = S.Set String wordListPath :: String wordListPath = "/usr/share/dict/british-english" createDictionary :: Int -> IO WordSet createDictionary n = do file <- readFile wordListPath return $ S.fromList $ filter (\x -> length x == n && all isAlpha x) (map (map toLower) $ words file) Once we've got a dictionary, all we need to do is build the graph. Since Haskell is lazy, we don't need to worry about the space complexity of the graph - we'll just build it lazily and only the bit that is explored will be resident in memory. Each node contains the word it represents and the links to the child elements. The graph is built by starting at a root, and filling all the valid neighbours. Each time we place a word in the graph we remove it from the dictionary, otherwise we'll get cycles in the graph. data Node = Node String [Node] deriving Show buildGraph :: WordSet -> String -> Node buildGraph wordset top = Node top (map (buildGraph smaller) neighbours) where neighbours = S.toList (S.filter (neighbour top) smaller) smaller = S.delete top wordset The graph is *huge*, so we need to find some way to limit the search space. The most obvious way is to give a restriction on the depth of the search. A word ladder that is 10000 words rungs high is probably not much fun to complete. We can also cut the search short if the word is too many changes away given the maximum depth (for example, if 4 characters need to change in a 5 letter word and the maximum left to search is 3 then we can prune this search branch). search :: Node -> Int -> String -> [String] search graph maxDepth goal = search' graph maxDepth goal [] search' :: Node -> Int -> String -> [String] -> [String] search' (Node end children) maxDepth goal path | end == goal = end : path | null children = [] | length path >= maxDepth = [] -- too deep | difference end goal >= maxDepth - length path = [] -- too much difference | otherwise = first where childRoutes = filter (not . null) $ map (\child -> search' child maxDepth goal (end : path)) children first | null childRoutes = [] | otherwise = head childRoutes quickest | null childRoutes = [] | otherwise = minimumBy (comparing length) childRoutes The way we search the children is important. In this case we've used firstgone for the first available route that satisfies the depth guarantee, but isn't guaranteed to be the shortest route. quickeston the other hand calculates all child routes and finds the minimum length part. Finally, we can put this all together and write a simple search search function. makeLadder :: Int-> String -> String -> IO [String] makeLadder maxDepth start end | length start /= length end = error "Only two strings of equal length are currently supported." | otherwise = do dict <- createDictionary (length start) if (S.member start dict && S.member end dict) then return $ search (buildGraph dict start) maxDepth end else return []The complete code for this version available on my git hub repo here. This version has several problems. - It's too slow - searching for the minimal path can take considerable time - It's not very flexible data DistanceMetric = DistanceMetric (Word -> Word -> Int) (Word -> WordSet) difference :: Word -> Word -> Int difference x y | length x /= length y = 999999 | otherwise = sum $ zipWith (\c1 c2 -> if c1 == c2 then 0 else 1) x y transposeChar :: Word -> [Word] transposeChar [] = [] transposeChar (x:xs) = map (:xs) (validChars \\ [x]) deleteChar :: Word -> [Word] deleteChar [] = [] deleteChar (x:xs) = [xs] insertChar :: Word -> [Word] insertChar [] = [] insertChar (x:xs) = map (\y -> y:x:xs) validChars differenceEdit :: Word -> WordSet differenceEdit x = edit' x [transposeChar] editDistanceEdits :: Word -> WordSet editDistanceEdits x = edit' x [insertChar,transposeChar,deleteChar] edit' :: Word -> [Word -> [Word]] -> WordSet edit' w fns = S.fromList $ concat $ zipWith (\x y -> map (\z -> x ++ z) (concatMap (\x -> x y) fns)) (inits w) (tails w) simple :: DistanceMetric simple = DistanceMetric difference differenceEdit edits :: DistanceMetric edits = DistanceMetric editDistance editDistanceEditsThis gives two distance functions and two ways of generating edits. The Levenshtein distance of 1 is generated by transposing, deleting and inserting characters from the original word. This gives us the flexibility, because another distance metric could be put in place (anagrams perhaps?). Next to performance. buildGraph :: DistanceMetric -> WordSet -> Word -> Node buildGraph d@(DistanceMetric dist edits) wordset top = Node top (map (buildGraph d smaller) neighbours) where possibleNeighbours = edits top neighbours = S.toList (smaller `S.intersection` possibleNeighbours) smaller = S.delete top wordset search :: DistanceMetric -> Node -> Int -> Word -> [Word] search (DistanceMetric dist _) graph maxDepth goal = search' graph [] where search' (Node end children) path | end == goal = end : path | length path >= maxDepth = [] -- too deep | dist end goal >= maxDepth - length path = [] -- too much difference | otherwise = first where -- Find the best node to search by comparing it against the goal costForNextChild :: [(Int,Node)] costForNextChild = zip (map (\(Node x _) -> dist x goal) children) children bestFirst = map snd $ sortBy (comparing fst) costForNextChild -- Best first search childRoutes = filter (not . null) $ map (\child -> search' child (end : path)) bestFirst first | null childRoutes = [] | otherwise = head childRoutesTwo things have changed from the original code. The first is that the graph is built by comparing the edits against the dictionary, rather than the word against the whole dictionary. This is the main saving and makes it *hugely* faster (thanks to jkkramer for the pointer and this post.) The only other change is that we decide which node to search next based on how close it is to the goal (a best-first search). With these changes it can now solve all of the problems I've tried at wordchains.com. Neat. The complete code is available here.
http://www.fatvat.co.uk/2010/12/word-ladders.html
CC-MAIN-2015-11
refinedweb
1,184
66.57
Date: Mon, 16 May 2022 14:19:41 +0000 (UTC) Message-ID: <1256520498.81485.1652710781256@confluence> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_81484_1192002218.1652710781251" ------=_Part_81484_1192002218.1652710781251 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: Treasure Data provides a cloud-based analytics infrastructure ac= cessible via SQL. Interactive engines like Presto enable you to crunch billions of records easily. H= owever, writing a SQL query is sometimes painful for data scientists, and y= ou=E2=80=99ll still need to use external tools like Excel or Tableau to vis= ualize the result. You can use Treasure Data with the Python-based data ana= lysis tool called Pandas and visualize the data interactively = via Jupyter Notebook. Basic knowledge of Python. Basic knowledge of Treasure Data. Set your master API key as an environment variable before launching Jupy= ter. The master API KEY can be retrieved from the TD Console profile. $ export= TD_API_KEY=3D"1234/abcde..."=20 You can set your environment variables with= a command such as the following in Jupyter Notebook cell. %env TD= _API_KEY =3D "123c/abcdefghjk..."=20 Set Treasure Data API Endpoint as an environment variable if your accoun= t does not belong to the US Region. You can see Endpoint info here $ expor= t TD_API_SERVER=3D" You can set your environment variables with= a command such as the following in Jupyter Notebook cell. %env TD= _API_SERVER =3D " For more information and instructions, see Installing Conda, Pandas, matplotli= b, Jupyter Notebook, and pytd. We=E2=80=99ll use Jupyter as a frontend for our analysis project. Run Notebook using the following syntax: (analysi= s)$ ipython notebook=20 Your web browser will open: Select New > Python 3. Copy and paste the following text into your notebook: %matplot= lib inline import os import pandas as pd import pytd.pandas_td as td # Initialize the connection to Treasure Data con =3D td.connect(apikey=3Dos.environ['TD_API_KEY'], endpoint=3D' pi.treasuredata.com')=20 Your notebook should now look similar to Type Shift-Enter. If you get "KeyError: 'TD_API_KEY'" error, If it works, Jupyter didn't recognize the = TD_API_KEY variable from the OS. Confirm the TD_API_KEY again and re-lau= nch Jupyter. Optionally, save your notebook. There are two tables in sample_datasets. You can use the ma= gic command td_tables to view all the tables in your database.= Let=E2=80=99s explore the nasdaq table. In Jupyter, type the following syntax: engine = =3D td.create_engine("presto:sample_datasets") client =3Dtd.Client(database=3D'sample_datasets') client.query('select symbol, count(1) as cnt from nasdaq group by 1 order b= y 1')=20 For example: For the purposes of this example, Presto is used as the query engine for= this session. In Jupyter, type the following syntax: import p= ytd.pandas_td as td con =3D td.connect(apikey=3Dapikey, endpoint=3D" m") engine =3D td.create_engine("presto:sample_datasets") td.read_td_query(query, engine, index_col=3DNone, parse_dates=3DNone, distr= ibuted_join=3DFalse, params=3DNone)=20 th= e details of time-series data. As your data set grows very large, the method from the previous step doe= sn=E2=80=99t scale very well. We don't recommend that you retrieve more tha= n a few million rows at a time due to memory limitations or slow network tr= ansfer. If you=E2=80=99re analyzing a large amount of data, you need to lim= it the amount of data getting transferred. There are two ways to do this: You can sample data. For example, the =E2=80=9CNasdaq=E2=80=9D table= has 8,807,278 rows. Setting a limit of 100000 results in 100,000 rows, whi= ch is a reasonable size to retrieve: Write SQL and limit data from the server-side. For example, as we ar= e interested only in data related to =E2=80=9CAAPL=E2=80=9D, let=E2=80=99s = count the number of records, using read_td_query: It=E2=80=99s small enough, so we can retrieve all the ro= ws and start analyzing data: See the contents below for further information. Python for Data Analysis (Book by O'Reill= y Media) Jupyter Notebooks are supported by GitHub and you can share the result o= f your analysis session with your team: GitHub + Jupyter Notebooks =3D <= ;3
https://docs.treasuredata.com/exportword?pageId=329196
CC-MAIN-2022-21
refinedweb
718
57.06
James Youngman wrote: > It seems to me that ABSOLUTE_STDINT_H can be used without being > defined. I cannot see under which conditions this could be the case. Also, I don't reproduce this problem when compiling findutils-4.3.6 on Solaris 7 with Sun cc 5.0. > When this happens a compilation error can result. This code: > > #if @HAVE_STDINT_H@ > # if defined __sgi && ! defined __c99 > /* Bypass IRIX's <stdint.h> if in C89 mode, since it merely annoys users > with "This header file is to be used only for c99 mode compilations" > diagnostics. */ > # define __STDINT_H__ > # endif > /* Other systems may have an incomplete or buggy <stdint.h>. > Include it before <inttypes.h>, since any "#include <stdint.h>" > in <inttypes.h> would reinclude us, skipping our contents because > _GL_STDINT_H is defined. */ > # include @ABSOLUTE_STDINT_H@ > #endif > > provokes an error message because @ABSOLUTE_STDINT_H@ expands to nothing :- > > source='xstrtoumax.c' object='xstrtoumax.o' libtool=no \ > DEPDIR=.deps depmode=none /bin/ksh ../../build-aux/depcomp \ > cc -DHAVE_CONFIG_H -I. -I../.. -I../../intl > -I/usr/local/include -I/usr/local/include -c xstrtoumax.c > "./stdint.h", line 47: empty file name This error message indicates that @ABSOLUTE_STDINT_H@ expands into "". > The configure output seems to support this idea: > > > checking for stdint.h... yes > checking for stdint.h... (cached) yes > checking absolute name of <stdint.h>... Indeed. This is the problem. > My guess is that the cause of the problem is that findutils is > checking for stdint.h like this in configure.in:- > > AC_CHECK_HEADERS(unistd.h sys/types.h inttypes.h fcntl.h locale.h stdint.h) There is no problem with that. The value ac_cv_header_stdint_h is only used, not overridden or modified. > I guess it's possible that the problem is caused by my calling > AC_CHECK_HEADERS(stdint.h) This is just a guess. Have you tried removing it? I bet it would not help. > `(eval "$ac_cpp conftest.$ac_ext") 2>&AS_MESSAGE_LOG_FD | > sed -n > '\#/]m4_quote(m4_defn([gl_HEADER_NAME]))[#{s#.*"\(.*/]m4_quote(m4_defn([gl_HEADER_NAME]))[\)".*#\1#;s#^/[^/]#//&#;p;q;}'` This is the code producing the value. I guess the $ac_cpp command led to an error, for some reason that the user needs to investigate. The investigation can use the config.log file, since - as you see - the error output of the $ac_cpp command is piped to the config.log. It would also help to show the configure command together with all relevant environment variables (CC, CPP, CPPFLAGS). Bruno
http://lists.gnu.org/archive/html/bug-gnulib/2007-05/msg00153.html
CC-MAIN-2013-48
refinedweb
391
54.18
pies 2.5.2 The simplest way to write one program that runs on both Python 2 and Python 3. Let’s eat some pies! Installing pies pip install pies or if you prefer: easy_install pies Overview Pies is a Python2 & 3 Compatibility layer with the philosophy that all code should be Python3 code. Starting from this viewpoint means that when running on Python3 pies adds virtually no overhead. Instead of providing a bunch of custom methods (leading to Python code that looks out of place on any version) pies aims to back port as many of the Python3 api calls, imports, and objects to Python2 - Relying on special syntax only when absolutely necessary. How does pies differ from six? Pies is significantly smaller and simpler then six because it assumes for everything possible the developer is using the Python 3 compatible versions included with Python 2.6+, whereas six tries to maintain compatibility with Python 2.4 - leading to many more overrides and further into different language territory. Additionally, as stated above, where possible pies tries to enable you to not have to change syntax at all. Integrating pies into your diet Using and integrating pies into an existing Python 3+ code base (to achieve Python 2 & 3 dual support) couldn’t be simpler: from __future__ import absolute_import, division, print_function, unicode_literals from pies.overrides import * Then simply write standard Python3 code, and enjoy Python2 Support.) Some Python3 Modules have moved around so much compared to their Python2 counterpart, that I found it necessary to create special versions of them to obtain the Python3 naming on both environments. Since these modules exist already in Python2 allowing them to be imported by the Python3 module name directly is not possible. Instead, you must import these modules from pies. Example: form pies import pickle Full List: - - Author: Timothy Crosley - Download URL: - Keywords: Python,Python2,Python3,six,future,refactoring,single-code-base - License: MIT - Requires pies2overrides, enum34 - Categories - Development Status :: 5 - Production/Stable -: pies-2.5.2.xml
https://pypi.python.org/pypi/pies/2.5.2
CC-MAIN-2017-09
refinedweb
335
51.48
Unsure why this is not working, probably some niche reason I am unaware of. I have two scripts that are involved here, def universalPrint(message): """ Will work for vision or perspective clients now. Args: message: str, what do you want to print Returns: None """ from env import isVision if isVision(): print message else: import system.perspective system.perspective.print(message) This has works fine and has been use in use for a while. My new script which is printing, but is not logging, is def logInfoAndPrint(message, loggerName): """ For instances where we want to both log to the server but also print to console for easier debugging. Args: message: anything as we type cast in this function for ease of use, what are we trying to print loggerName: str, what logger are we saving this to """ import system.util logger = system.util.getLogger(loggerName) universalPrint(str(message)) universalPrint("about to log") logger.info(message) universalPrint("logged") It gets to print the last “logged” statement, but I do not see the actual logged statement in my server logs. In my console, I see test message about to log 09:01:55.877 [AWT-EventQueue-0] INFO test logger - test message logged Any ideas whats going on here? Is this not possbile?
https://forum.inductiveautomation.com/t/creating-a-log-and-print-function-that-is-not-working/42203
CC-MAIN-2022-40
refinedweb
210
63.9
Tag Libraries Microsoft Corporation October 2003 Applies to: Microsoft® .NET Framework Microsoft ASP.NET Microsoft Visual Studio® .NET Microsoft Visual C#® .NET Java Server Pages Summary: Learn how to convert Java tag libraries to ASP.NET Web form controls. (11 printed pages) Contents Tag Libraries Converting Tag Libraries by Using the Java Language Conversion Assistant ASP.NET Web Form Controls Summary In a Web application, a common design goal is to separate the display code from business logic. Java tag libraries are one solution to this problem. Tag libraries allow you to isolate business logic from the display code by creating a Tag class (which performs the business logic) and including an HTML-like tag in your JSP page. When the Web server encounters the tag within your JSP page, the Web server will call methods within the corresponding Java Tag class to produce the required HTML content. Microsoft® ASP.NET uses Web form controls to serve the same purpose as Java tag libraries. Similar to JSP tags, Web form controls are added to an ASP.NET Web page using an HTML-like syntax. Unlike JSP tags however, a Web form control is actually an object that is contained within your ASP.NET page. This allows you to access information from your Web form control both before and after the page is loaded. The Microsoft® .NET Framework contains many ready-to-use Web form controls, including a Calendar Web form control and a Crystal Reports Viewer Web control. If you require different functionality than is provided by these Web form controls, you can either extend the existing Web form controls or create your own Web form controls by implementing various interfaces. In this article, we will briefly review tag libraries in Java. We will then discuss how the Java Language Conversion Assistant (JLCA) will convert tag libraries and what you must to do clean up the conversion. Finally, we will provide an overview of Web controls and their use in ASP.NET Tag Libraries Tag libraries were designed so that Java code could be executed within a JSP page without using Java script blocks, which clutter up the HTML and break the design goal of separating display code from business logic. Instead of script blocks, tag libraries allow you to create custom HTML-like tags that map to a Java class that performs the business logic. Groups of these HTML-like tags are called tag libraries. Creating and using a custom tag library involves three things: - One or more classes that implement the javax.servlet.jsp.tagext.Tag interface. The Tag interface defines six methods that allow your JSP page to use the class to create the desired HTML output. There are also classes/interfaces that implement/extend the Tag interface, such as TagSupport and BodyTagSupport, to make it easier for you to develop your custom tag. - An XML document that describes your tag library. Tag library description files must conform to the JSP tag library description DTD, and generally have an extension of "tld". - Importing the tag library to the JSP page using the taglib directive. Once the three requirements are met, you can use the tags in your tag library anywhere within your JSP page. Tag Libraries in On the CodeNotes site, we made use of the tag libraries included in the Struts framework, and did not use any tag libraries that were developed in house. Because we did not include the Struts source code with our conversion, the tag libraries did not convert at all. However, for the purposes of demonstrating a sample tag library conversion, we will use a tag that fills a <select> tag with books stored in a database. At the end, we will be able to populate our <select> element using code similar to the code in Listing 1. Listing 1. Books.jsp <%@ taglib <book:BookList/> </select> <!-- rest of jsp page removed for clarity --> When a user browses to our Books.jsp page, they will see listing of all the books, for which the HTML will look like Listing 2. Listing 2. The HTML for our listing <select name="bookID"> <option value='BU1032'>The Busy Executive's Database Guide</option> <option value='PS7777'>Emotional Security: A New Algorithm</option> <option value='PS1372'>Computer Phobic AND Non-Phobic Individuals: Behavior Variations</option> <!-- the rest of the options were removed for brevity --> </select> As we can see from Listing 2, the main requirement of our Tag class is to produce a String containing multiple <option>elements. The BookListTag in Listing 3 is an example of a Tag class that performs this task. As you can see, BookListTag extends the TagSupport class. The TagSupport class is an implementation of the Tag interface that allows you to create a custom tag by overriding only a few methods instead of implementing the entire Tag interface. You will notice that all of our code takes place within the doStartTag() method. As its name implies, doStartTag() is called whenever the corresponding start tag appears in the JSP page. By using the JSP page's printwriter object within this method, all the strings that we write will replace the occurrence of the start tag in the JSP page. Listing 3. BookListTag.java package books; public class BookListTag extends TagSupport { public int doStartTag() { try { JspWriter out = pageContext.getOut(); Hashtable books; /* populate books from the database */ String id = new String(); for (Enumeration e = books.keys();e.hasMoreElements();) { id = e.nextElement().toString(); out.println("<option value='" + id + "'>" + books.get(id) + "</option>"); } } catch (Exception e) { System.out.println(e); } return SKIP_BODY; } } The last step in using our book list tag is to register it in a tag library description file, which is shown Listing 4. Listing 4. BookTags.tld <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" ""> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>BookTags</shortname> <info>Tags for Book Application</info> <tag> <name>BookList</name> <tagclass>books.BookListTag</tagclass> <info>Outputs product list for a form</info> </tag> </taglib> Recall from Listing 1 that the first line in our JSP page was a taglib directive that mapped the tag library saved in BookTags.tld to the prefix book. This directive allows us to use any of the tags contained in Listing 4 using the syntax <book: tagName>. When producing an HTML file from the JSP page, the Web server will examine the OrderTags.tld file to find a <tag>element with a <name>element equal to tagName. Once a match has been found, an instance of the class named in the <tagclass>element is created and used to produce the output for the custom tag. For example, when the Web server processes the <book:BookList>tag in Listing 1, it examines the BookTags.tld file to find the BookList <name>element. Once the proper <name>element has been found, the Web server can determine from the <tagclass>element that a BookListTag object should be created. Since <book:BookList/>is a start tag (as well as an end tag), the Web server will then call the BookListTag.doStartTag() method, which produces the desired output. Converting Tag Libraries by Using the Java Language Conversion Assistant Provided that you have source code for your tag libraries, the JLCA will cleanly convert the tag functionality in your project. Although the presentation says that nested tags may be a problem, that information was based on an early build. The newest version converts nested tags cleanly. You will still most likely have to clean up whatever code is called within your doStartTag() method (or whatever Tag methods you implement), but the JLCA will ensure that the functionality within your tag will be invoked at the proper time. For example, the JLCA will ensure that wherever the <ord:BookList>tag originally appeared in your JSP page, the functionality contained within the BookListTag.doStartTag() method will be called at the same point in the JLCA-produced ASP.NET page. If you do not have the source code for your tag libraries, you will have to develop your own Web form control, which is discussed in the ASP.NET Web Form Controls section. In this section, we will walk through the conversion of the tag library from the Tag Libraries in section to demonstrate how the JLCA converts a sample tag library. The first thing you will notice after the conversion is that the JLCA created a directive (Listing 5) in the Books.aspx page similar to the one in the Books.jsp page from Listing 1. Listing 5. The ASP.NET directive for registering the books tag library <%@ Register TagPrefix="book_1" Namespace= "books" Assembly="BookApplication"%> The ASP.NET Register directive contains similar information to the JSP taglib directive. The Register directive in Listing 5 declares that any tag with the book_1: prefix maps to a control in the books namespace and is found in the BookApplication assembly. In our example in Listing 6, the <book_1:BookListTag>element maps to the books.BookListTag class. Listing 6. The ASP.NET syntax for calling a server control <select name="bookID"><book_1:BookListTag You will notice that there are more attributes for the tag in Listing 6 than in the JSP-equivalent in Listing 1. The id attribute references the variable name of the control in the Books.aspx codebehind. In the conversion of your tag libraries, you will not likely need to do anything in your codebehind, but as explained in the upcoming ASP.NET Web Form Controls section, having access to the control in the codebehind allows you to interact with the control. The runat attribute must be set to "server" and indicates that the <book_1:BookListTag>element is a server control. One important thing to notice about the conversion of the Books.jsp page is that the JLCA correctly maps the tag in the ASP.NET page to the corresponding Web form control class. During the conversion, the JLCA examines the tag library description files to determine which classes are being invoked by which tags in the JSP pages, and then ensures the resultant ASP.NET pages call the correct class. The only other part of the converted project that reflects the tag library is the BookListTag.cs file (Listing 7, which was created from the BookListTag.java file). Listing 7. BookListTag.cs using System; namespace orders { public class BookListTag:WCIterationImpl { public override int doStart() { try { System.Web.HttpResponse out_Renamed = GetOut(); System.Collections.Hashtable books; /* populate books from the database */ // UPGRADE_TODO removed for clarity for (System.Collections.IEnumerator e = h.Keys.GetEnumerator(); e.MoveNext(); ) { // UPGRADE_TODOs removed for clarity id = e.Current.ToString(); // UPGRADE_TODO removed for clarity out_Renamed.Write("<option value='" + id + "'>" + books[id] + "</option>" + "\r\n"); } } catch (System.Exception e) { // UPGRADE_TODO removed for clarity System.Console.Out.WriteLine(e); } return SkipBody; } } } There are two things you should notice about the BookListTag class: - Instead of the functionality being placed in a doStartTag() method, the functionality is placed within the doStart() method. This is simply a change in name and there is no difference in functionality associated with this change. - The BookListTag class extends the WCIterationImpl class. WCIterationImpl is a JLCA-created class found in the SupportClass.cs file. WCIterationImpl contains methods that allow an implementation of the UserControl class (the base class for most server controls) to have methods similar to those contained in the Java Tag interface. The JLCA takes care of mapping from the Tag methods to WCIterationImpl methods, so you do not have to do anything with the WCIterationImpl class. The JLCA did flag a few issues during the conversion of BookListTag.java to BookListTag.cs. Specifically, the JLCA mentioned that there might be some problems due to the conversion from java.util.Enumeration to System.Collections.Ienumerator, as well as some problems stemming from changing the Java toString() method to the C# ToString() method. While in some instances, these issues may cause problems, they do not affect the functionality of the BookListTag class so they can be ignored. This means that without making any changes to the converted code, our JSP tag was converted successfully into an ASP.NET Web control. ASP.NET Web Form Controls You may find that the terminology used to describe Web form controls and other controls can get confusing because they all have similar sounding names. The following is a brief discussion of terms that you are likely to hear when discussing Web form controls: - Server controls are objects that are instantiated and run on the Web server and produce HTML and/or JavaScript that will be embedded in the final HTML page. Server controls can be divided into two more specific categories: Web controls and Mobile controls. - Web controls are used in pages that are designed to be viewed in a Web browser. Web controls can be divided into two more specific categories: HTML controls and Web form controls. - Mobile controls are used to produce content intended to be displayed on a mobile device. Mobile controls are located in the System.Web.UI.MobileControls namespace. - HTML controls are Web controls that have a direct map to an HTML element. By using an HTML control instead of an HTML element, you can manipulate the contents of the element within the codebehind of the ASP.NET page allowing the display to be dynamic. HTML controls are located in the System.Web.UI.HtmlControls namespace. - Web form controls are Web controls that provide functionality for which there is not necessarily a corresponding HTML element. For example, there is a Button Web form control, which has a corresponding HTML element (an input button) and there is a Calendar Web form control for which there is no corresponding HTML element. The difference between using a Web form control for an HTML element and using the corresponding HTML control is that the HTML control is limited by the attributes/functionality of the HTML element while the Web form control may incorporate more or different HTML elements depending on the target browser to achieve your desired look-and-feel. However, because a Web form control does not map directly to an HTML element, there is no guarantee that your Web form control will appear the same on all browsers. For example, the TextBox Web form control can span multiple lines when viewed in Internet Explorer. However, on some versions of Netscape, the TextBox will only be a single line, similar to the HTML TextField element. Web form controls are located in the System.Web.UI.WebControls namespace. In this article, we will focus our discussion on the Web form controls because those are the server controls that most closely match the functionality of tag libraries. Built-in Web Form Controls ASP.NET includes a variety of built-in Web form controls that can be used to add graphical elements to your Web pages. They include labels, calendars, buttons, images, tables, and many others. All Web form controls can be added to your ASP.NET page by dragging the associated icon from the Web Forms tab of the Toolbox to the desired location on your Web form. Once a Web form control is added to your page, it can be configured through the Properties tab. As we alluded to in Converting Tag Libraries by Using the Java Language Conversion Assistant, once a Web form control is added to your Web form, an associated object is added to the codebehind class. This means that anywhere within the codebehind, you can have access to the properties of all the Web form controls in the associated page. For example, in the button_click event for a Button Web form control, you can access the text the user entered in a TextBox. This level of interactivity truly allows you to separate the user interface from the business logic, as you can verify that forms have been entered correctly (that a valid value has been entered for each field) before performing the necessary business logic. It also provides a convenient and logical location for all classes for a specific user interface (the .aspx page and the associated codebehind) instead of the Java method of using a JSP page and an associated servlet which has no direct link to the JSP page. For an example of how easy it is to use Web form controls, we will create a simple application containing a text box and a button. When the user clicks the button, the String in the textbox is converted to upper case. First, we drag a TextBox and a Button from the Web Forms tab on the Toolbox to the ASP.NET page. Once you have added both controls to the ASP.NET page, double-click the button control to create the Button1_Click() method and configure the ASP.NET page to activate this method whenever the button control is clicked. By adding the single line of code in Listing 8 to the Button1_Click() method, our application will now convert the user-entered String to upper case. Listing 8. Converting the value in a TextBox to uppercase private void Button1_Click(object sender, System.EventArgs e) { TextBox1.Text = TextBox1.Text.ToUpper(); } While Listing 8 contains very little functionality (it simply manipulates the TextBox.Text property which is a String representing the current value of the TextBox), the ASP.NET Web server is actually doing a lot of work behind the scene. When converting the ASP.NET page into an HTML page for viewing, the Button Web form control is converted into an HTML input submit element. When the user clicks the button, the form is submitted from the client's browser to the Web server. When the Web server receives the posted form, it populates the objects in the codebehind to reflect the user-entered values, and then calls the Button1_Click() method to handle the button click. After the Button1_Click() method has been executed, the Web server uses the new values of all the objects in the codebehind to build the HTML file that will be sent back to the user. While our example only used the Button and TextBox Web form controls, all Web form controls are handled by the ASP.NET Web server in a similar manner. Please consult the MSDN® Library for more information on specific Web form controls. Data-Bound Controls A special subset of the built-in Web form controls is the two data-bound controls, DataGrid and DataList. These two classes allow you to display and format data from a database, or from any other valid data source using the ADO.NET classes. A valid data source is any object that implements the IEnumerable interface. Data-bound controls are used in a manner similar to the built-in Web form controls. In the "Data Bindings" article, we provide an in-depth discussion of data-bound controls. Custom Web Controls If the Web form controls included with the .NET Framework do not provide your desired functionality, there are three different ways you can create your own Web control: - Create your own Web control by extending the System.Web.UI.WebControls.WebControl class. The WebControl class includes a variety of properties describing the display characteristics of the Web form control, such as BackColor (for background color), ForeColor (for foreground color), Width and Height. The WebControl.Render() method is called to produce the HTML content for your Web control and is the method that you will override in almost all custom Web controls. - Extend an existing Web form control and override one of its methods to include your own functionality. All existing Web form controls extend the WebControl class and will use the Render() method to produce their HTML output. Depending on your desired functionality, you may end up overriding the Render() method or changing the functionality of the property methods, or some combination of the two. - Create a Web forms user control. A Web forms user control can be thought of as an ASP.NET page with some restrictions. Like a normal ASP.NET page, a Web forms user control is created using the IDE, and the same controls can be added to the Web forms user control. However, because a Web forms user control is intended to be a component in an ASP.NET page and not an entire ASP.NET page, certain HTML elements, such as <HTML> and <HEAD> should not be included in the Web forms user control. A Web forms user control can be compiled and added to an ASP.NET page if it contains any of the restricted HTML elements, but the compiler will generate warning messages warning you that these elements should not be used. Also, if you include some of the restricted elements, your Web forms user control may have an unpredictable effect on the parent ASP.NET page. For example, if both your ASP.NET page and a Web forms user control contain an <HTML> element, you cannot be sure how the user's browser will display the page. Regardless of which way you wish to create your own Web form control, there are several concepts that you will need to be aware of. In this article, we will discuss these concepts and direct you to places with a more in-depth examination of creating your own Web form controls. You can find more about creating custom controls in the MSDN Magazine article Develop Polished Web Form Controls the Easy Way with the .NET Framework. Control templates Control templates allow developers to override certain aspects of a control's visual appearance. Essentially, they specify how the control's element will be rendered at run time. For example, you can customize the appearance of a DataGrid by providing a template that describes how each individual row, alternating row, or selected row will be rendered. Other iterative controls, such as DataList and Repeater also make use of control templates. Rendering When writing a custom Web form control, you must make special provisions with respect to how the control renders within the Microsoft Visual Studio® design environment. There are two things you must concern yourself with: - How the control renders on the client; that is, its client-side representation - How the control renders within the design environment The latter is achieved by associating the control with a Designer class by using the Designer attribute. When the control is dragged onto a Web form, Visual Studio .NET instantiates the Designer class to oversee the design-time rendering of the control. The Designer class performs additional functions such as prescribing how a control's properties are modified within the environment, and how such properties affect the client-side rendering of the control. Information on Designer classes can be found in the MSDN Library. ViewState The purpose of the ViewState field is to make the properties of a Web control accessible when a user posts a page back to the server. For example, when a user enters information into a page (such as a name, a credit card number, or an e-mail address) a hidden ViewState field stores those values in a single encoded string. This field allows information to be posted back to the server without loss of client-side information. See also - Building ASP.NET Custom Controls describes ASP.NET custom Web controls, provides an example of creating a custom Web control, and illustrates how you can register this custom control with Visual Studio .NET. - Web User Controls and Web Custom Controls provides an overview and examples of Web user controls and custom Web controls. - Building a Custom Web Control describes creating a custom Web control that inherits from the TextBox Web form control, and automatically adds a required field validator at run time. Thus, this custom Web control eliminates the need to use the required field validator in your ASP.NET pages. - Creating Web Server Control Templates Programmatically illustrates increasingly sophisticated ways to create templates for Repeater, DataList, and DataGrid controls, providing examples in both Microsoft Visual Basic® .NET and Microsoft Visual C#® .NET. Summary Custom tag libraries and Web controls serve a similar function, and the JLCA will automatically convert your tag libraries into Web controls. However, if you do not have the source code for your custom tag libraries, you will have to either replace the code with existing ASP.NET Web controls, or write your own custom Web controls. In either case, ASP.NET offers a wide variety of options for replacing tag libraries.
https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/aa478990(v=msdn.10)
CC-MAIN-2019-09
refinedweb
4,066
53.92
I have a script that lists all layers in an MXD and I have a script that lists all broken layers in an MXD. I want to list all layers, their name, source, description, and whether or not their source is broken. Can anyone help me with this? import arcpy, os, fnmatch, csv #Create an empty list of ArcMap documents to process... mxd_list=["A.mxd", "B.mxd", "C.mxd"] for mxd in mxd_list: mxd = arcpy.mapping.MapDocument(mxd) mapPath = mxd.filePath fileName = os.path.basename(mapPath) layers = arcpy.mapping.ListLayers(mxd) filepath = "C:/Users/USERNAME/Desktop/"+ fileName[:-4]+".csv" writer = csv.writer(file(filepath, 'wb')) sourcelist = [] for layer in layers: if layer.supports("dataSource"): layerattributes = [layer.longName, layer.dataSource] #Write the attributes to the csv file... writer.writerow(layerattributes) writer.writerow(sourcelist) del writer I figured out an easy fix: I create an array of the broken layers, then check to see if the layers in the MXD are in that array. I instruct my output to write a "yes" or "No" to determine if the layer is broken.
https://community.esri.com/thread/217113-arcpy-list-all-layers-in-mxd-and-then-make-a-note-of-whether-is-it-broken-or-not
CC-MAIN-2020-45
refinedweb
179
69.89
VFPRINTF(3P) POSIX Programmer's Manual VFPRINTF(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. vdprintf, vfprintf, vprintf, vsnprintf, vsprintf — format output of a stdarg argument list #include <stdarg.h> #include <stdio.h> int vdprintf(int fildes, const char *restrict format, va_list ap); functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2017 defers to the ISO C standard. The vdprintf(), vfprintf(), vprintf(), vsnprintf(), and vsprintf() functions shall be equivalent to the dprintf(), fprintf(), printf(), snprintf(), and sprintf() functions(3p). Refer to fprintf(3p). The following sections are informative. None. Applications using these functions should call va_end(ap) afterwards to clean up. None. None. Section 2.5, Standard I/O Streams, fprintf(3p) The Base Definitions volume of POSIX.1‐2017, stdarg.h(0p),FPRINTF(3P) Pages that refer to this page: stdio.h(0p), stdin(3p), vprintf(3p), vsnprintf(3p)
https://www.man7.org/linux/man-pages/man3/vfprintf.3p.html
CC-MAIN-2022-27
refinedweb
196
51.55
Journal tools | Personal search form | My account | Bookmark | Search: Heeh, hi! I know I said I was gonna make an actual post but I feel so sleepy, you wouldn't believe it! I am yawning so gracelessly... My jaw will get ripped open..seriously! lol Anywell, I don't have the stamina to post anything new, so I will resort to "Copy&Paste". From my bb Lori harlequinned Reply to this post and i'll give you full ten reasons I love you You must repost the ... Hi fans, neko_lovesyou and ivonnemcgruder would like to bring you Kei-chan news in form of video with subs so you can enjoy it 100%!!! bout... ...education a map of seychelles of africa import psp games uk alternative clothing culture rock russian matryoshka doll benedictine health systems rostov on don woman german enlgish dictionary copytodvd 3.0.42 patch discount freezer fridge maytag mainland southeast asia sousa biography public bank holidays cable caper code muse music running time american... ... result nancy thorp paul caverly 2006 draft first mock nfl round short easy to read guide to personal financial planning drug florida law idc eds global marketing sales enlgish dictionary online cbusa credit climbfall lifehouse lyric stanley thomas kincaid print garden of prayer michael angello white baby doll dirt devil 6-ply atv tires discount beachwood ... ...January. *sigh*I'm just goingo n and on because I'm waiting for dr. marlin to call me back. Which is very important. I really cna't do ANYTHING until he calls.And I'm NOT going over to the Enlgish department and just sitting there like a fucking bump on a long waiting around. This is why i called in the summmer to come up and fix my roster. because I would sit around my first day and not go to the... A word of warning this may be a long post: The nature of this post, ironically in Enlgish, was born from many events in my work with tourists, travel, university, friends, some other forums in the net by random people, on many viewpoints some of them very, VERY incorrect, etc. As I was surfing through the net I came across a forum rant of some US tourist that could not believe how he couldn't ... For those of you who didn't see this there is an article about Alexander posted over at ontd_trublud . The lovely girl was nice enough to translate it into Enlgish for us since it was originally in Swedish. You can find the post and article (HERE) . ... translate so far. I'll post the rest as I need to check it first. I'll try to post the entire thing soon ^^ AND... this is my first time ever to translate anything from Japanese into Enlgish (and none of the languages is my native language...) so please bear with me and whatever translation mistakes I make. If you do find a mistake, please tell me ^_^ Well then... [] comments are my own... .... Moreover, learning English is also worthwhile, because I can read more books in English than I did before. Reading in English has made me know more about western culture. I believe that learning Enlgish can also help me to acquire more advanced knowledge so that in future I can become more knowledgeable and can be more likely successful in my career. In a word, English learning is not ... so i have a new student and he's new to the country and does not know any enlgish. he's in the middle years 6-8. let me clarify, he can say the alphabet and name a few objects and that's about it. where do i start with him? sounds? phoneme work? alphabet books? or making alphabet books? do i read books aloud to him? I know dual language books would be helpful, but how can he respond to it if... Book Store Camera Celebrities Computer Cruise Dating Download Games Hotel Humor Ipod Movie Mp3 Music Ringtones School Shopping Travel Vacation Weather Result Page: 1 2 3 4 for Enlgish
http://www.ljseek.com/Enlgish_s4.html
crawl-002
refinedweb
681
72.16
[Android] Using the SQLite Database with ListView 27 September, 2010 16 Comments The dev guide provides information on how to set up a database for your application. This essentially involves extending SQLiteOpenHelper and overriding its onCreate and onUpgrade methods. Both methods are given a SQLiteDatabase object, which you use to execute the SQL queries to setup the database. In the following example, the a table called names is created with three columns – an id column and first and last columns for storing the first and last names, respectively, and inserts a couple of initial entries. public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, "CursorDemo", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS names (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, first VARCHAR, last VARCHAR)"); db.execSQL("INSERT INTO names (first, last) VALUES ('John', 'Doe')"); db.execSQL("INSERT INTO names (first, last) VALUES ('James', 'Kirk')"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Steps to upgrade the database for the new version ... } } A note on the dev guide recommends having an id column that has the same name as the BaseColumns._ID constant. The onUpgrade needs to be implemented only in subsequent versions, where the structure of the database has changed. It should perform only the necessary operations to upgrade the database (e.g. create only the new tables, drop ones that are no longer needed, alter tables old tables to match the new one, etc.). Then, to populate a ListView with data from the database: - Create the instance of your SQLiteOpenHelper and open the database with either getReadableDatabase or getWritableDatabase. You must use getWritableDatabase if you intend to add data to the database. - getReadableDatabase and getWritableDatabase will provide a SQLiteDatabase, similar to the one that was used to create or update the database. - Use one of SQLiteDatabase‘s query methods to obtain a Cursor, which provides access to the result set. - Create a CursorAdapter based on the Cursor. - Set the ListView to use the created CursorAdapter. The CursorAdapter is an abstract class, requiring the bind and newView to be defined. This allows you to control the view that is used to display the data for an entry in the view. However, in many cases, the SimpleCursorAdapter would be sufficient. This fragment uses the above DatabaseHelper class to provide data for a ListView in a ListActivity. public class SQLiteDemo extends ListActivity { private static final int DIALOG_ID = 100; private SQLiteDatabase database; private CursorAdapter dataSource; private View entryView; private EditText firstNameEditor; private EditText lastNameEditor; private static final String fields[] = { "first", "last", BaseColumns._ID }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DatabaseHelper helper = new DatabaseHelper(this); database = helper.getWritableDatabase(); Cursor data = database.query("names", fields, null, null, null, null, null); dataSource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[] { R.id.first, R.id.last }); ... setListAdapter(dataSource); } ... } In some cases, the some data will be added, deleted or changed while the view is still displaying. The view will need to be updated to reflect these changes. In Android, you only have to call the Cursor‘s requery method. This will also update the view. The following snippet follows from the above examples. It creates an entry, based on the contents of a couple of EditText fields and updates the view, simply by calling requery. ContentValues values = new ContentValues(); values.put("first", firstNameEditor.getText() .toString()); values.put("last", lastNameEditor.getText().toString()); database.insert("names", null, values); dataSource.getCursor().requery(); A full working example, using the snippets of code in this tutorial, is available here. hi kah, i am new in android and this tutorial really helped me now i am tring to using an activity funcion in activity.class as an launcher and SQLiteDemo class as its child and in manifest file i did all the manipulation that required, but still its not working and giving some error and forces me to closs. Can you send me/post a completed working version? thnks edwardpark.1997@gmail.com The full source listing should be available from here. thnks, but i want a new class like activity.class(parent) with one button on it which direct it to your SQLiteDemo class(child), simple intent i know how to use intent but its giving me a compilation error… my request is, Can you send me/post a completed working version of intent.. thnk u Thanks so much Hi, thank you for the wonderful tutorial. I Have managed to learn a lot from this. Can you help me out in deleting a row from the database on ClickedItem I have managed to include view.setOnItemClickListener (list view) But how can i delete the row based on Row ID? And also should i also refresh the database after deletion with any syntax? Please help. With love, Wesley. Hi, Try using SQLiteDatabase.delete() with the where clause set to match the row id. Hi, Thanks for the tutorial. I’m having a problem with the line The error message is The method onClick(DialogInterface, int) of type new DialogInterface.OnClickListener(){} must override a superclass method Any suggestions or help much appreciated Thanks in advance Java 1.5 did not allow @Override annotation on methods implemented from the interface. However, if you are using 1.6 or 1.7, make sure you have set the compiler compliance level to 1.6 or 1.7. First, check the setting under Window -> Preferences -> Java -> Compiler. Then, check the project properties by right clicking on the project folder, select Properties -> Java Compiler. If the “Enable project specific settings” checkbox is unticked or the level is also set 1.6 or 1.7, then it should work too. Hi, Thanks for this tutorial, very useful. I’m having an issue though. I am correctly populating the list from the database, however the very first item in the list is populated with the default layout text. It seems as though the list is being populated from item 1 rather than item 0. Any ideas how I would get around this?? Thanks Fixed, my fault, needed to remove the lines: view.setHeaderDividersEnabled(true); view.addHeaderView(getLayoutInflater().inflate(R.layout.list_layout, null)); It’s nice to know that I can do this if needed in the future. Thanks Hi, Great to hear you managed to find the answer. Originally, I had replied asking for a better idea of what you observed and wanted (its deleted now). Where is list view? Can’t see item click, listadapter or someting like between the codes. What a poor tutorial pofff.. The demo activity is using a ListActivity (a subclass of Activity), which provides the ListView for free! In other words, I don’t define nor create it explicitly in the code because it is provided automatically. The indirectly implements the ListAdapter! I wasn’t sure what you referring to by “item click” or “something” though. Thanks for the useful example! Would like to point out though that allowing the Cursor and DatabaseHelper objects to leak into the activity class feels kind of unclean. This is just my opinion but I consider that such usage should be discouraged as it violates the separation of concerns principle: and . In a real app all the database-related code would have to be located in the DatabaseHelper or some intermediate wrapper. Having db code in the activity class should be discouraged as a bad habit. Of course the example is still useful. But to make it even more useful I would recommend moving the db code out of the activity to prevent beginner programmer from following bad practices. Hi. How do I implement this SimpleCursorAdapter in my app if minSdkVersion is 8? An error tell me that this method call requires API11? How can i insert details of an incoming Sms into the db and take an action if a record contains a certain value? help me migrate to OOP!! Thank you Very good tutorial! Thanks for the good work!
https://kahdev.wordpress.com/2010/09/27/android-using-the-sqlite-database-with-listview/
CC-MAIN-2019-13
refinedweb
1,336
57.98
I am writing a program using classes, the program should allow a user to enter a time in , hours, minutes, and seconds. The program should then generate the next 20 times (in military time). The problem is I cannot find one example online or in my book that uses classes and also uses cin in main(). Can someone please help with this and let me know how I can fix this? Thanks! EDIT- I get an error at the cin statements saying it does not know how to handle >> of type Time. Code:#include <iostream> using namespace std; //Class Declaration class Time { private: int secs; int mins; int hours; public: Time(int = 0, int = 0, int = 0); void settime(int, int , int); void showtime(); void tictime(); }; // Constructor Time::Time(int h, int m, int s) { secs = s; mins = m; hours = h; } void Time::settime(int h, int m, int s) { secs = s; mins = m; hours = h; return; } void Time::showtime() { cout << "The time is " << hours << ":" << mins << "." << secs; cout << endl; return; } void Time::tictime() { secs = secs + 1; if(secs > 59) mins = mins + 1; if(mins > 59) hours = hours +1; return; } int main() { Time a, b, c; cout << "Enter hours\n"; cin >> a; cout << "Enter minutes\n"; cin >> b; cout << "Enter seconds\n"; cin >> c; for(int i = 1; i < 21; i++) { a.tictime(); a.showtime(); b.tictime(); b.showtime(); c.tictime(); c.showtime(); } system("pause"); return 0; }
https://cboard.cprogramming.com/cplusplus-programming/131854-help-cin-using-classes.html
CC-MAIN-2017-22
refinedweb
236
69.65
Issue Type: Unit Tests: Problem Created: 2011-06-11T00:18:18.000+0000 Last Updated: 2011-08-13T23:46:44.000+0000 Status: Resolved Fix version(s): Reporter: Kazusuke Sasezaki (sasezaki) Assignee: Pádraic Brady (padraic) Tags: - Zend_InfoCard Related issues: Attachments: InfoCard's XmlParsingTest has below's code. <pre class="highlight"> public function testKeyInfo() { try { Zend_InfoCard_Xml_KeyInfo::getInstance(""); $this->fail("Expected Exception Not thrown"); } catch(Exception $e) { /* yay */ } Zend_InfoCard_Xml_KeyInfo::getInstance() method will not throw Exception, if string is as argument? Please evaluate this above testcase. Is "" valid for KeyInfo?(sorry, I can't judge.) If "" is valid ,please write assert-testcase for "", and write remove failmethod above. Posted by Pádraic Brady (padraic) on 2011-08-13T23:45:50.000+0000 The method actually checks for an XML DSig namespace in the given XML string later on and throws an Exception if not found. The test description sucks, but I think that's what it's verifying. Marking as a non-issue as a result. Thanks for taking the time to report it though!
https://framework.zend.com/issues/browse/ZF-11470
CC-MAIN-2017-22
refinedweb
171
52.26
IRC log of tagmem on 2006-02-14 Timestamps are in UTC. 18:02:46 [RRSAgent] RRSAgent has joined #tagmem 18:02:46 [RRSAgent] logging to 18:02:55 [Zakim] +DanC 18:03:38 [DanC] Meeting: TAG Weekly 18:03:41 [DanC] Scribe: DanC 18:03:44 [DanC] Chair: VQ 18:04:00 [DanC] Agenda: 18:04:22 [DanC] agenda + Administrative: role call, review records and agenda, plan next meeting 18:04:28 [DanC] agenda + Face-to-face in Cannes/Mandelieu 18:04:34 [DanC] agenda + Heartbeats 18:04:44 [DanC] agenda + Principle of Least Power 18:04:52 [DanC] agenda + Issue namespaceDocument-8 18:05:04 [DanC] agenda + Issue XMLVersioning-41 18:05:07 [Zakim] +DOrchard 18:05:32 [DanC] Zakim, take up item 1 18:05:32 [Zakim] agendum 1. "Administrative: role call, review records and agenda, plan next meeting" taken up [from DanC] 18:05:36 [DanC] Zakim, who's on the phone? 18:05:36 [Zakim] On the phone I see Norm, Noah, Vincent, Ht, DanC, DOrchard 18:06:31 [DanC] -> minutes 7 Feb 18:06:39 [DanC] minutes 7 Feb good enough for me 18:06:47 [Zakim] +Ed_Rice 18:07:01 [Ed] Ed has joined #tagmem 18:07:07 [DanC] PROPOSED: to meet again 21 Feb 18:07:27 [DanC] RESOLVED: to meet again 21 Feb, NDW to scribe 18:07:34 [Zakim] +TimBL 18:07:57 [DanC] regrets timbl 21 Feb 18:08:29 [DanC] Zakim, agenda order is 1,2,3,4,6,5 18:08:29 [Zakim] ok, DanC 18:09:03 [timbl] timbl has joined #tagmem 18:09:06 [DanC] RESOLVED: to accept minutes 7 Feb 18:09:15 [DanC] (vq will remove - DRAFT - ) 18:09:28 [DanC] Zakim, next item 18:09:28 [Zakim] agendum 2. "Face-to-face in Cannes/Mandelieu" taken up [from DanC] 18:09:42 [DanC] -> meeting page 18:11:03 [DanC] DO: I'm working on the state finding... how about that for the agenda? 18:11:41 [noah] q+ to say I'm hoping we turn corner on least power before F2F, but if not maybe worth a bit of discussion 18:12:20 [noah] q- 18:12:34 [DanC] DC: suggest moving metadataInURI-31 after the other 3 technical things 18:13:09 [DanC] NM: if we don't finish least power, it might merit ftf discussion. leave it off for now, if the agenda is fluid. 18:13:59 [DanC] "Monday 27 February: 13:30 - 17:30 @@@" 18:15:29 [DanC] some sentiment for 2p, some for 1:30 18:16:10 [DanC] RESOLVED to start 13:30 Monday 18:16:51 [DanC] NM: did we end up with any liaison meetings scheduled? 18:16:54 [DanC] VQ: not at this tiem 18:16:57 [DanC] s/tiem/time/ 18:18:03 [DanC] Ed: previously we had a "what's important for the coming year" session... shall we do that again 18:18:04 [DanC] ? 18:18:31 [DanC] DC, HT: I prefer the current contents of the agenda to that sort of thing 18:18:51 [DanC] NM: perhaps make some time to chat with TV, but otherwise, yes, technical topics 18:19:30 [dorchard] dorchard has joined #tagmem 18:20:25 [DanC] TBL: hmm.. indeed, looking forward would be good... do we have a social time scheduled? it's hard to swap between technical topics and looking ahead 18:20:43 [DanC] DC: perhaps the "what did we learn this week?" session will be sufficient? 18:22:02 [DanC] HT: I'm constrained to Monday evening for an evening thing 18:22:23 [DanC] NM: I'll be on US east coast time, so not too late 18:22:53 [DanC] ACTION: VQ organize a monday evening quiet social event 18:23:04 [timbl] Zakim, who is on the phone? 18:23:04 [Zakim] On the phone I see Norm, Noah, Vincent, Ht, DanC, DOrchard, Ed_Rice, TimBL 18:23:17 [DanC] VQ: around 7pm 18:23:45 [DanC] Zakim, next item 18:23:45 [Zakim] agendum 3. "Heartbeats" taken up [from DanC] 18:27:30 [DanC] DC: there's a convention of publishing on /TR/ at least every 3 months. We haven't done it in over a year. I'm inclined to take something and publish it. 18:27:42 [DanC] NDW: yes, the ns48 finding is approved 18:29:01 [DanC] TimBL: how about concatenating the approved findings? 18:29:12 [DanC] DC: that's more work than I'm offering now 18:29:27 [timbl] 18:29:34 [Ed] list of findings 18:29:39 [timbl] 18:29:42 [DanC] 18:30:10 [DanC] (norm, I'm inclined to work from the .html only and not bother with the xml) 18:30:54 [noah] Speaking of which, the approved finding link at is to the xml 18:30:58 [timbl] This page contains the following errors: 18:30:58 [timbl] error on line 17 at column 140: Entity 'http-ident' not defined 18:30:58 [timbl] error on line 19 at column 199: Entity 'draft.day' not defined 18:30:58 [timbl] error on line 20 at column 226: Entity 'draft.monthname' not defined 18:30:58 [timbl] error on line 21 at column 247: Entity 'draft.year' not defined 18:31:01 [timbl] error on line 24 at column 283: Entity 'http-ident' not defined 18:31:03 [timbl] error on line 27 at column 370: Entity 'http-ident' not defined 18:31:06 [timbl] error on line 30 at column 431: Entity 'http-ident' not defined 18:31:08 [timbl] error on line 33 at column 488: Entity 'http-ident' not defined 18:31:11 [timbl] Below is a rendering of the page up to the first error. 18:31:45 [Norm] What page was that timbl? 18:34:02 [DanC] TimbL: good to put all this in the SOTD: (1) it's approved by the tag (2) there's lots of other stuff (3) [darn; leaked out already] 18:35:02 [DanC] PROPOSED: to publish as a W3C Working Draft 18:35:09 [Norm] Uhm, with what shortname? 18:35:15 [timbl] The eventual disposition of this text is not cler, but one possibility is it being integrated wioth other finids into a new AWWW or a second volume AWWW 18:35:43 [timbl] TAG-namespaceState 18:35:59 [DanC] namespaceState 18:37:23 [DanC] ACTION NDW: with DanC, publish WD of ns48 finding 18:37:31 [DanC] RESOLVED: to publish as a W3C Working Draft 18:38:18 [DanC] VQ: this is just one document; we'll see what we learn from this 18:38:21 [DanC] Zakim, next item 18:38:21 [Zakim] agendum 4. "Principle of Least Power" taken up [from DanC] 18:38:56 [DanC] -> least power finding, latest version 18:39:06 [DanC] -> 13 Feb draft 18:40:35 [DanC] NM: there has been much www-tag discussion of chomsky hierarchies and complexity... 18:40:39 [Norm] Norm has joined #tagmem 18:40:56 [Norm] What publication date should we use for namespaceState, DanC ? 18:41:16 [DanC] dunno 18:41:28 [noah]or 18:41:45 . 18:41:46 [DanC] HT: why not just say "occam's razor applies to computers too"? 18:41:48 [DanC] q+ 18:41:52 [noah] Indeed, on the Web, the least powerful language that's suitable should usually be chosen. This is The Rule of Least Power: 18:42:01 [noah] Good Practice: Use the least powerful language suitable for expressing information, constraints or programs on the World Wide Web. 18:42:15 [Vincent] ack danc 18:42:19 [timbl] q+ 18:42:39 [Vincent] ack timbl 18:43:04 [DanC] DanC: yes, the principle is 2 lines, but what we add is to relate it to the history of web technology development. 18:43:13 [DanC] ... e.g. how HTML is and why 18:43:23 [DanC] TimBL: yes, examples. CSS vs javascript. 18:43:37 [noah] q+ 18:44:19 [DanC] (huh? closed and continuous are pretty sharp mathematical concepts.) 18:45:09 [DanC] TimBL: the fact that you can cascade to CSS stylesheets is a result of a decision to make it declarative 18:45:34 [Vincent] ack noah 18:45:58 [DanC] q+ 18:46:06 [DanC] q+ to suggest going specific-to-general 18:47:12 [Vincent] ack DanC 18:47:12 [Zakim] DanC, you wanted to suggest going specific-to-general 18:49:07 [noah] q+ to discuss scope of this rewrite...are we thrashing? 18:49:11 [ht] HST doesn't understand why Turning-completeness is bad 18:49:27 [ht] Prolog is Turing-complete, and dead easy to analyze! 18:50:07 [DanC] hmm... I thought validator.w3.org would be impossible/impractical if the web had used TeX rather than HTML 18:50:11 [ht] SQL is Turing-complete (or close), and probably more analyzed than almost any other language 18:50:27 [Vincent] ack noah 18:50:27 [Zakim] noah, you wanted to discuss scope of this rewrite...are we thrashing? 18:50:30 [DanC] the analysis of SQL is precicely on the bits that are *not* turning complete, no? 18:55:54 [raman] raman has joined #tagmem 18:56:18 [raman] belated regrets -- I shamefully admit that I just plain forgot to call in... 18:57:10 [DanC] VQ, I suggest a straw poll: how many think it's reasonable to approve as is. 18:58:04 [noah] If you have a Turing-complete program, you don't in general know whether it even gets done 18:58:34 [noah] If I have a table in a relational database, or a list of name/value pairs, I don't have that problem. 18:58:50 [noah] DC: The halting problem is crucial. Most of the other things you want to know follow from it. 18:59:05 [DanC] no, I didn't say it's crucial. 18:59:14 [noah] Sorry, that's what I thought I heard you say. 18:59:21 [DanC] I just said you can't analyze scheme nor prolog 18:59:51 [DanC] Zakim, who's on the phone? 18:59:51 [Zakim] On the phone I see Norm, Noah, Vincent, Ht, DanC, DOrchard, Ed_Rice, TimBL 19:02:48 [DanC] PROPOSED: to approve "The Rule of Least Power" as 12 Feb draft, incorporating edits agreed by from NDW and NM 19:03:02 [DanC] so RESOLVED. 19:03:22 [raman] raman has left #tagmem 19:03:30 [DanC] ACTION NM: announce approved finding, when discussion with NDW concludes 19:03:42 [DanC] Zakim, next item 19:03:42 [Zakim] agendum 6. "Issue XMLVersioning-41" taken up [from DanC] 19:04:43 [DanC] ACTION DO: contextualize his scenarios, such as more on what is happening with SOAP and WSDL 19:04:44 [Norm] Returning to the publication of namespaceState, I chose 23 Feb as the publication date because that's the last day before the moritorium. 19:05:02 [DanC] DO: I did some work on this... 19:05:10 [DanC] ... sent them to the schema WG a few weeks ago 19:05:58 [DanC] ... haven't seen [which?] draft posted as I expected 19:06:40 [DanC] ... I hope to talk with interested people at the TP in France 19:07:34 [DanC] ... so I think this is done 19:07:37 [DanC] DC: pointer? 19:08:01 [DanC] DC/HT: getting it public has taken a back seat to other things 19:08:10 [DanC] er... rather: DO/HT 19:08:51 [DanC] NM: I think we have license to make this public already 19:09:03 [DanC] HT: yes, if you can follow up, that would be fine 19:09:30 [DanC] -- done 19:10:02 [ht] DO: Appropriate list is public-xml-versioning@w3.org 19:10:10 [DanC] ACTION DO: with NM continue and extrapolate the versioning work DO et al have been doing already, updating the terminology section. 19:10:53 [DanC] -> terminology section update from DO 13 Feb 19:11:50 [DanC] DO: I got some comments re first/last name from Misha 19:11:58 [DanC] DO: main list is public-xml-versioning 19:12:25 [DanC] not necessarily new, ht. RRSagent groks continued/done actions too 19:12:30 [DanC] or at least: scribe.perl does 19:12:32 [DanC] q+ 19:12:43 [Vincent] ack danc 19:13:33 [DanC] DC: hmm... public-xml-versioning... partial understanding isn't limited to xml 19:16:24 [timbl] q+ 19:17:14 [Vincent] ack timbl 19:18:13 [DanC] DO: public-xml-versioning was created at the suggestion of the TAG as a mechanism for collaboration with XML Schema WG. 19:19:18 [ht] q+ to incline towards focussing on XML language 19:19:27 [DanC] NM: [... about broadening from xml-specific story to a story about strings, with markup as a special case] 19:19:30 [DanC] (which appeals to me) 19:20:05 [timbl] q+ 19:20:58 [Vincent] ack ht 19:20:58 [Zakim] ht, you wanted to incline towards focussing on XML language 19:21:17 [DanC] DO: broadening makes sense to some extent, but there's a limit, and we need to be sure to deliver for XML authors 19:22:25 [Vincent] ack timbl 19:22:34 [DanC] (surely notation 3 is a webized language that's not XML) 19:22:50 [noah] Isn't URI an example of a non-QNamed namespace 19:22:50 [DanC] (webized meaning: has its terms grounded in URI space) 19:23:02 [ht] DanC, remind me what N3's media type is? 19:23:12 [ht] I.e., can I follow-my-nose to find out about N3? 19:23:13 [DanC] text/n3+rdf or some such; registration pending 19:23:33 [noah] I thought we set up in Edinburgh that versioning was about the conclusions drawn by a consumer and a producer for any particular document, where the two parties have imperfect agreement on the language they thought they were using. 19:23:39 [noah] I like that start a lot, and it's not XML-specific 19:23:42 [DanC] HT: [...] XML gives us the "follow your nose" principle, with namespaces 19:24:25 [noah] Follow your nose seems to give you something very important, which is self description. I'm not convinced that versioning should be only about self-describing documents. 19:24:29 [DanC] TBL: all stories about versioning depend on a notion of semantics/meaning... 19:26:44 [DanC] ... at the level of XML, there is only a basic infrastructure. At higher levels, e.g. HTML and RDF, there's more to say 19:27:41 [noah] zakim, who is here? 19:27:41 [Zakim] On the phone I see Norm, Noah, Vincent, Ht, DanC, DOrchard, Ed_Rice, TimBL 19:27:43 [Zakim] On IRC I see Norm, timbl, Ed, RRSAgent, Vincent, noah, Zakim, ht, DanC 19:29:42 [DanC] DC: meanwhile, I have a new .violet file from DO that I intend to check against my changePolicy.n3 work 19:29:53 [DanC] TBL: I wonder about a 4 part finding: 19:30:03 [DanC] (1) at the level of representations 19:30:15 [DanC] (2) at the level of namespaces in XML 19:30:33 [DanC] (?) [...] in HTML and such 19:30:50 [DanC] (4) an one about RDF 19:31:05 [DanC] NM: about strings of characters? 19:31:12 [DanC] TBL: that's what I meant by (1) 19:32:05 [noah] Cool. 19:32:44 [DanC] DO: let's please have some discussion on public-xml-versioning of the new terminology section 19:32:49 [DanC] +1 19:33:20 [DanC] VQ: with regret, it's time to curtail this discussion 19:33:21 [Norm] +1 19:33:26 [Norm] Uh, on the previous :-) 19:33:59 [DanC] VQ: maybe next time we'll get to ns8 19:34:12 [Norm] I'll try to get back to Jonathan and make progress on ns8 for next week 19:34:28 [Zakim] -DOrchard 19:34:29 [Zakim] -Ht 19:34:30 [Zakim] -Noah 19:34:32 [Zakim] -Norm 19:34:32 [Zakim] -DanC 19:34:33 [Zakim] -Ed_Rice 19:34:34 [Zakim] -Vincent 19:38:29 [DanC] ADJOURN. 19:39:05 [DanC] hmm... the archive cover page of doesn't say that it's a joing tag/xml-schema thingy 19:39:34 [Zakim] disconnecting the lone participant, TimBL, in TAG_Weekly()12:30PM 19:39:35 [Zakim] TAG_Weekly()12:30PM has ended 19:39:37 [Zakim] Attendees were Norm, [IBMCambridge], Noah, Vincent, Ht, DanC, DOrchard, Ed_Rice, TimBL 19:39:56 [DanC] Maintainer_Email: cmsmcq 19:41:02 [DanC] in May 2005 DO sent a pointer to 19:43:00 [DanC] hmm... Hoylen answers "Sorry, we are not able to help you" to a question that I think was pretty interesting. 21:41:11 [timbl] timbl has joined #tagmem
http://www.w3.org/2006/02/14-tagmem-irc
CC-MAIN-2017-04
refinedweb
2,841
64.24
Writing Plugins For Windows Live Writer – Getting Started In this article, I am going to show how to create a simple plugin for Windows Live Writer, starting from the beginning. Writing plugins for Live Writer is simple enough, but sometimes you just need a little helping hand, and I’m speaking from experience . First off, you will need to make sure that you have the required programs. Make sure that you have the following installed: - Windows Live Writer – download - Microsoft .NET Framework v2.0 – download - Visual Studio Express C# Edition – download (this link takes you to an installer that will require you to download the rest of the files). Now we need to tell the plugin to look at the Windows Live Writer API. In the Solution Explorer on the right hand side, right click on the References folder and select ‘Add Reference’ and browse to the Live Writer folder in your Program Files folder. The dll we want is WindowsLive.Writer.API.dll: Now that the reference has been create we need to tell the plugin to actually use the APIs, so we need to add using WindowsLive.Writer.Api; You should also add the reference for Windows Forms. So, following the same procedure we have just done, add the System.Windows.Forms reference from the .NET section, and again tell the plugin that we need to use it using System.Windows.Forms; Next we need to set the plugin’s attributes: [WriterPlugin("8638eda4-6533-4d19-9da7-ff92ff5a7590","My First Plugin", Description="This is my first plugin", HasEditableOptions=false, Name="My First Plugin", PublisherUrl="")] Now, the first thing you see in those attributes is the GUID (the combination of numbers and letters), this is unique to each plugin that you make. To get the GUID for your project, right click on the project name in the Solution Explorer and click on properties, then click on the Assembly Information button in the next screen: The second string is the text that will appear in Live Writer’s Plugins section in the Options; the Description is what appears underneath the list of plugins when you have clicked on your plugin in the options of Live Writer; HasEditableOptions is either true or false and this tells Live Writer whether to put an options button in the Plugin options (for most plugins you probably won’t need this set to true, and you certainly don’t for this example); PublisherUrl is where you put the link to your site. Underneath the WriterPlugin code, we need to set what text appears in the Insert section. So we use the code: [InsertableContentSource("From MyNewPlugin")] Time to declare the plugin’s main class public class NewPlugin : ContentSource { public NewPlugin() { } Note: after declaring the public class, you must call that class, but keep it empty as in the example above. Next we need to override the main class (this is why it was left blank), and we put in the following code: public override DialogResult CreateContent(IWin32Window dialogOwner, ref string newContent) { The ref string newContent is what actually gets put back into the blog entry, so we need to set that to equal something: newContent = "This was put in by my first Live Writer Plugin :)"; Because of how the override works, we need to return a DialogResult of OK (I will go into this in more detail in another post), so we simply put in: return DialogResult.OK; Close off anything that is open (ie, }). That is your plugin written, now we need to build it. Before we do though, we should add a command into the post-build section. So, right click on your plugin name in the Solution Explorer and click on properties. Select the Build Events section and copy the following command into the post-build event section: XCOPY /D /Y /R “$(TargetPath)” “C:Program FilesWindows Live WriterPlugins” Now we are ready to build the plugin. Hit F6 on your keyboard and watch the fun begin . Once the build has finished successfully, open up Windows Live Writer and in the Insert section, you will see your link: Click it and you will see the text we set for newContent is now in your blog entry. So we have now created a basic plugin for Windows Live Writer Next time I will talk you through how to add an image to your link. SL
http://www.liveside.net/2006/10/03/Writing-Plugins-For-Windows-Live-Writer-Getting-Started/
CC-MAIN-2014-15
refinedweb
729
62.11
In this article we are explaining How to use Base_UserDefined transform step by step with an example of Replacing Special characters from the input field(Salary). Base_UserDefined Transform This transform provides an interface to do anything that you can write Python code to do. You can use the User-Defined transform to create new records and data sets, or populate a field with a specific value, just to name a few possibilities. - Create Input File and place a Base_UserDefined transform of Data Services and link the transform with the file . - Open Base_UserDefined in the Input tab of the transform, drag and drop Input column of the input schema to the Input Schema Column Name so as to map with the Transform Input Field Name . 3. Check the Options tab and Click on Edit Options Button to customize the transform. - Check Per record , then select Python Expression Editor and Click on Launch Python Editor Button to open the Python Editor . (Option :- Per Record:- To deal all record independently ,Per collection:- Build a group of records on basis of Break group conditions like Base_match transform in this example we will go with Per record option and in next Topic we will proceed with Per collection option ) - Python Editor:- a.) I/O Field :- Insert the Input/Output fields according to requirement by Right clicking on particular option Input Fields / Output Fields then click on Insert give the field name and length of field . b.) Python API :- Python functions GetField to get the input field value and SetField to set output field value. c.) Editor :- Write your Python code here . (For more details about code refer any Python Book) - On the Output tab select the fields of interest. 7. Result :- Please find the input and the output dataset generated as screenshots below: In Part-2 I will explain used Python code in detail Exceptional example, including sample Python code.{63BBBB2B-3E0B-4444-93E6-F23C7BE977C0} Good article. Please do more about Python in DS. Does we can use all Python in DS or only DS Python API? (can we do something similar) Not sure I want my ETL/DQ tool sending me a text message. Yeah it looks cool in a demo, but why? In fact, I’m kind of wary of DS being allowed to send emails. I’d much rather just have DS be able to initiate a workflow request in a ticket system. Put whatever notification mechanisms you need into the ticket system and allow the end user to customize them. Don’t hard-code that kind of notification in DS. And, better yet, if you need that kind of notification from DS? Have DS call a web service function. I like Python as much as the next guy, but I don’t want to see Data Services as a glorified front end for Python. Thanks Scott and Mikhail for showing interest in the topic. I want to add some things before going with User Defined transform … 1. First analyse your requirement 2. Look for the existing functions of the tool. 3. If not exist go with Custom function or User defined Transform. like Mikhail shared the link in which they are sending the mail, for that BODS providing the existing function mail_to(recipients_list, subject, message, number_of_trace_lines, number_of_error_lines) Following are Python features which we can use in User_defined transform these are mentioned in help book itself.. The software has its own Python module that contains five classes: Each of these classes has one or more methods. Third-party Python libraries To ensure that your Python expressions run correctly, make sure that all third-party python libraries are in the appropriate dynamic library path for your operating system so that the dependencies are resolved. If you find that a Python library is not working correctly, update the library path (LD_LIBRARY_PATH for Solaris and Linux, LIBPATH for AIX, and SHLIB_PATH for HP) in the environment where the AL_JobService is installed, and restart the job service. Regards, Kamal Thanks. Does it mean that we can you all Python (Third-party Python libraries, classes, etc) power in DS ? The software has its own Python module that contains five classes: Each of these classes has one or more methods. Not so match as required, but i hope sap will add more methods, properties, etc. Good Post, really useful to start with the UDT.. Good Post. But I have a question does the output of the python variable is always datatyped to varchar 255. If not so is there a way to increase the variable length. Could you tell me how to store data in global variable of a particular job? Nice intro, going to have to give this a shot. Hi Kamal, I was trying the User_Defined transform as given in the above article. But i have some issues in using this transform.I am unable to figure out.Plz help me. 1)In the Options tab,Edit Options button is non clickable.Is there any setting to use it. 2)In the Output tab,STD_Sal check box is not showing in the Mapped_Name. I am attaching 2 screenshot for better understanding. Thanks in advance. Neha Khetan Hi Neha, The problem is not with User defined transform. Problem is here your windows pop up disabled or something is stopping to open . Try to check the Match transform edit option button also . If you are facing same issue try to disable the antivirus and try. This type of problems we face in match, user defined and associate transform as having edit options. see the below SAP notes. 1925789 – Click on the Edit Options button in the Match transform and nothing happens, no pop up window appears – Data Services Cause The antivirus software running on the box is not allowing the popup to occur. Resolution Disable the antivirus software or at the least exclude the Data Services install directory from it. Thanks & Regards, Ramana. Hi Venkata, I have tried with Match transform also and Edit Options is not working. As i am working in my ofc i cant disable the antivirus. Is there any other workaround? Regards, Neha Khetan Hi Neha, You can ask your admin to exclude SAP Data Services folder from Antivirus. Thanks & Regards, Ramana. I suggest a generic solution for this antivirus problem – Sometimes antiviruses are set to block programs, ports etc. automatically. Go in the settings of your AV and try to change that setting. Make it ask for user action instead. When you run your SAP stuff, your AV will detect something and then you can allow that thing to run. The downside is that other programs in your computer will also cause such warnings from your AV. To prevent that, remember which “SAP things” you allowed your AV to run. Then, add those things to the list of exceptions in your AV (AV settings or firewall settings) and switch back to automatic mode. Simple analogy – The guard (AV) at your house (computer) will shoo away anyone (software, external computers) who SEEMS suspicious. Tell the guard to show you the face of all these people and then you decide which one is to be allowed. Your were expecting your friend (SAP) to come home and have free access to your living room. The guard now shows you his face and you tell him to remember it (Adding exceptions to Virus Scanner or Firewall). After allowing your buddy inside, you tell the guard should go back to automatically shooing away anyone who looks strange, even if its your mom-in-law. Don’t add an exception for her If you really get into working with python in these user defined transforms, something handy to use if you’re using complex data structures… (dictionary,multi-dimensional lists) is the pickle module. You open a file handle and can write the contents of the dictionary to a file, then open it up from outside of DS to work on. import cPickle OH = open(r’\\Dsvcs1\repository\user\jblythe\wms_work\dctOrder.dat’,’wb’) cPickle.dump(dctOrder,OH,2) OH.close() to import it to your desktop python… import cPickle IH = open(r’C:\Users\jblythe\Desktop\dctOrder.dat’,’rb’) dctOrder = cPickle.load(IH) IH.close() this makes debugging python code for use in DS a piece of cake. Thank You for your explanation.As i am very new to this tool I was only trying to use the User Defined transform. Neha Khetan I wonder how SAP can continue to provide such a complicated, rudimentary, junk ETL tool. SSIS is far easier to learn and use compared to this monstrosity. This tutorial is excellent, but it also shows how SAP is so complex. SSIS coding – Drag script task onto screen, choose VB or C# and start coding in that language. Do ANYTHING you like. Simple. SAP – Read above tutorial and do several steps. Do ANYTHING ??? Maybe not. I wonder why SAP does not make it like SSIS. Looks like the word “intuitive” is missing from SAP’s dictionary. is there a possibility of coding in any other language? like the same BODS scripting language? learning python will add an other overhead. Hi all, 1) why are we accessign the input field SALARY as (u’SALARY’) here? 2) and what does below line this mean ? is it a list creation or something? dct[u’SALARY’] 3) while i was trying out the same example in my designer, i tried to drag the input field into editor window, but it just comes as SALARY.. no errors while validation, but it gives an error that SALARY field not found while execution. i did an online tutorial on Python, but still having difficulty in understanding the code used in above example. is there any tutorial available for python codding syntax inside BODS? 4) also how do you evaluate whether user-defined-transform or custom-function for any scenario? Hi Swetha, If you want to use user defined transform , you should know about python language. User defined transform supports only python language. Coming to custom function vs user defined transform. Custom transform , we will use when we need any iteration type of logic etc… But you cannot achieve everything using the custom transform that python does. Using custom transform , we can connect social media like twitter, facebook etc. Mean you can utilize the python language features here but this is not possible in the custom transform. Custom transform scripting is not a programming language. You can find a lot of online courses for basic python. You should learn lists,tuples, dictionaries to write decent user defined transform code. Here dct means dictionary. u means Unicode conversion of the field. We should convert Unicode that’s why we used u. Thanks & Regards, Venkata Ramana Paidi thanks Venkata. I have started on the python online tutorials. but one question is on whether/how we can enable intellisense for custom coding in BODS ? By this I mean the syntax errors highlighted, typing a dot next to module bringing a drop down of the available functions to choose from, errors highlighted in color etc while coding ? we have this feature in most programming languages and would be very helpful. but now the validation would not really catch most of the errors and I tend to write each line of code and run the job without any intellisense in case of errors. Hi Swetha, I agreed with you. There is no IntelliSense for User defined transform like other program languages IDE’s . We will know when we are executing the job only. You can check your code in the Python IDE then write in the user defined transform. Thanks & Regards, Ramana. thanks Venkata for the reply.
https://blogs.sap.com/2013/01/31/how-to-use-userdefined-transform-in-sap-bodsbusiness-object-data-services/
CC-MAIN-2017-39
refinedweb
1,948
73.58
Created on 2007-12-17 16:24 by giampaolo.rodola, last changed 2014-05-28 21:37 by vstinner. This issue is now closed. Hi, I post this message here in the hope someone using asyncore could review this. Since the thing I miss mostly in asyncore is a system for calling a function after a certain amount of time, I spent the last 3 days trying to implement this with the hopes that this could be included in asyncore in the the future. The logic consists in calling a certain function (the "scheduler") at every loop to check if it is the proper time to call one or more scheduled functions. Such functions are scheduled by the new delayed_call class which is very similar to the DelayedCall class defined in /twisted/internet/base.py I drew on. It provides a basic API which can be used for setting, resetting and canceling the scheduled functions. For better performance I used an heap queue structure. This way the scheduler() only needs to check the scheduled functions due to expire soonest. The following code sample implements an idle-timeout capability using the attached modified asyncore library. --- code snippet --- import asyncore, asynchat, socket class foo(asynchat.async_chat): def __init__(self, conn=None): asynchat.async_chat.__init__(self, conn) self.set_terminator(None) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(('127.0.0.1', 21)) self.scheduled_timeout = self.call_later(120, self.handle_timeout) def collect_incoming_data(self, data): self.scheduled_timeout.reset() # do something with the data... def handle_timeout(self): self.push("500 Connection timed out.\r\n") self.close_when_done() def close(self): if not self.scheduled_timeout.cancelled: self.scheduled_timeout.cancel() asyncore.dispatcher.close(self) foo() asyncore.loop() --- /code snippet --- Today I played a little more with it and I tried to add bandwidth throttling capabilities to the base asynchat.py. The code could be surely improved but it's just an example to show another useful feature which wouldn't be possible to implement without having a "call_later" function under the hood: --- code snippet --- class throttled_async_chat(asynchat.async_chat): # maximum number of bytes to transmit in a second (0 == no limit) read_limit = 100 * 1024 write_limit = 100 * 1024 # smaller the buffers, the less bursty and smoother the throughput ac_in_buffer_size = 2048 ac_out_buffer_size = 2048 def __init__(self, conn=None): asynchat.async_chat.__init__(self, conn) self.read_this_second = 0 self.written_this_second = 0 self.r_timenext = 0 self.w_timenext = 0 self.r_sleep = False self.w_sleep = False self.delayed_r = None self.delayed_w = None def readable(self): return asynchat.async_chat.readable(self) and not self.r_sleep def writable(self): return asynchat.async_chat.writable(self) and not self.w_sleep def recv(self, buffer_size): chunk = asyncore.dispatcher.recv(self, buffer_size) if self.read_limit: self.read_this_second += len(chunk) self.throttle_read() return chunk def send(self, data): num_sent = asyncore.dispatcher.send(self, data) if self.write_limit: self.written_this_second += num_sent self.throttle_write() return num_sent def throttle_read(self): if self.read_this_second >= self.read_limit: self.read_this_second = 0 now = time.time() sleepfor = self.r_timenext - now if sleepfor > 0: # we've passed bandwidth limits self.r_sleep = True def unthrottle(): self.r_sleep = False self.delayed_r = self.call_later((sleepfor * 2), unthrottle) self.r_timenext = now + 1 def throttle_write(self): if self.written_this_second >= self.write_limit: self.written_this_second = 0 now = time.time() sleepfor = self.w_timenext - now if sleepfor > 0: # we've passed bandwidth limits self.w_sleep = True def unthrottle(): self.w_sleep = False self.delayed_w = self.call_later((sleepfor * 2), unthrottle) self.w_timenext = now + 1 def close(self): if self.delayed_r and not self.delayed_r.cancelled: self.delayed_r.cancel() if self.delayed_w and not self.delayed_w.cancelled: self.delayed_w.cancel() asyncore.dispatcher.close(self) --- /code snippet --- I don't know if there's a better way to implement this "call_later" feature. Maybe someone experienced with Twisted could provide a better approach. I would ask someone using asyncore to review this since, IMHO, it would fill a very big gap. If you want attention, please post to python-dev if you didn't already. Or widen the audience to python-list if you want to. The issue #2006 (asyncore loop lacks timers and work tasks) was closed as duplicate of this one... noting this just for reference. Giampaolo: Can you pleaes bring this up on python-dev or the normal python mailing list for further discussion on the issue? Sean, I already tried to raise two discussion attempts on both lists here: ...and here: ...but no one seems to be interested at this feature. Moreover, before doing anything against asyncore and asynhat there are a lot of long-time pending patches which should be committed first; see here: Unfortunately, it appears that asyncore and asynchat are caught in a deadlock, in which it is demanded that certain patches be applied before any further work is done, but nobody (even among those making the demands) is both willing and able to review and apply those patches. We need this situation to be resolved, preferably by somebody with commit access doing the necessary work, but failing that by allowing new patches and requiring the old ones to be updated at whatever time somebody decides to actually address them. Generally speaking, delayed calls, and/or a practical scheduling algorithm are useful for async servers. Since 2.6 and 3.0 are on feature freeze right now, this is going to have to wait for 2.7 and 3.1 . I'll make sure to get something like this into 2.7 / 3.1 . I try to revamp this issue by attaching a new patch which improves the work I did against asyncore last time. The approach proposed in this new patch is the same used in the upcoming pyftpdlib 0.5.0 version which has been largely tested and benchmarked. In my opinion, without the addition of an eventual paired heap module into the stdlib there are no significant faster ways to do this than using the common heapq module. The patch in attachment includes: - various changes which improve the speed execution when operating against the heap. - a larger test suite. - documentation for the new class and its methods. Josiah, do you have some time to review this? I have an updated sched.py module which significantly improves the performance of the cancel() operation on scheduled events (amortized O(log(n)), as opposed to O(n) as it is currently). This is sufficient to make sched.py into the equivalent of a pair heap. From there, it's all a matter of desired API and features. My opinion on the matter: it would be very nice to have the asyncore loop handle all of the scheduled events internally. However, being able to schedule and reschedule events is a generally useful feature, and inserting the complete functionality into asyncore would unnecessarily hide the feature and make it less likely to be used by the Python community. In asyncore, I believe that it would be sufficient to offer the ability to call a function within asyncore.loop() before the asyncore.poll() call, whose result (if it is a number greater than zero, but less than the normal timeout) is the timeout passed to asyncore.poll(). Obviously the function scheduler would be written with this asyncore API in mind. I'm looking forward to having this functionality in asyncore. It would help me remove some unwanted hackery from my own code.. Josiah, is your updated sched module the one described in this blog post? Is there an issue in the bug tracker about it? >. Personally I can't think of any use case in which that would come helpful, but perhaps it's because I've never mixed asyncore and threads. Can't you do that by simply overriding the global list? The idea is to be able (whether you see a use case or not) to use different tasks lists simultaneously. Messing with globals is the worst possible API for that. All you need is to add a tasks=None argument to the loop() signature, rename the global tasks list to (e.g.) default_tasks, and add this to the top of loop: if tasks is None: tasks = default_tasks similar to what it does for map. You'd also have to pass the tasks list to the scheduler() call and the call_later() constructor. Defaulting to a global is fine. Forest: To answer your question, yes, that blog post discusses a better variant of sched.py , but no, there isn't a bug. I should probably post it some time soon for 2.7/3.1 inclusion. > You'd also have to pass the tasks list to the scheduler() call and the > call_later() constructor. Defaulting to a global is fine. Unless I change the current API I can't add a new optional arguments to call_later constructor because it already uses *args **kwargs: def __init__(self, seconds, target, *args, **kwargs): You could solve this with a "reserved" keyword argument _tasks. Or you could have two different factory methods, call_later_with_tasks() and call_later(). I've just attached a patch to sched.py and asyncore.py to offer a richer set of features for sched.py, with a call_later() function and minimal related classes for asyncore.py to handle most reasonable use-cases. There is no documentation or tests, but I can add those based on Giampaolo's tests and docs if we like this approach better. Here's a better patch without tabs. A new patch is in attachment. Changes from the previous one (Sep 2008): - renamed "deafult_tasks" global list to "scheduled_tasks" - loop(), scheduler() and close_all() have a new "tasks" keyword argument defaulting to None - close_all() other than iterating over all existing dispatcher instances and closing them, also iterate over any unfired scheduled call found in "tasks" list, cancel() it and finally clears the list. - call_later constructor accepts a reserved _tasks argument - call_later overrides __lt__ instead of __le__ Tests and documentation are also included. I fixed some bugs with my patch, merged in Giampaolo's tests and documentation, and altered the API to match Giampaolo's API almost completely. This new version differs from Giampaolo's patch only in underlying implementation; this uses a modified sched.py, and doesn't have a standard "execute outstanding methods" function built into asyncore (asynchat.scheduled_tasks.run(time.time()) is sufficient). The major difference is that the modifications to sched.py offer a fast cancel/reschedule operation, which Giampaolo's lacks. At the language summit last Thursday there was widespread disappointment with the changes to asyncore.py in 2.6, which broke almost all code that actually uses it. Unfortunately, the documented API is lame, so everybody depended on undocumented internals, and those were changed without respect for established use. I'd like to prevent more problems like that. IIRC, there was a threat to remove asyncore because there were no maintainers, no one was fixing bugs, no one was improving it, and no one was really using it (I believe the claim was that people were just using Twisted). The patches that were ultimately committed to 2.6 and 3.0 were committed 3 months prior to 2.6 release, after having languished for over a year because no one would review them. If people care about where asyncore/asynchat are going, then it is *their* responsibility to at least make an effort in paying attention at least once every few months or so. The delayed calls feature discussed in the current bug doesn't alter the behavior of previously existing code, except there are additional checks for pending tasks to be executed. If people never use the call_later() API, it is unlikely they will experience any difference in behavior. If you are concerned about the sched module, I'd be happy to do a search for it's use to verify that people aren't relying on it's internal implementation, only the features of it's external API. I guess the Zope developers aren't that tuned in to core Python developement. They were sorely bitten. I don't think you can claim that users should be tuned in to python-dev just to assure their favorite module isn't removed or broken. It behooves you to request their feedback now that you know there still are asyncore users, not to hijack the module for your own purposes. IIRC one option discussed at the summit was to restore asyncore to its pre-2.5 state and to slowly end-of-life it, giving Zope and other users plenty of time to start maintaining their own copy (which they've half-done already with all the monkey-patching that goes on :-), and create a new module with a better specified API that won't require users to use undocumented internals. Part of this (even if we don't actually roll it back to the 2.5 version, which is controversial) would be not adding new features. I'm happy to let them know proposed changes now that I know issues exist, but you have to admit that they were pretty under-the-radar until 4-5 months *after* 2.6 was released. If there is a mailing address that I can send proposed changes to asyncore so that they can have a say, I'd be happy to talk to them. Generally, what you are saying is that I'm damned if I do, damned if I don't. By taking ownership and attempting to fix and improve the module for 2.6 (because there were a bunch of outstanding issues), people are pissed (generally those who use Zope and/or medusa). Despite this, other people have continued to use it, and have been pushing for new features; event scheduling being one of the major parts. Pulling asyncore out of Python is silly. Not improving the module because of fear of breakage is silly. I'm happy to hear suggestions from the Zope crew, but I'm only going to put as much effort in communicating with them as they do me. Josiah, you need an attitude adjustment. The breakage of asyncore in 2.6 was real and is now harming adoption of 2.6 by those folks (who are by nature not early adopters -- their customers are typical enterprise users). Talk to Tres Seaver and Jim Fulton. They occasionally post to python-dev but that doesn't mean they read all of it. Here's a question: How do we fix 2.6? From what I've read, the only answer I've heard is "revert to 2.5 in 2.6.2", which has the same issues as adding True/False in 2.2 . I agree that Zope not working in 2.6 is a problem, I agree that the documentation for asyncore is lacking, I agree that I probably wasn't as vocal as I could have been prior to the changes, I agree that 3rd parties relying on internal implementation details not covered in the limited documentation is a problem, I agree that we need to figure something out for asyncore 2.7 and beyond, I agree that we need to figure something out for asyncore 2.6 issues related to Zope and Medusa, ... I'm happy to take the blame for changing asyncore internals in Python 2.6 . And I've not stated otherwise in any forum. At the time I thought it was the right thing to do. If I could change the code retroactively, I would probably do so. But it seems to me that "fork asyncore", "pull asyncore out of the stdlib", and "revert to 2.5" are all variants of the cliche "throwing the baby out with the bathwater". There are good bug fixes in 2.6, and depending on how much of the internals that Zope and/or medusa rely on, we might even be able to write a short wrapper/adapter to throw in to Zope and/or asyncore. I'll contact Tres and Jim, and hopefully be able to come to some reasonable solution. Well arguably asyncore is unsalvageable due to the undocumented internals issue, and we sure know a bit more about how to design a *good* asynchronous API than we did when asyncore was created. (One hint: don't make subclassing part of your API.) The Zope folks at the meeting in all seriousness proposed reverting to the 2.5 version of asyncore since "it is broken in 2.6". Since I don't use it myself I really have no idea if anyone is using the 2.6 version. I don't know what are the problems experienced by the Zope folks (is there a place where this is discussed?) but I can guess that they're having problems with asynchat rather than with asyncore, since the latter hasn't changed too much between 2.5 and 2.6 except for low level connection related bug fixes. The greatest difference in the new asynchat is that the producer_fifo attribute is no longer an asyncore.fifo() instance but a deque(). Python 2.5: > self.producer_fifo = fifo() Python 2.6 > self.producer_fifo = deque() Although they're quite similar the old code relying on the fifo() API can't obviously work anymore. This could have been a bad choice and there are probably other changes that might have caused the problem (one other change that comes to my mind is the different readable() writable() implementation). An alternative to completely reverting asynchat.py to the 2.5 version, which is somewhat too drastic IMO, could be identifying what are the changes that caused the incompatibility, and reverting those parts only for 2.6.2, in a way that no one (2.5 and 2.6 users) is affected. If there's a place where this is discussed I could contribute in some way since I've been working on asynchat/asyncore for a long time now. To be wholly clear about the issues, it's not with asyncore, the core asynchronous library, it's with asynchat and the internal changes to that. Any changes to asyncore were to fix corner cases and exceptions. No API, internal or external was changed. People who subclassed from asyncore should have no problems. People who subclassed from asynchat may have problems. If we want to revert selected changes to asynchat, that's fine with me. AFAICT, there is only 1 substantial bugfix in asynchat (if your text terminator isn't discovered in the first ac_in_buffer_size bytes read since the last terminator, your connection will hang), which is easily pulled out. Offering a compatibility mode is also relatively easy. Six months ago you were 'eh' with what was going on with the asyncore libraries (see messages from early October). Over a year ago everyone on python-dev cared so little about the libraries that it was preferred to give me commit access than for someone to review the code. Now everyone seems willing and happy to remove the library because it is "unsalvageable". Ultimately the change that broke Zope/medusa was replacing the use of asynchat.fifo with a deque, and getting rid of ac_out_buffer. Those are *tiny* changes that we can change back, temporarily pull into Zope, and tweak Medusa to fix (I'd be happy to offer a patch to AMK to produce Medusa 0.5.5). As for your "subclassing is bad" comment, Twisted, wxPython, SocketServer (SimpleXMLRPCServer, TCPServer, ...), sgmllib.SGMLParser, etc., all use subclassing as part of their APIs. Josiah, there's no need to get all defensive and passive-aggressive about it. I'm just reporting about strong feelings that were brought up at the language summit -- to my surprise too! Admitting somebody made a mistake would be step one (and I'll gladly admit I wasn't aware of the Zope issues at the time or I would've warned you). I've asked Tres Seaver and Jim Fulton to comment on this issue, I really can't help you more with the details of which module actually broke and what to do about it. I'm just recommending you use your commit privileges wisely. I am the developer of Supervisor () which depends on (and extends) Medusa 0.5.4, which itself depends on some implementation details of pre-2.6 versions of asynchat (e.g. "ac_out_buffer"). I need to make sure Supervisor works with Python 2.3, 2.4, and 2.5, as well as Python 2.6. To do so, I intend to just ship the Python 2.5 version of asyncore/asynchat along with Medusa 0.5.4 and Supervisor in the next Supervisor release; straddling the asynchat stuff would just be too hard here. I don't know of any other consumers of Medusa other than Zope and Supervisor, so maybe Medusa should just ship with its own version of asyncore and asynchat forever from now on; I'm certainly not going to take the time to "fix" Medusa to forward port it to the 2.6 version of asynchat. I might argue that in retrospect the the current implementation of asynchat might have been better named "asynchat2", as the changes made to it seem to have broken of its major consumers. But we can work around it by just forking, I think. Looking back, I think Zope and Medusa should have adopted and evolved their own copy of asynchat a long time ago... > Looking back, I think Zope and Medusa should have adopted and evolved > their own copy of asynchat a long time ago... This statement is puzzling. No big deal, but I'm curious why you say this. For the record, afaict, Zope wasn't broken by this. Supervisor isn't part of Zope. Sidnei da Silva had to put some "straddling" code in the Zope2 trunk to workaround the 2.6 changes to asyncore / asynchat: - - . On Apr 2, 2009, at 1:27 PM, Guido van Rossum wrote: > > Guido van Rossum <guido@python.org> added the comment: > > . Not that I'm aware of. I did add the ability to pass in alternative map objects, which is the only change we needed that I'm aware of. I think I made that change before or soon after asyncore was added to the standard library. > The resulting coupling between Zope and asyn* has > meant that the de-facto API of asyn* was much more than the documented > API. If we were monkey patching it, it would be at our own risk, which is why we'd copy the module if we needed to. That has its own problems of course. I rue the day I forked doctest. :( >. I've read a good argument that subclassing across implementation packages is a bad idea. If a framework offers features through subclassing, it should define the subclassing interface very carefully, which asyncore doesn't. Jim -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Guido van Rossum wrote: >. Zope does not monkeypatch asyncore or asynchat, and hasn't since at least Zope 2.5 (the oldest checkout I have, first released 2002-01-25). Tres. - -- =================================================================== Tres Seaver +1 540-429-0999 tseaver@agendaless.com Agendaless Consulting -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - iD8DBQFJ1QLqFXKVXuSL+CMRAhelAJ9yYgo1RXUhWR2cH8CjYRoXz/qsvACgg13O BFAiRoYP8AWVgQVWBhVhB+4= =wj2y -----END PGP SIGNATURE-----? On Apr 2, 2009, at 3:35 PM, Josiah Carlson wrote: > > Josiah Carlson <josiahcarlson@users.sourceforge.net> added the > comment: > >? Actually, the documentation is better than I remember it to be. The problem is that subclassing is a much more intimate interface between components that a call interface. In the case of asyncore, the methods being overridden have non-trivial default implementations. Overriding methods often entails studying the base-class code to get an idea how it should be done. The subclassing interface for asynchat appears to be much cleaner, but even then, you need to study the base class code to make sure you haven't accidentally overridden any base class attributes. I wish classes that exposed subclassing interfaces were more careful with their internal names. Jim Assuming this is still desirable I'd really like to move forward with this issue. The current situation is that we have two patches. My patch ======== pros: * affects asyncore.py only * (imho) cleaner, as it just adds one class * stable, as it has been used in pyftpdlib for over 3 years now cons: * significantly slower compared to Josiah's "paired-heap" approach Josiah's patch ============== pros: * significantly faster cons: * affects asyncore.py and sched.py * sched.py is modified quite heavily, also it's not clear whether that has been done in a fully retro-compatible way or not, so a full review from someone who has experience with this module would be needed * it seems that sched.py gains brand new functionnalities which are not necessarily related with asyncore, hence tests and documentation should be added. Furthermore, belonging them to sched.py, maybe they should be treated in a separate issue Both patches should no longer apply cleanly so they should be adjusted a little and the missing parts (full tests, documentation including example usage, etc...) completed. It seems we both agree on the API, which is both simple and has the extra advantage of being the same as Twisted's. Now it's only a matter of deciding what to do about the internal implementation. I agree with the points raised against Josiah's patch. I'm not sure O(n) cancellation is really a concern. The main focus of optimization should be the scheduler's loop itself, and both approaches have an O(log n) complexity there AFAICT. Also, the cancellation optimization could be backported into Giampaolo's patch. One area tests should check for is when scheduling operations are done from a delayed call. Especially, a delayed call rescheduling itself. By the way, it's too late for 2.7, so this is only for 3.2 now. I like the idea of leveraging the sched module. It encapsulates the priority queue, allowing the user to be agnostic to the underlying data structure. If someday we have a data structure in the collections module that provides an efficient delete-key operation, we can switch. Giampaolo's patch forever ties us to heapq. That said, I believe Josiah's patch could be simplified considerably. Here are two ideas, which can be evaluated separately: - The performance improvements to sched should be part of a separate patch and listed under a separate issue in the tracker. -. Also, fix one small bug: - Add a function to create a sched.scheduler(). Several functions take an optional "tasks" parameter, but there's no way to allocate a scheduler without peeking at the implementation and duplicating how it allocates the global one. Some prodding from Giampaolo got me to pull out and simplify the sched.py changes here: issue8684 . That should be sufficient to add scheduling behavior into async socket servers or otherwise. >. I think a wrapper around sched.py is necessary. Now that I wrote tests for it I realized its API is pretty rusty and old. Adding a call: scheduler = sched.scheduler(time.time, time.sleep) scheduler.enter(10, 1, function, (arg,)) ...vs: asyncore.call_later(10, function, arg) Cancelling a call: scheduler = sched.scheduler(time.time, time.sleep) event = scheduler.enter(10, 1, function, (arg,)) scheduler.cancel(event) ...vs: event = asyncore.call_later(10, function, arg) event.cancel() Moreover, reset() and delay() methods are not implemented in sched. By using call_later you can do: event = asyncore.call_later(10, function, arg) event.reset() event.delay(10) By using sched.py you'll have to recreate a new event from scratch (scheduler.cancel(event) -> calculate the new timeout, scheduler.enter(newtime, 1, function, (arg,)).')). > Adding a call: > > scheduler = sched.scheduler(time.time, time.sleep) > scheduler.enter(10, 1, function, (arg,)) > > ...vs: > > asyncore.call_later(10, function, arg) I don't really see the difference. How hard it is to build a scheduler object at startup and store it somewhere in your globals or on one of your objects? The main improvement I could see would be to make the arguments to sched.scheduler() optional, and default to time.time and time.sleep. On Tue, May 11, 2010 at 11:55 AM, Giampaolo Rodola' <report@bugs.python.org> wrote: > Moreover, reset() and delay() methods are not implemented in sched. > >')). These are nice features, but wouldn't it make more sense to add them to sched? That would provide them to other users of sched, while keeping the asyncore code simpler. This patch is now available as a recipe for python 2.x: With issue13449 fixed I think we can now provide this functionnality by adding a specific section into asyncore doc which explains how to use asyncore in conjunction with sched module. As such, asyncore.py itself won't need any change. > With issue13449 fixed I think we can now provide this functionnality by > adding a specific section into asyncore doc which explains how to use > asyncore in conjunction with sched module. How would it work? Now that I think of it maybe some kind of wrapper would still be necessary. As of right now, we'd do something like this. At the core we would have: import asyncore, asynchat, sched # global scheduler = sched.scheduler() while 1: asyncore.loop(timeout=1.0, count=1) # count=1 makes loop() return after 1 loop scheduler.run(blocking=False) Then, every dispatcher can define a scheduled function of its own: class Client(asynchat.async_chat): # an already connected client # (the "connector" code is not included in this example) def __init__(self, *args, **kwargs): asynchat.async_chat.__init__(self, *args, **kwargs) self.set_terminator("\r\n") self.set_timeout() def set_timeout(self): self.timeout = scheduler.enter(30, 0, self.handle_timeout) def reset_timeout(self): scheduler.cancel(self.timeout) self.set_timeout() def found_terminator(self): scheduler.cancel(self.timeout) self.timeout = scheduler.enter(30, 0, self.handle_timeout) # do something with the received data... def handle_timeout(self): self.push("400 connection timed out\r\n") self.close() def close(self): scheduler.cancel(self.timeout) asynchat.async_chat.close(self) > while 1: > asyncore.loop(timeout=1.0, count=1) # count=1 makes loop() return after 1 loop > scheduler.run(blocking=False) Isn't that both ugly and imprecise? The right way to do it is to set the timeout of the select() call according to the deadline of the next scheduled call in the scheduler. But you probably need to modify asyncore for that. New changeset 59f0e6de54b3 by Giampaolo Rodola' in branch 'default': (sched) when run() is invoked with blocking=False return the deadline of the next scheduled call in the scheduler; this use case was suggested in Where does this issue stand now? Did the applied sched patch supersede the proposed asyncore patch? Is enhancing asyncore still on the table given Guido's proposed new module? A new implementation is part of Tulip (tulip/selectors.py); once Tulip is further along it will be a candidate for inclusion in the stdlib (as socket.py) regardless of whether tulip itself will be accepted. I have no plans to work on asyncore. On Fri, Mar 8, 2013 at 12:03 PM, Terry J. Reedy <report@bugs.python.org> wrote: > > Terry J. Reedy added the comment: > > Where does this issue stand now? Did the applied sched patch supersede the proposed asyncore patch? Is enhancing asyncore still on the table given Guido's proposed new module? > > ---------- > nosy: +terry.reedy > versions: +Python 3.4 -Python 3.3 > > _______________________________________ > Python tracker <report@bugs.python.org> > <> > _______________________________________ I'm not sure how many users asyncore has out there nowadays, but if it has to stay in the stdlib then I see some value in adding a scheduler to it because it is an essential component. If this is still desirable I can restart working on a patch, although I'll have to go through some of the messages posted earlier in this topic and figure how's best to proceed: whether reusing sched.py or write a separate scheduler in asyncore.py. Now asyncio/tulip has landed in the 3.4 stdlib, asyncore will be effectively obsolete starting 3.4 (even if we don't mark it so). Its presence is required for backwards compatibility, but that doesn't mean we should encourage people to keep using it by adding features. If you agree, please close this issue. asyncore documentation now starts with this note (which was approved by the asyncore maintainer): "This module exists for backwards compatibility only. For new code we recommend using asyncio." Since asyncio is now part of the stdlib, I don't think that it's worth to enhance asyncore. asyncore has design flaws like its poll() function which doesn't scale well with the number of file descriptors. The latest patch for this issue was written 5 years ago, I don't think that many people are waiting for this feature in asyncore. Delayed calls are part of asyncio core, it's well designed and *efficient*. So I'm now closing this issue. "Upgrade" your code to asyncio!
https://bugs.python.org/issue1641
CC-MAIN-2017-47
refinedweb
5,480
67.15
I have a attribute table for contours every 10 feet but would like to label ONLY the major contours using the value specified in the Contour field. Found some similar messages but can't get the syntax correct. Please help. New to Python. I have a attribute table for contours every 10 feet but would like to label ONLY the major contours using the value specified in the Contour field. Found some similar messages but can't get the syntax correct. Please help. New to Python. James, Here is my modification. I have a string field called Line_typ which has the contours I want to label as major. Do I need to have an integer field like you do in the example and have values for each of the line types to choose a number for all those that are called major that I want to label or can I use that string field? This did not work. Siran I created a field called index and used the value 1 for all major contours. See above. Still get error message about line 1 syntax Did you set the field type to Short Integer for the Index field? I setup the same way and do not get any error. I am a big fan of label expressions but since the label expression does not seem to be working for you, why don't you try Label Classes. Change the Method under the Labels tab to "Define classes of features and label each class differently". Next, click on the SQL Query button to essentially do a Definition Query for [Lin_typ] = "Major". Set your Label Field to be [Contour] and then setup the text symbology: I hope this helps. Cory Right answer! much easier. Will I ever learn Python? I really think its cool...when it works! Thanks so much. Your expression was actually written for VBScript, not the Python parser. Maybe you should double-check that. You are using a VB Script language Label expression. Python has no Then with an if statement or Function/End Function syntax. For python you have to use == to mean equals in an if statement. A single = assigns a value only in python, which cannot be done here. The Expression that will work for Python is: def FindLabel ([Contour], [Index]): if int([Index]) == 1: return [Contour] else: return "" You have to convert Index to an Int, because the Label parser automatically converts all field values to string, since only strings make valid labels. Otherwise numeric fields and date fields would throw errors unless you explicitly converted them to string. So you have to convert back to int or flt to make numbers behave like numbers. Alternatively, this will work: def FindLabel ([Contour], [Index]): if [Index] == '1': return [Contour] else: return "" For VB Script it would be: Function FindLabel ([Contour], [Index]) If cint([Index]) = 1 Then FindLabel = [Contour] Else FindLabel = "" End If End Function It does not work because Index contains Null values and Null values cannot be converted to Int. So you need to handle Null values (VB Script would throw the same error). def FindLabel ([Contour], [Index]): if [Index] == None: return "" elif int([Index]) == 1: return [Contour] else: return "" Hey, I think I figured it out....The index field that has 1's for what I want to label had <NULL> as the value for the one's I do not want to label. Once I changed that to a 0 it labeled them like I wanted. thanks you so much for the clarification. I will keep that script. Be sure to use my last version. If Nulls are at all possible it is best to handle them explicitly in the expression to avoid an error rather than having to eliminate all Null values before the error will stop. If this is a geodatabase you should set the Default value for the Index field to 0 or 1 (or -1 to act as unassigned) to avoid Null values. ArcGIS Help 10.1 "Placing labels for contours" should do what you want.
https://community.esri.com/thread/114551
CC-MAIN-2019-04
refinedweb
676
72.76
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi everyone! I've created a custom field and I would like it to be set automatically to a User's Group by who reported the issue, so that if I'm a reporter in fx jira-developer group, the custom field is set automatically to jira-developer group when I report an issue. I need this cause I would like to be able to get a pie chart of what group is reporting the most / fewest issues. I've tried the plugin Dynamic Forms but it didn't quite do the trick. Best regards Kristín If you have the Script Runner plugin installed, then you could try having a Scripted Field which will display the Reporter's group. In your scripted field, you would need a groovy script like this: import com.atlassian.jira.ComponentManager import com.atlassian.jira.user.util import com.atlassian.jira.issue.Issue import com.atlassian.crowd.embedded.api.User def componentManager = ComponentManager.getInstance() def userUtil = componentManager.getUserUtil() def Reporter = issue.getReporter().getDisplayName(); GroupList = userUtil.getGroupsForUser(Reporter); return GroupList[0].getName(); That code would just display one group. You'd have to modify it to display more groups. Thanx guys, you are awesome! :) I'll try this out and hopefully it will work out I'm getting error when I try to run the script - something you can help with? org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script7.groovy: 2: unable to resolve class com.atlassian.jira.user.util @ line 2, column 1. import com.atlassian.jira.user.util ^ 1 error This is interesting. Do you have just one group for each user? If not, then how do you plan to sort out which group exactly should be in the custom field. I have not done it, but I think a workaround is possible using Jira Suite Utilities and configure a post function to copy.
https://community.atlassian.com/t5/Jira-questions/Jira-Is-it-possible-to-automatically-set-the-User-s-Group-to-a/qaq-p/155729
CC-MAIN-2018-22
refinedweb
332
51.55
How can I dump a log of my commits showing only the ones with notes of a given namespace? Commits without notes, or notes not belonging to a given namespace should be filtered out In the text dump I do not want just the note, also the commit info. I have played with: show refs/notes/ and I believe the solution might be there rather than with "git log". However I am still having some problems to find the right command showing also all commits. git notes will give you the id of each note and what object it applies to. So the second column is what you want. $ git notes f5ac8874676de3029ffc8c31935644ff7c4deae0 07ca160c58cf259fe8bb5e87b9d9a7cbf8845f87 62ecfc95355587d6d1f779fcaca6e4f53d088ccc eb6c60b9dcb56219d9d882759c0bf928f6d6c3fa Grab that last column using cut and pass them into git show. $ git notes | cut -d' ' -f2 | xargs git show To pick a specific namespace, add a --ref=namesapce to git notes. $ git notes --ref=namespace | cut -d' ' -f2 | xargs git show There's a slight problem here, git show will show the current checkout if passed no arguments. So if there's no notes you're going to get misleading output. I leave this as an exercise to write a more interesting program to fix that.
https://codedump.io/share/dke8iSSMlSxB/1/filter-git-log-to-show-only-commits-with-notes
CC-MAIN-2017-47
refinedweb
202
78.79
Learn how to compare file path in Java? AdsTutorials In this section, we will discuss how to compare pathname of two file for the equality of their path. For this purpose, we use compareTo() method. First ,we create two instance of class-same or different and check there equality using compareTo() method. The compareTo() method return 0(zero), if the argument is equal to this abstract pathname. Given below example will give you a clear idea : import java.io.File; public class FilePathCompare { public static void main(String[] args) { File file1 = new File("C:/Folder/dev.txt"); File file2 = new File("C:/Folder/dev.txt"); if (file1.compareTo(file2) == 0) { System.out.println("Both paths are same!"); } else { System.out.println("Paths are not same!"); } } } If both path name are same : Advertisements We have 1000s of tutorials on our website. Search Tutorials tutorials on our website. Posted on: February 19, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles Advertisements Ads Ads Discuss: File Path compare in java Post your Comment
http://roseindia.net/java/example/java/io/FilePathCompare.shtml
CC-MAIN-2017-51
refinedweb
180
69.89
Back from London/Boston trip LinuxWorld in london was a surprisinggly small to me, smaller than the "Solution Linux" equivalent in Paris (I will talk about GNOME there in Feb). Apparently I was a bit too loud during my speech about Xen, people from the other room came to tune down the volume of my speakerphone (sorry gary :-) . GNOME Summit Most notable points of the Summit were the focus on performances, Federico did a good job of pointing people at tools though I'm surprized most people looked like having their first session on optimizations. John Rice also made a nice presentation on DTrace (but he seems to have fogotten his syscalls ;-), looks really good, too bad I will have a hard time using it at the moment (I'm waiting for a complete OpenSolaris distro with Xen 3.0 support, yeah I don't hold my breath ;) . Anyway the Summit is really about talking to the people and try to focuse on technical areas, but I didn't spot any big innovation. Servers First the alim for my home network dies while I was on the trip, then there were some problems with INRIA lab power where I host my boxes, fr.rpmfind.net was down for most of those 2 weeks, then xmlsoft.org is now down for similar reason waiting for someone to push the Power button (use in the meantime). On the good news it seems the rpmfind.net server at speakeasy will be repaired :-). Oh and the server in my closet don't seems to find the network, I don't yet know why. Vacations I also took a few days of vacations while I was around Boston, spent last week-end in Cape Cod with Jeff Johnson, that was cool, I enjoy cooking and being able to work with a real kitchen and barbecue after a week cooking in the hotel room was a pleasure :-). Oysters are better in France but you can find excellent (i.e. ultra fresh) fish and sea food around Boston ! I was also hosted at Seth place, we tried to kill ourselve twice, first with an expresso machine (nice job Seth ;-) and next evening by sailing at night on the Charles River. Sailing at night is amazing, doing that within the town was fantastic, really, I only feel so stupid because I worked for 18 months at MIT and never discovered they had that sailing club ! There is something going on in Norway Can someone tell me what is happening at Opera ? First they make that GTK version of their browser for Nokia, great. But I just found those selected pieces from their Changelog for windows 9.0 p1 release : - Removed support for XML namespaces in HTML documents Hummm is that a good idea ? I got troubles in that area with libxml2 - Added support for xml:id. Yay !! - Added support for XPath 1.0 hell is freezing ! - Added support for XSLT 1.0 and the XSLTProcessor constructor okay hell definitely froze !!! Did Håkon spent his summer in Redmond or what ;-) ? As a followup on a relatively heated debate we had at the W3C Advisory Board in 2000 (IIRC) would someone happen to know the runtime size of their XPath and XSLT implementations (in term of compiled code size for i686), I'm ready to keep that for myself if needed...
http://www.advogato.org/person/DV/diary.html?start=217
CC-MAIN-2016-07
refinedweb
561
68.7
i want to develop a code for when user clicks on forgot password then the next page should be enter his mobile no then the password must be sent to his mobile no...! Thanks in advance Nag Raj forgot password i want to proper code for forgot password, means how to send password into email id if i forgot my password import java.io.*; import javax.mail.*; import javax.mail.internet.*; // important Coding for forgot password Coding for forgot password coding for forgot password Please go through the following links: Here you will find a jsf Developing Forgot Password Form Developing Forgot Password Form In this section we will develop Forgot Password Form code for our application. Developing Forgot Password Form   Forgot Password of Application i want sample code for Forgot Password of Application The password forgot Action is invoked when you forgot your password and want to recover the password. The forgot Forgot Password of Application Forgot Password of Application through servlet and jsp Forgot Password Screen our web application allows... is displayed. With the help of this screen user can retrieve their password. Forgot coding for forgot password coding for forgot password coding for forgot password Please visit the following link: how to forget password in spring framework the following links: Please.../ Password need to encrypt while inserting into DB and need to decrypt while responding to forgot password Password need to encrypt while inserting into DB and need to decrypt while responding to forgot password Hi, I need the functionality in JSP... responding to forgot password. please help me out. Regards, GRR forget password forget password can i get coding for forgot password in jsp, need using javamail also cannot.. what should i do?? Thx Username password Username password Hi there, I am trying to create a page on a JFrame that will validate usernames and passwords from a database. I need help... to the next page, else show an error message. Here is a Login application recovery of password through mail recovery of password through mail hi i want code for login page... user account should be verified and if they forgot password then security question should be provided ,if they answer then their password must be sent How can I protect my database password ? How can I protect my database password ? How can I protect my database password ? I'm writing a client-side java application that will access... in as plain text. What can I do to protect my passwords Spring Security Password Hashing Spring Security Password Hashing In this section, you will learn about Password Hashing in Spring Security. In the Spring Security Authorized Access Using...; d11186354d1ef01ca06ae37d7e23e827da13e85f In the above case, my password change password - JSP-Servlet change password hi, my problem is as follows: i am creating a simple web application using mysql and jsp. now i want to create a web page for a user. this web page consists of changing the password for the existing user Spring portlet with Hibernate Spring portlet with Hibernate Hi All, Could you please help me integrate the code for Forgot Password using spring portlet, hibernate withn MYSQL... link: Thanks spring hibernate encrypted password In this section, you will learn about encrypted password in spring Password History - JSP-Servlet Password History I am using servlets and in my application i want to maintain password history.It means on password change My application should check previous 5 password so that new password can't be same to 5 old password Code To match password - Development process ! I am sending you HTML code from my project.try...Code To match password Hi, Suppose I have 10 username... in resultset Hi why are you trying to get all the username and passwords password change password change Hi , I am using jsf and trying to write a code to change the password of a user . Ihave to retrine userid fromdata base how to do that using session Validating the password field Validating the password field When the validate method returns back to the registration page the password field get cleared there by asking again one more time to enter the password field at the time of re-submitting the form Forget Password Forget Password How i get my forget password through mail? Please visit the following links: Decrypt an encrypted password in JSP Decrypt an encrypted password in JSP How to decrypt an encrypted password and store in database ? Her is my code that i have done for encryption > <%@page > import="java.sql.*,java.util.*"%> > <%@page import Change Password Code in JSP page) application and getting values. we use some database query executeQuery...Change Password Code in JSP In this example we will see how to change password... three password fields "oldpassword","newpassword"," array password - Java Beginners array password i had create a GUI of encryption program that used the array password. my question is can we do the password change program? i mean we change the older password with the new password different output trying to execute same java code different output trying to execute same java code i am using net beans 7 ide and java 6 to develop my java projects. i used the following coding...(event.getEventType()) { ..... ...... ..... ...... } } } When i execute myfaces,hibernate and spring integration - Hibernate myfaces,hibernate and spring integration sorry, in the previous.... when i write in my url (my port... folder) to my tomcat/webapp directory. 4)i have created the database pls review my code - Struts pls review my code Hello friends, This is the code in struts. when i click on the submit button. It is showing the blank page. Pls respond soon... { public ActionForward execute( ActionMapping mapping, ActionForm form different output trying to execute same java code different output trying to execute same java code i am using net beans 7 ide and java 6 to develop my java projects. i used the following coding...);} break; } } } When i execute from netbeans, JOptionPane showing "portList : true pls review my code - Struts pls review my code When i click on the submit page i am getting a blank page Pls help me. thanks in advance. public ActionForward execute...(); String password = lOGINForm.getPASSWORD(); if(username == null || password == null Random Creation of password to be encrypted and then send to the database.....I am using jsp as my front end and java has my back end,....My database is Ms Access...my problem is that i am not able...Random Creation of password Dear Sir I have created a form with some How to create the program in Java for getting the forgotten Password Form? in which user will fill the login name and then the application will send the password... data and send the email to user. Check the tutorial Developing Forgot Password...How to create the program in Java for getting the forgotten Password Form?  problem getting password - JavaMail problem getting password hi i am trying to get password but igot following error Error sending mail:javax.mail.MessagingException: Could not connect to SMTP host: 192.168.10.14, port: 25;nested exception username and password in servlet username and password in servlet i'm usng eclipse luna(java programming) Sevlet and apache tomcat8.0 i need to do a login page then after login... page after i login it shows error Login Page Hello User! please Projects learning easy Using Spring framework in your application Project in STRUTS... In this tutorial I will show you how to integrate Struts and Hibernate... will build our Struts Hibernate Plugin Application and then test.   forget password forget password codding for forget password using spring framework spring hibernate spring hibernate i need to display many fields( fields are in different tables) in a jsp page....how to implement this using spring hibernate  .../hibernate-spring/index.shtml Password encryption and decryption Password encryption and decryption Hello, I'm developing a system that requires user to login to enter the system. so I wanted to store encrypted users' password in the database so that I wouldnt know their password?   Password make a program which ask ask the username and password * in this format. in C language spring with hibernate - Spring spring with hibernate Hi, I need the sample code for user registration using spring , hibernate with my sql. Please send the code as soon... the following link: forget password? forget password? can anyone help me? how to create a module of forget password?the password can reset by generate random password and send to user's email..i develop the php system using xampp and dreamweaver 3D PASSWORD 3D PASSWORD HI i would like to know abt where the 3d password in india used and also few info about the 3d password pls rply some1 as soon as possible spring hibernate spring hibernate I need to save registration details in a database table through jsp using spring an hibernate....and the fields in the registration... that have same flow as needed in my application??? Please foget password foget password i have make a login form and add three buttons.one is user login ,second is new user and third is forget password in java using netbeans.so please help me to write the code for forget password button.forget Binding Error in Spring - Spring target object for bean name 'loginBean' available as request attribute I am trying to write a login page in Springs My jsp: User Id : "> My Maping in xml password - Security password How can i do password encript and decript in java Hi friend, Code to encript and decript password in java import... password= "Hello"; System.out.println("input " + password Struts Hibernate Spring - Login and User Registration - Hibernate Struts Hibernate Spring - Login and User Registration Hi All, I fallowed instructions that was given in Struts Hibernate Spring, Login and user.... Struts2.2.1 password tag example. Struts2.2.1 password tag example. In this tutorial, you will see the use of password tag of struts2.2.1. It is a UI tag in struts framework. It display... userName; private String password; public String execute Managing Datasource in struts Application Managing Datasource in struts Application Hi i need to know how to do set up of Oracle data base with struts using Data source.I have defined...-source> </data-sources> Then in my action class i am retrieving validating username and password from database validating username and password from database Hello sir, i am developing a login page. i want that when i fill data in text fields. it validate data from database. if enter data is match from database. page goes to next page how to check username & password from database using jsp how to check username & password from database using jsp Hello, I have created 1 html page which contain username, password & submit button. in my oracle10G database already contain table name admin which has name, password Login Application application that can be used later in any big Struts Hibernate and Spring based.... Register: The registration page has five fields namely User Id, Password, E... Login Application   you get a password field in struts you get a password field in struts How do you get a password field in struts Understanding Spring Struts Hibernate DAO Layer Understanding Spring Struts Hibernate DAO Layer... how Spring Hibernate and Struts will work together to provide best solution for any web based application. Understanding Spring Struts The password tag In this section, you will learn about the password tag of the Spring form tag library Unable to execute JSP page folder. But I could not execute the JSP page. Please help me...Unable to execute JSP page I have written one jsp file. It contains.... The tomcat server is already running onto my machine. I have saved the jsp file Blocking a user when he enters his password worng for three times ?? Blocking a user when he enters his password worng for three times ?? I have a login page called login.jsp and a login validation servlet Loginval.java. And i want add more security to my login page such as if any user enters to enter into a particular page only if the username,password and listbox value mtches to enter into a particular page only if the username,password and listbox value mtches I have created a login page in which a user could enter in to his page only if the username, password and the listbox value(user type The Complete Spring Tutorial The Complete Spring Tutorial In this tutorial I will show you how you can integrate struts, spring and hibernate in your web application. Spring framework is developed to simplify the developed Java Password Field Java Password Field In this section we will discuss how to use password field in Java. To create a password field in Java Swing JPasswordField is used... of text field which allows to enter password only. Due to the security reason spring hibernate spring spring hibernate spring why are all the links in the following page broken.... the following link: Spring Hibernate servlet code to update password? servlet code to update password? Create a servlet page which helps the user to update his password. The user should give the username,old password,new password,confirm password. The updation is applicable only for valid how to execute the below servlet with html page how to execute the below servlet with html page //vallidate user n...; <td>enter password</td> <td><Input Type="password" name..." value="tick">remember my password</td> </tr> <tr> Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/6534
CC-MAIN-2015-48
refinedweb
2,273
62.58
Lab 3: ASP vs. ASP.NET Visual Studio Team Microsoft Corporation August 2001 Summary: In this hands-on lab, you will build both an Active Server Pages (ASP) page and an ASP.NET page, each of which generates an HTML page using data from a database. (9 printed pages) Download the Experience Visual Studio .NET Lab files from the introduction topic. Contents Introduction Creating the ASP Page Viewing the ASP page Creating the ASP.NET Page Viewing the ASP Page Closing Out of Lab 3 Introduction In this hands-on lab, you will build both an Active Server Pages (ASP) page and an ASP.NET page, each of which generates an HTML page using data from a database. In both examples, the concept of data access is the same—they both involve a connection to the database. The difference is in the way the data are collected and displayed. Creating the ASP Page - To open the Visual Studio .NET Integrated Development Environment, click Start, click Programs, click Experience VS .NET Content, click Lab 3, and then click ASP Source. A blank ASP page with the file name Authors.asp opens in Visual Studio .NET IDE, as shown in Figure 1. Figure 1. ASP page - Type the following code: <%@ Language=VBScript %> <HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> <STYLE> BODY { font:arial } H1 { color:navy } </STYLE> </HEAD> <BODY> <DIV align=center> <H1>Authors</H1> <% ' ' Connecting to a database ' dim cn set cn = server.CreateObject("ADODB.Connection") cn.Open "Provider=sqloledb;" _ & "Data Source=(local);" _ & "Initial Catalog=pubs;" _ & "User ID=sa" ' Retrieving Data via the Recordset Object. dim rs set rs = server.CreateObject("ADODB.Recordset") rs.Open "select au_fname, au_lname, phone from authors order by au_lname",cn %> Note The mix of static HTML and server-side scripting in a table is in the following code. The recordset is iterated throughout in order to extract the data sequentially. <TABLE border='1'> <TR> <TH>First Name</TH> <TH>Last Name</TH> <TH>Phone</TH> </TR> <% do until rs.EOF Response.Write "<TR>" Response.Write "<TD>" & rs("au_fname") & "</TD>" Response.Write "<TD>" & rs("au_lname") & "</TD>" Response.Write "<TD>" & rs("phone") & "</TD>" Response.Write "</TR>" rs.MoveNext loop %> </TABLE> <!-- Footer --> <h5>Current as of <%Response.Write now%></h5> </DIV> </BODY> </HTML> - Click File, and then click Save Authors.asp. - Close the IDE. Viewing the ASP page - To view the ASP page, click Start, click Programs, click Experience VS .NET Content, click Lab 3, and then click ASP. The page shown in Figure 2 appears. Figure 2. ASP page results Creating the ASP.NET Page - To open Visual Studio .NET IDE, click Start, click Programs, click Experience VS .NET Content, click Lab3, and then click ASP.NET VB Source. A blank ASP.NET page with the file name Authors VB.aspx opens in the Visual Studio .NET IDE, as shown in Figure 3. Figure 3. ASP.NET page - To view the source, click the HTML button in the lower left corner of the Visual Studio .NET IDE window. - Type the following code: Note The System.Data and System.Data.SqlClient namespaces are declared at the top of the page. All of the classes within these namespaces are available to the ASP.NET page. Note The server-side script is completely isolated from the static HTML. You can use any run-time language, such as Microsoft® JScript® and C#, in addition to Microsoft Visual Basic®. <script language="VB" runat="server"> Sub Page_Load(Src As Object, E As EventArgs) Dim DS As DataSet Dim MyConnection As SQLConnection Dim MyCommand As SQLDataAdapter MyConnection = New SQLConnection("server=localhost;uid=sa;pwd=;database=pubs") MyCommand = New SQLDataAdapter("select au_fname as 'First Name', au_lname as 'Last Name', Phone from Authors", MyConnection) Note The DataSet object in the following code replaces the Recordset object. Notice the fill method of the SQLDataAdapter object. Note See the following code sets the DataSource property of the DataGrid control. Note the Tables collection in the DataSet object; unlike Recordset objects, DataSet objects can contain more than one table. Note In the following code, the DataBind method of the DataGrid control loads the DataGrid with data. The DataGrid then displays the data as an HTML table. Note The following line of code embeds a DataGrid object in the page. Additonal properties of the DataGrid control can also be set by adding the property/value pairs. For example: Width="700" and BackColor="#ccccff". - Click File and then click Save Authors VB.aspx. - Close the IDE. Viewing the ASP Page - To view the ASP.NET page, click Start, click Programs, click Experience VS .NET Content, click Lab 3, and then click ASP.NET-VB. The page shown in Figure 4 appears. Figure 4. ASP.NET page Closing Out of Lab 3 When you have finished viewing the ASP.NET page, close all windows. Other articles and labs in the Experience Visual Studio .NET set include: Introducing the Visual Studio .NET Lab Series Lab 4: Server Controls Walkthrough Lab 5: Using the Visual Basic Upgrade Wizard Lab 6: Building a Browser-Based Application Lab 7: Inheritance and Override
http://msdn.microsoft.com/en-us/library/aa290358(v=vs.71).aspx
CC-MAIN-2014-15
refinedweb
852
69.07
public class ActionMap extends Object implements Serializable ActionMapprovides mappings from Objects (called keys or Actionnames) to Actions. An ActionMapis usually used with an InputMapto locate a particular action when a key is pressed. As with InputMap, an ActionMapcan have a parent that is searched for keys not defined in the ActionMap. As with InputMap if you create a cycle, eg: ActionMap am = new ActionMap(); ActionMap bm = new ActionMap(): am.setParent(bm); bm.setParent(am);some of the methods will cause a StackOverflowError to be thrown. InputMap clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait public ActionMap() ActionMapwith no parent and no mappings. public void setParent(ActionMap map) ActionMap's parent. map- the ActionMapthat is the parent of this one public ActionMap getParent() ActionMap's parent. ActionMapthat is the parent of this one, or null if this ActionMaphas no parent public void put(Object key, Action action) keyto action. If actionis null, this removes the current binding for key. In most instances, key will be action.getValue(NAME). public Action get(Object key) key, messaging the parent ActionMapif the binding is not locally defined. public void remove(Object key) keyfrom this ActionMap. public void clear() ActionMap. public Object[] keys() Actionnames that are bound in this ActionMap. public int size() ActionMap. ActionMap public Object[] allKeys() ActionMapand its parent. This method differs from keys()in that this method includes the keys defined in the.
http://docs.oracle.com/javase/7/docs/api/javax/swing/ActionMap.html
CC-MAIN-2015-40
refinedweb
234
50.63
Walkthrough: Accessing and Displaying Data with JScript .NET in ASP.NET Jason Cooke Visual Studio Team Microsoft Corporation January 2002 Summary: This article illustrates how to use JScript .NET to write an ASP.NET page that accesses and displays information from a database. Techniques for accessing the data in an XML dataset are also illustrated. (9 printed pages) Requires - Some experience with ASP.NET, JScript .NET, and database querying. - Permission to read the SQL or Access Northwind databases. - Permission to create and modify files on a Web server that has the .NET Framework installed. Contents Introduction Setting up a Generic Page Creating and Displaying a DataTable Accessing and Displaying Data from the Northwind Database Accessing and Displaying Data from an XML Dataset Personalizing the Table Conclusion Introduction ASP.NET provides many new server-side controls that make it easy to program rich ASP.NET applications. In this walkthrough, which features the DataGrid control, you first create a page that uses the DataGrid control. You then bind the control to a table that you create, to the results of a database query, and finally to an XML dataset. Security is an important factor whenever an ASP.NET page accesses data on the server. The examples in this walkthrough implement some basic features to protect your information. For more information about data access with ASP.NET pages, see .NET Data Access Architecture Guide at MSDN Online and the ASP.NET QuickStart Tutorials at GotDotNet (). Setting up a Generic Page The simplest way to display a table of data in an ASP.NET page is to bind the data to a DataGrid control, which has properties that control the presentation of data. To bind data to a DataGrid control, the data must be stored in an object that implements the System.Collections.IEnumerable interface, such as System.Collections.ArrayList and System.Data.DataView. For more information, see DataGrid Class. In this section, you create a simple page that uses the DataGrid control. This page will serve as the basis for the pages in subsequent sections. To create a simple ASP.NET page with a DataGrid control - In your Web directory, located at C:\Inetpub\wwwroot by default, create a new directory named DataAccess. - Create a new ASP.NET file named DataAccess.aspx in the C:\Inetpub\wwwroot\DataAccess directory. You can do this with an application such as Notepad. Note You cannot use the Visual Studio .NET integrated development environment (IDE) to create a JScript .NET project. However, you can edit ASP.NET files in the IDE. - Open the ASP.NET page for editing in either the Visual Studio .NET IDE or Notepad. Note You cannot directly paste code copied from a richly formatted source (such as a Web page) into an ASP.NET page that you are editing in the Visual Studio .NET IDE. The IDE converts richly formatted text into HTML code that reproduces the look of the original text instead of pasting as unformatted text. You can use a two-step process to work around this restriction. First, paste a code example into a text-based editor (such as Notepad) to remove the rich formatting. Second, cut the code from the text-based editor and paste it into the IDE. - Add the following code to the page: <%@ Page Language=jscript %> <html> <body> <script runat=server> function Page_Load(sender : Object, e : EventArgs) { // Put code in this function that you want to have loaded // each time the page is requested from the server. if (!IsPostBack) { // Put code here that you want to run only the first time. } } // Page_Load </script> <h3>Category List</h3> <form runat=server> <asp:DataGrid </asp:DataGrid> </form> </body> </html> - Save the page. - View the page by typing the following address into the address bar of Internet Explorer: When you access the page, it only displays the "Category List" header. The DataGrid control does not display data because no data has been bound to it. Creating and Displaying a DataTable Before you attempt to load data from a database, ensure that the DataGrid control works properly by using data from a well-controlled data source. In this section, you construct an ArrayList, and then you bind the ArrayList to the DataGrid control. To bind data to a DataGrid control - Add the following function to the script block. - Bind the data in the table to the DataGrid control by adding the following lines to the if (!IsPostBack)block of the Page_Loadfunction: - Save the page. - Reload the page in Internet Explorer, or type the following address in the address bar of Internet Explorer: The page now displays a simple table of several fruits. Accessing and Displaying Data from the Northwind Database You can use the OleDbConnection, OleDbCommand, and OleDbDataAdapter classes to manage database connections. These classes are part of the System.Data.OleDb namespace, one of the constituents of ADO.NET. In this section, you use these classes to open a connection to a database, send a query, and populate a DataSet with the resulting data. You construct a DataView with the data from the DataSet, and then you bind that DataView to the DataGrid. You also implement a few layers of security. This involves ensuring that the application has the correct configuration and that sensitive information, such as the connection string, is not stored in the application. To create a configuration file - Create a new file named web.config in the C:\Inetpub\wwwroot\DataAccess directory. This file holds configuration information for the application. - Choose an appropriate connection string for your database. A typical connection string for the SQL Northwind database is: You must replace the placeholders YourServerName, YourUserID, and YourStrongPasswordwith the appropriate values for your database. Note Make sure that you provide an appropriate user, not SA, with a strong password. A typical connection string for the Access Northwind database is: You must replace the placeholder YourPathwith the path to your Access Northwind database. By default, this path is C:\Program Files\Microsoft Office\Office\Samples. Note The default installation of Access does not install the sample Access databases. You may need to run Office Setup to install Northwind. - Add the following code to the configuration file. This setup helps protect potentially sensitive information by not displaying verbose errors to remote machines and by separating the connection string from the Web application. Be sure to replace the placeholder YourConnectionStringwith the connection string you chose in the previous step. <!-- Web.Config Configuration File --> <configuration> <system.web> <!-- Throw a generic error for remote requests. --> <customErrors mode="RemoteOnly" /> </system.web> <appSettings> <!-- Separate the connection string from the application. --> <add key="DBConnStr" value=YourConnectionString /> </appSettings> </configuration> - Save web.config. You now modify the DataAccess.aspx file to read data from the Northwind database that you specified in the web.config file. To access a database - In the DataAccess.aspx file, add the following directives to the line immediately following the <%@ Page %>directive: The first directive allows the application to use the OleDbConnection, OleDbCommand, and OleDbDataAdapter classes, and the second directive allows the application to use the DataSet, DataTable, and DataView classes. - Add the GetDBDatafunction to the script block. function GetDBData() : ICollection { // Read a database table and return the DataView for that table. var ds : DataSet = new DataSet(); try { // Use a property to access the connection string. var dbConn: OleDbConnection = new OleDbConnection(ConnectionString); var queryStr : System.String = "SELECT CategoryID, CategoryName, Description FROM Categories"; var dbc : OleDbCommand = new OleDbCommand(queryStr, dbConn); var da : OleDbDataAdapter = new OleDbDataAdapter(dbc); da.Fill(ds); } finally { // Shut down the connection even on failure. if (dbc != null) dbc.Connection.Close(); } // Select one table from the DataSet to populate a DataView. return new DataView(ds.Tables[0]); } // GetDBData - Add the ConnectionStringproperty to the script block: - In the Page_Loadfunction where a DataView is bound to the DataSource property, replace the call to the CreateTestDatafunction with a call to the GetDBDatafunction. - Save DataAccess.aspx. - Reload the ASP.NET page in Internet Explorer, or type the following address in the address bar of Internet Explorer: The page now displays the CategoryID, CategoryName, and Description columns of the Northwind database in a DataGrid control. Accessing and Displaying Data from an XML Dataset The process that accesses XML data is almost the same as the process that accesses database data. However, to access XML data, you use the FileStream, FileMode, FileAccess, and StreamReader classes. These classes are located in the System.IO namespace, yet another facet of ADO.NET. You first create a sample XML dataset for the ASP.NET page to read. To create an XML dataset - Create a new XML file named schemadata.xml in the C:\Inetpub\wwwroot\DataAccess directory. - Add the following XML data to the file: ="Table"> <xs:complexType> <xs:sequence> <xs:element <xs:element </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <Table> <ID>6</ID> <Name>Ford</Name> </Table> <Table> <ID>7</ID> <Name>Zaphod</Name> </Table> <Table> <ID>42</ID> <Name>Phil</Name> </Table> </NewDataSet> Note The Extensible Markup Language (XML) is case-sensitive. As you add text to the schemadata.xml file, maintain the same case in the elements as included in the sample. - Save schemadata.xml. You now modify the DataAccess.aspx file to read data from the XML data stored in schemadata.xml. To read XML data from a file - In the DataAccess.aspx file, add the following directive to the line immediately following the <%@ Page %>directive: This directive allows the application to use the FileStream, FileMode, FileAccess, and StreamReader classes. - Add the GetXMLDatafunction to the script block. function GetXMLData() : ICollection { // Read an XML dataset and return the DataView for that data. var ds : DataSet = new DataSet(); var sPath : String = Server.MapPath("SchemaData.xml"); var fp : FileIOPermission = new FileIOPermission(FileIOPermissionAccess.Read, sPath); try { var fs : FileStream = new FileStream(sPath, FileMode.Open, FileAccess.Read, FileShare.Read); var reader : StreamReader = new StreamReader(fs); ds.ReadXml(reader); } finally { // Shut down the connection even on failure. if (fs != null) fs.Close(); } // Select one table from the DataSet to populate a DataView. return new DataView(ds.Tables[0]); } // GetXMLData Note that much of the code for accessing XML data is the same as in the GetDBDatafunction. The differences are bolded. - In the Page_Loadfunction where a DataView is bound to the DataSource property, replace the call to the GetDBDatafunction with a call to the GetXMLDatafunction. - Save DataAccess.aspx. - Reload the ASP.NET page in Internet Explorer, or type the following address in the address bar of Internet Explorer: The page now displays a table with the ID and Name columns of the XML dataset. Personalizing the Table Although the default properties of the DataGrid control produce a simple looking table, you can modify the settings to change the appearance of the table. You can further change the behavior by adding other tags within the opening and closing tags of the DataGrid control. For more information, see DataGrid Web Server Control. In this section, you change several property values of the control that influence the font and layout of the table. You also add tags to change the style of the header and the alternating rows of the table. To modify the default DataGrid settings - Change the opening <asp:DataGrid> tag to: - Add the following tags between the opening and closing <asp:DataGrid>tags: - Save DataAccess.aspx. - Reload the ASP.NET page in Internet Explorer, or type the following address in the address bar of Internet Explorer: The page now displays the same data in a table that looks different. Conclusion This article has demonstrated how to display tabular data using the DataGrid control. You learned how to programmatically create a DataTable from within in an ASP.NET page. You also learned how to read data from a database and an XML dataset. In particular, follow these recommendations: - Use the <asp:DataGrid> control to display tabular data. - Use the DataTable, DataColumn, DataRow, and DataView classes from ADO.NET to create data tables and views. - Use the OleDbConnection, OleDbCommand, and OleDbDataAdapter classes from ADO.NET to access database data. - Use the FileStream and StreamReader classes from ADO.NET to read XML data. For more information about security in ASP.NET and in the .NET Framework, look for articles in MSDN Online library within the Web Development and .NET Development sections.
http://msdn.microsoft.com/en-us/library/aa289163(v=vs.71).aspx
CC-MAIN-2014-41
refinedweb
2,042
50.23
Registers a handle type as being provided by another XLL The type of an object represented by a handle. The class name argument must be a wide (Unicode) string and must exactly match the form of the class name used in add-in functions. If a namespace is used in the add-in function's definition then the namespace must also be used here. Similarly, if template arguments are used, they must be in exactly the same form as in the add-in function, including white-space. The name of the XLL which will provide the handles of the specified class. Note that the XLL name is in standard text form (either ASCII or Unicode depending on the project settings) and that it: For examples of use, see the SharedHandles sample project. Header: nonrtdhandles.h HandleCacheInstanceImportManager Class | HandleCacheInstanceImportManager Methods | Sharing object handles between XLLs (User Guide) | SharedHandles Sample
http://planatechsolutions.com/xllplus7-online/HandleCacheInstanceImportManager_RegisterType.htm
CC-MAIN-2022-40
refinedweb
148
50.87
Type: Posts; User: Ray Newman If you're using NetBeans you should be able to set a break point on s = new Socket(addr,i) run debug and then inspect your addr and i variables when the debugger breaks. They're probably not... I don't understand how you are getting the exception that you specified. You should be getting something like this after letting NetBeans create the constructor: Exception in thread "main"... Add "archive="jCharts-0.7.5.jar" to your applet tag. (i.e., <html><body><applet code="SwingDemo.class" archive="jCharts-0.7.5.jar" width='350' height='300'></applet</body></html>) Ray You need to add the static keyword to the create method in the TicTacToe class if you want to invole it without creating an instance of TicTacToe. So change: public TicTacToe create(String input)... Look at the JavaDocs for HashMap. Your code is trying to iterate the HashMap using an index and that's not the way you loop through the HashMap members. public String getAllRallies () ... The exception is being thrown because your Serial class does not implement java.io.Serializable. Ray There are several reasons your code will not compile. Beyond getting it compile you have some additional problems but I'll leave that to you to ponder. You define a public class Zone in the same... In your toString method you are testing the value of the "month" variable but you never assigned a value to month.
http://forums.codeguru.com/search.php?s=c77e1238b127011f819807ea7cc879a1&searchid=6151547
CC-MAIN-2015-06
refinedweb
245
65.42
In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce. In this tutorial, we'll learn how to create a debounce function in JavaScript. What is debounce? The term debounce comes from electronics. When you’re pressing a button, let’s say on your TV remote, the signal travels to the microchip of the remote so quickly that before you manage to release the button, it bounces, and the microchip registers your “click” multiple times. To mitigate this, once a signal from the button is received, the microchip stops processing signals from the button for a few microseconds while it’s physically impossible for you to press it again. Debounce in JavaScript In JavaScript, the use case is similar. We want to trigger a function, but only once per use case. Let's say that we want to show suggestions for a search query, but only after a visitor has finished typing it. Or we want to save changes on a form, but only when the user is not actively working on those changes, as every "save" costs us a database trip. And my favorite—some people got really used to Windows 95 and now double click everything 😁. This is a simple implementation of the debounce function (CodePen here): function debounce(func, timeout = 300){ let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, timeout); }; } function saveInput(){ console.log('Saving data'); } const processChange = debounce(() => saveInput()); It can be used on an input: <input type="text" onkeyup="processChange()" /> Or a button: <button onclick="processChange()">Click me</button> Or a window event: window.addEventListener("scroll", processChange); And on other elements like a simple JS function. So what’s happening here? The debounce is a special function that handles two tasks: - Allocating a scope for the timer variable - Scheduling your function to be triggered at a specific time Let’s explain how this works in the first use case with text input. When a visitor writes the first letter and releases the key, the debounce first resets the timer with clearTimeout(timer). At this point, the step is not necessary as there is nothing scheduled yet. Then it schedules the provided function— saveInput()—to be invoked in 300 ms. But let's say that the visitor keeps writing, so each key release triggers the debounce again. Every invocation needs to reset the timer, or, in other words, cancel the previous plans with saveInput(), and reschedule it for a new time—300 ms in the future. This goes on as long as the visitor keeps hitting the keys under 300 ms. The last schedule won’t get cleared, so the saveInput() will finally be called. The other way around—how to ignore subsequent events That’s good for triggering auto-save or displaying suggestions. But what about the use case with multiple clicks of a single button? We don’t want to wait for the last click, but rather register the first one and ignore the rest (CodePen here). function debounce_leading(func, timeout = 300){ let timer; return (...args) => { if (!timer) { func.apply(this, args); } clearTimeout(timer); timer = setTimeout(() => { timer = undefined; }, timeout); }; } Here we trigger the saveInput() function on the first debounce_leading call caused by the first button click. We schedule the timer destruction for 300 ms. Every subsequent button click within that timeframe will already have the timer defined and will only push the destruction 300 ms to the future. Debounce implementations in libraries In this article, I showed you how to implement a debounce function in JavaScript and use it to, well, debounce events triggered by website elements. However, you don’t need to use your own implementation of debounce in your projects if you don’t want to. Widely used JS libraries already contain its implementation. Here are a few examples:
https://www.freecodecamp.org/news/javascript-debounce-example/
CC-MAIN-2021-21
refinedweb
656
62.98
QT integration with Azure Pipeline I'm new to QT and azure devops. Hopefully, the question has a simple answer. I have a subdirs project created with unit tests that run fine on my computer. When I run qmake, all of the Makefiles have hard-coded paths to qmake and the QT environment based on my environment. I have a pipeline job in azure devops that I want to compile and run the unit tests. What is the best way to script the pipeline job? I can see two paths: --. Thank you in advance for you advice. - aha_1980 Qt Champions 2018 @dwilliams The only possible way is to use qmake to create the Makefiles on every build station. Usually there is not much magic involved: - make sure the compiler is correctly set up (e.g. for MSVC, call the vcvars*.bat - call the qmake from the Qt version you want to use with full path. This will create Makefiles suiting the Qt version of that qmake Check the Makefiles into git DONT do that! It will bite you and break your build anytime. The same applies for generated files, like the ui_xxx.h. Note that using shadow build gives an easy way to start a completely broken build from scratch, which often helps to recover from strange problems. Regards Thank you for the info. That helped and I'm making progress. I created a debian VM in azure and have installed QT (apt-get install QT5-default). As part of my build, I run qmake -makefile pathToProFileForTheMainProject -o buildPathMakefile It creates the make file and then I run make -f Makefile. It runs and has all of the dependencies, but now I'm getting compilation errors. error: ISO C++ forbids declaration of 'Q_ENUM' with no type -fpermissive] Q_ENUM(ControllerState) error: 'qInfo' was not declared in this scope qInfo() << "changing state from" << _currentState << "to" << newState << endl; Where are the script files to set up the compiler? I suspect it's just a configuration issue. - raven-worx Moderators @dwilliams said in QT integration with Azure Pipeline: --. never go the first way. Makefiles are basically meant to be kept local, not shared between machines. error: ISO C++ forbids declaration of 'Q_ENUM' with no type -fpermissive] Q_ENUM(ControllerState) did you miss to include QObject (directly or indirectly) anywhere in your file? Also check the version you have installed on the system. Q_ENUM is only available since Qt 5.5 error: 'qInfo' was not declared in this scope qInfo() << "changing state from" << _currentState << "to" << newState << endl; add #include <QDebug> different compilers can very likely behave differently on the same code. It seems to be working now, but I didn't make any changes today. The only change I can think of is that the VM shut down last night per the schedule and I restarted this morning. Maybe the install of QT5 took effect better with the reboot. I'm going to create a new VM and document every step along the way to get it working with Azure pipeline. Thanks for your help! - Daniel Williams A co-worker of mine talked about the "lazy programmer" is the best programmer because they automated as much of the mundane stuff as possible. With that in mind, I didn't want to have to go try to figure all this out again when I have to set up a new pipeline. So, I re-created the entire pipeline again and documented all of the steps. As a thank you to the community for the help, I'm adding that information below. There is a lot of azure stuff in here, but it also has info on how to integrate QT project files in the process. I hope this helps you... #Setting up a debian VM in Azure to work with the pipeline jobs Last Updated: 20 December 2018 Since, QT is not one of the tools supported by the Microsoft Azure build servers, you'll need to create a self-managed VM in the Azure portal to use. This assumes that you have the proper Azure accounts: - Azure: azure.microsoft.com (used to create a VM.) - Azure devops: dev.azure.com/devops (dev.azure.com/YourDevopsAccount) used to create pipeline jobs. You will need to do the following: *Prep your QT project file (.pro) *Create a debian VM and add it to the server pool *Set up a server pool to manage the server *Set up the pipeline job Preface & definitions The pipeline job runs in the root of the repo that it downloads, so all of the paths listed below are relative to the root of the repo. This guide assumes that the code is in an Azure repo. However, the Azure pipeline can equally read from github. In our repo, we have two directories directly below the root of the git repo: - ./builds - ./ProjectSource In the builds directory we have a .gitignore file with '*/'' to ignore all of the files in the builds directory. The script for the pipeline will run something like the following: mkdir -p builds/release/ProjectName cd builds/release/ProjectName qmake -makefile -o ./Makefile ../../../ProjectSoure/project.pro make -f Makefile Prep the QT project file (.pro) The ".pro" project file is the central configuration for the Azure pipeline, so the script listed above needs to work on your development workstation properly if you hope to have it work on the build server. cd RootOfYourRepo Run the commands of the script you will use for the pipeline and ensure that the script works completely on your development workstation. Ensure that all paths are relative as the paths will be very different on the build server. I found that I had to update the .pro files of the sub-projects to ensure library and include paths were correct. I also had to add dependency files in the main .pro file. For example: devicelibrary-impl.depends = devicelibrary-abstract These dependency definitions are important to make sure the Makefiles are set up correctly. Fix any errors you find with "make -f Makefile" and check those changes back into the repo. Creat the debian VM We have chosen debian as the target for the application, so the build server will need to be the same version to ensure that the builds are compatible. I will not give much detail on that as it's all basic Azure VM creation that is well documented in the Azure documentation. Be sure to give it a public IP so you can connect to it via ssh. You will need to create a user that will be used for the builds. It can't be root. So, pick a username that makes sense. Add your public key to that user's .ssh/authorized_keys file to make access easier. Install the build dependencies You will need to install whatever third-party libraries you use. (e.g., sdk's, etc). We have a script called "aptPackages.sh" that we use to maintain what is needed for a development workstation or build server. That can be added to the VM post creation build script. Be sure to install the appropriate version of QT. (e.g., apt-get install QT5-default). You may need to reboot the vm after installing QT. When I first started the process, the compile was failing until the VM was stopped and restarted. Then it started working. At this point, you should be able to connect to the server via ssh. The server is nearly ready to work as a build server. But, you will need to install the agent pool software. That can only be retrieved after the agent pool is set up which is described in the next section. Set up the Deployment Pool The deployment pool is a high-level grouping of deployment resources created at the Organization level. This is important to understand as it is outside of the project. The Deployment Group is inside the project. We created a Deployment Pool named "IPS Deployment Group IPS Debian Build Server." The name is long but I'm trying to understand the relationship between Deployment Pool, Deployment Group and Agent pool. By giving it a long name, I can see where it's defined and the intention of the resource no matter where I see in the interface. You manage Deployment Groups from the "Organization Settings" in the site. The "Deployment Pool" connects a project with the Deployment Group. Once you have the Deployment Pool created, there is a script to run on the server which will connect the VM with the Deployment Pool. Run the script on your server. Set up the Deployment Group The Deployment group is defined inside of a project and associated with pipelines. It relates a Deployment Pool with a project. We named our, "Deployment Group IPS Debian Build Server" and select "IPS Deployment Group IPS Debian Build Server" as the Deployment pool. This is manged from the project, pipelines, deployment groups section. Once you have created the Deployment Group, there is a script that you will need to run on the VM. Set up the agent pool In order for the deployment pipeline to know which server it can use to run the build, there has to be a linkage between the VM and the pipeline. This is done with "Agent Pools" in Azure devops. In the pipeline.yml file associated with the pipeline job, there is a setting for "Agent Pool." You can create an agent pool, add the VM to the pool then specify that pool in the yml file and voila, the pipeline job will know which server(s) it can use for builds. We used a pool name of "Debian server" which will be needed in the final step of setting up a pipeline job. To manage the agent pools, login to the Azure devops site: In the bottom-left of the screen, click on "Organization Settings." Under "Pipelines" click on "Agent pools." From here you can create, edit & delete agent pools. Once have a pool created, you can download the script necessary to install the agent software. Click on the "Download" button after you have selected your agent pool. Installing the agent software is essentiall to completing the linkage of the VM with the agent pool and the pipeline. Installation involves downloading a tarball, scp'ing to to the server and running the simple script. All of the steps and software are available on the Azure devops Agent Pool screen. You created the VM in the previous step. Download the agent software and install it on the VM. This should complete the linkage between the VM and the agent pool. Note, the install and configure jobs run once. There is a "run.sh" command that must run in order for the agent to scan for jobs. By default it is not set up as a service. You have to run it manually to get it working. However, it can be set up as a service so that it is running all of the time. Once you have the agent software installed and running, look at the agent pool and see if your server is listed as a know server in the agent pool. If so, you have a server that is ready to run your builds. Set up the pipeline job At this point, you are ready to create a build pipeline and build QT on newly create VM. Login to the Azure devops site: Click on "Pipelines" the click on "+ New" to create a new pipeline. Follow the prompts and enter the information as needed. You will end up with a azure-pipelines.yml file that will be checked into the root of your repo. Be sure you edit the pipeline in the visual designer and select the appropriate pool that you just created. Even if you put the pool in the yaml file, you have to "authorize" it in the designer. This is a sample file: # C/C++ with GCC # Build your C/C++ project with GCC using make. # Add steps that publish test results, save build artifacts, deploy, and more: # # Trigger on changes to the develop brandh # Use servers in the "Debian server" agent pool # 4 Steps in the script to build the site. trigger: - develop pool: name: 'Debian server' steps: - script: | pwd cd builds/release/ProjectName qmake -makefile -o ./Makefile ../../../ProjetSource/Project.pro make -f Makefile - displayName: 'make' #Troubleshooting the Azure Pipeline Pipeline Setup If the pipeline job never kicks off, then it may be a set up issue with the pipeline. Assume you created a VM for the pipeline name "MyBuildServerABC." You need to check to be sure everything is set up correctly. - Check the VM itself - Make sure the VM is running and you can log into - check to see if ~/azagent directory exits - Both the Deployment pool and deployment group installation scripts use that directory. If it doesn't exist, they probably aren't set up. - Make sure that the agent software is running - Make sure the azure pipeline is set up correctly. - Log into - At the root / organization level, click on "Organization Settings" in the bottom-left of the screen. - Click on Deployment pools and check your deployment pool has at least 1 server running. - You can click on the pool name and see the names of the targets. - You should see the name of your VM (MyBuildSeverABC) - Navigate into your project. This is inside of the organization. - Click on Pipelines - Click on Deployment Groups - You should see your deployment group with "1 Online" - Click on your deployment group to see the name of your build server (MyBuildServerABD) - Navigate into the project settings (bottom-left of the screen) - Note, the menu item at the bottom-left of the screen changes from "Organization Settings" to "Project Settings" when you navigate into a project. To get back to the organization level, click on "Azure DevOps" in the upper-left of the screen. - Click on Agent pools. - Click on the agent pool you set up. - You should see your VM listed (MyBuildServerABC) If the pipeline job kicks off, but you get an error like, "Could not find a pool with name {PoolName}. The pool does not exist or has not been authorized." You need to edit the pool in visual mode, click on "Edit in the visual designer," and be sure the pool you want to use is selected. See also:. Pipeline script fails If the pipeline job runs, but the script fails, you can drill into the build history and look at the logs in the azure devops portal. Once the job has run once the source code will exists on the hard drive of the VM. The default is in the home directory of the user in _work (~work/...). You can ssh into the VM and run the script commands to simulate what is happening with the build job. With that, you can debug errors in the script. - SGaist Lifetime Qt Champion Hi and welcome to devnet, Thank you very much for the detailed instructions ! Would you mind turning it into a Wiki article ? This will make it more visible as forum threads tends to disappear over time due to new threads piling upon them. @SGaist I have moved this to the Wiki along with a number of corrections and simplifications I found. The page has been submitted to moderation and should be available once they have reviewed it. Thanks for the suggestion of making it a wiki page. - SGaist Lifetime Qt Champion Thanks ! By the way, it's Qt, QT stands for Apple QuickTime which is not what you are writing about.
https://forum.qt.io/topic/97642/qt-integration-with-azure-pipeline/10
CC-MAIN-2019-04
refinedweb
2,605
72.97
Cellular). The following code generates a maze using to this approach. The CA rules are implemented using SciPy's convolve2d algorithm to count neighbours. The code generates frame images of the growing maze every nit iterations, as animated below. The frames are saved to a subdirectory ca_frames. This code is also available on my Github page. # ca_maze.py import numpy as np from scipy.signal import convolve2d import matplotlib.pyplot as plt # Create a maze using the cellular automaton approach described at # # The frames for animation of the growth of the maze are saved to # the subdirectory ca_frames/. # Christian Hill, January 2018. def ca_step(X): """Evolve the maze by a single CA step.""" K = np.ones((3, 3)) n = convolve2d(X, K, mode='same', boundary='wrap') - X return (n == 3) | (X & ((n > 0) & (n < 6))) # Maze size nx, ny = 200, 150 X = np.zeros((ny, nx), dtype=np.bool) # Size of initial random area (must be even numbers) mx, my = 20, 16 # Initialize a patch with a random mx x my region r = np.random.random((my, mx)) > 0.75 X[ny//2-my//2:ny//2+my//2, nx//2-mx//2:nx//2+mx//2] = r # Total number of iterations nit = 400 # Make an image every ipf iterations ipf = 10 # Figure dimensions (pixels) and resolution (dpi) width, height, dpi = 600, 450, 10 fig = plt.figure(figsize=(width/dpi, height/dpi), dpi=dpi) ax = fig.add_subplot(111) for i in range(nit): X = ca_step(X) if not i % ipf: print('{}/{}'.format(i,nit)) im = ax.imshow(X, cmap=plt.cm.binary, interpolation='nearest') plt.axis('off') plt.savefig('ca_frames/_img{:04d}.png'.format(i), dpi=dpi) plt.cla() Comments are pre-moderated. Please be patient and your comment will appear soon. There are currently no comments New Comment
https://scipython.com/blog/maze-generation-by-cellular-automaton/
CC-MAIN-2019-51
refinedweb
299
61.12
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hello! I'm currently messing around with the final output of a Spline Object affected by a deformer. I'm trying to get the Spline Object, post-deformed, not the Line Object. So in the case of the Circle spline I would expect four points to be returned with tangents, instead of a linear sixty-eight point Line Object. I'm aware of the Cache and DeformCaches and I don't think either of those give me what I'm looking for. As an example of what I'm talking about. The deform cache would appear like this as I understand it. This looks to me like the Line Object of the Spline that is then deformed through the Bend Object. When I use a Matrix object setup to match the vertexs of the Circle though, it returns four points, not the sixty-eight points of the Deformed Cache and they are in the correct place on the deformed spline. I'm using the Matrix Object to illustrate that it seems to be possible to get the Spline Points post deformer as opposed to the Line Points post deformer. Is it possible to get the Spline Object in this circumstance or am I stuck with just retrieving the Line Object from the deform cache? Thanks for any help! Dan hi, it's even more straight forward than what i though. use SPLINEHELPFLAGS_USERDEFORMERS when you init your splinehelper and you just need to ask the matrix of the corresponding point. SPLINEHELPFLAGS_USERDEFORMERS import c4d #Welcome to the world of Python def main(): spline = op[c4d.ID_USERDATA,1] splineIndex = 2 shelp = c4d.utils.SplineHelp() if not shelp.InitSplineWith(spline, c4d.SPLINEHELPFLAGS_GLOBALSPACE | c4d.SPLINEHELPFLAGS_CONTINUECURVE | c4d.SPLINEHELPFLAGS_USERDEFORMERS): return lineIndex = shelp.SplineToLineIndex(splineIndex) orienttMat = shelp.GetVertexMatrix(lineIndex) obj = op.GetObject() obj.SetMg(orienttMat) You just need to iterate for each point of the original spline and convert them to the deformed position. Cheers, Manuel Hi, I do not quite understand what you are trying to do. I might be misunderstanding you, but: SplineObject SplineHelp SplineLengthData Long story short: You cannot arbitrarily deform a parametric spline. Cheers. zipit as @zipit said, it's not possible. The deformer is working with the cache of the spline witch is already the line object (with lost of points) @m_magalhaes @zipit Thank you for the replies! That all mostly makes sense to me. I'm only really confused about why the Matrix object seems to be able to track the original spline points. Is it just placing a point along the same percentages of the spline as before the spline is deformed? so sorry, i just looked at it and you are right. it's just using the SplineToLineIndex function from the SplineHelp. I did a quick test with python (without error check sorry) This function convert from the spline index to the line index. After that, just retrieve the deformed cache (on a spline you have to use a CSTO) and just retrieve the position of the deformed line. import c4d #Welcome to the world of Python def main(): spline = op[c4d.ID_USERDATA,1] shelp = c4d.utils.SplineHelp() if not shelp.InitSplineWith(spline): return lineIndex = shelp.SplineToLineIndex(1) tempDoc = c4d.documents.IsolateObjects(doc, [spline]) newSpline = tempDoc.GetFirstObject() resultCSTO = c4d.utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT, list=[newSpline], doc=tempDoc) deformedSpline = resultCSTO[0] points = deformedSpline.GetAllPoints() obj = op.GetObject() obj.SetRelPos(points[lineIndex]) @m_magalhaes said in Post Deformer Spline: Thanks, Manuel! This is what I was looking for!
https://plugincafe.maxon.net/topic/12662/post-deformer-spline
CC-MAIN-2021-49
refinedweb
619
67.35
AdaOpt Want to share your content on python-bloggers? click here. AdaOpt is a probabilistic classifier based on a mix of multivariable optimization and a nearest neighbors algorithm. More details about it are found in this paper. When reading the paper, keep in mind that the algorithm is still very new; only time will allow to fully appreciate all its features. Plus, its performance on this dataset is not an indicator of its future performance, on other datasets. Currently, the package containing AdaOpt, mlsauce, can be installed from the command line as: pip install git+ In this post, we’ll use mlsauce’s AdaOpt on a handwritten digits dataset from UCI Machine Learning repository. The model is firstly trained on a set of digits – to distinguish between a “3”, or a”6”, etc.: from time import time from tqdm import tqdm import mlsauce as ms import numpy as np from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.datasets import load_digits # Load datasets digits = load_digits() Z = digits.data t = digits.target # Split data in training and testing sets np.random.seed(2395) X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2) obj = ms.AdaOpt(n_iterations=50, learning_rate=0.3, reg_lambda=0.1, reg_alpha=0.5, eta=0.01, gamma=0.01, tolerance=1e-4, row_sample=1, k=3) # Teaching AdaOpt to recognize digits start = time() obj.fit(X_train, y_train) print(time()-start) 0.03549695014953613 Then, AdaOpt is tasked to recognize new, unseen digits (X_test, y_test), based on what it has seen on the training set (X_train, y_train): start = time() print(obj.score(X_test, y_test)) print(time()-start) 0.9944444444444445 0.19525575637817383 The accuracy is high on this dataset. Additional error metrics are presented in the following table: preds = obj.predict(X_test) print(classification_report(preds, y_test)) precision recall f1-score support 0 1.00 1.00 1.00 31 1 1.00 0.97 0.99 40 2 1.00 1.00 1.00 36 3 1.00 1.00 1.00 45 4 1.00 1.00 1.00 37 5 0.97 1.00 0.98 29 6 1.00 0.98 0.99 42 7 1.00 1.00 1.00 35 8 0.97 1.00 0.99 33 9 1.00 1.00 1.00 32 accuracy 0.99 360 macro avg 0.99 1.00 0.99 360 weighted avg 0.99 0.99 0.99 360 Ad here is a confusion matrix: At test time, AdaOpt uses a nearest neighbors algorithm. Which means, a task with quadratic complexity (a large number of operations). But there are a few tricks implemented in mlsauce’s AdaOpt to alleviate the potential burden on very large datasets, such as: instead of comparing the testing set to the whole training set, comparing it to a stratified subsample of the training set. row_sample == 0.1 for example in the next figure, means that 1/10 of the training set is used in the nearest neighbors procedure at test time. The figure represents a distribution of test set accuracy: We also have the following timings in seconds (current, could be faster in the future), as a function of row_sample: The paper contains a more detailed discussion of how these figures are obtained, and a description of AdaOpt..
https://python-bloggers.com/2020/05/adaopt/
CC-MAIN-2021-10
refinedweb
550
67.96
I have to write a function that takes a list(or string) and and object and returns the copy of the list up to but not including the first occurrence of that object, or all the elements if that object is not in the list. I know i have to use loop here but what I'm confused at is list and strings use different methods for finding the index of that object. How can I use that with the loops to get my function up to the first occurrence of that object. def up_to_first(item, element): if type(item) == list: index_of_element = item.index(element) res = [ ] for i in range(0, index_of_element): sliced_list = item[0 : index_of_element] return sliced_list Try the following function: def up_to_first(seq, obj): if obj not in seq: return seq return seq[:seq.index(obj)] This will return the sequence seq if obj is not in that sequence, and will return the sequence up to, but not including obj otherwise. However, this function as it is will break if you are not careful about types. For example, it will work if you are looking for 5 in [1, 2, 3, 4, 5] (and return [1, 2, 3, 4]), but will raise an error if you look for 5 in a string. >>> up_to_first([1, 2, 3], 3) [1, 2] >>> up_to_first('abcdef', 'd') 'abc' >>> up_to_first([1, 2, 3], 'a') [1, 2, 3] >>> up_to_first('abcdef', 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../.../test.py", line 2, in up_to_first if obj not in seq: TypeError: 'in <string>' requires string as left operand, not int
https://codedump.io/share/p1SFwlxurbK0/1/return-a-list-or-string-up-to-first-occurrence-of-that-object
CC-MAIN-2016-50
refinedweb
269
62.82
trimIndent Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty). Note that blank lines do not affect the detected indent level. In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the common indent is 0, and therefore this function doesn't change the indentation. Doesn't preserve the original line endings. import kotlin.test.assertTrue fun main(args: Array<String>) { //sampleStart val withoutIndent = """ ABC 123 456 """.trimIndent() println(withoutIndent) // ABC\n123\n456 //sampleEnd } See Also
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/trim-indent.html
CC-MAIN-2019-13
refinedweb
108
54.93
HP debuts news Ibrix scale-out NAS system Hewlett-Packard Co. recently announced a new enterprise scale-out network attached storage (NAS) system – the HP Ibrix X9730 – that scales to 1.68 PB of capacity in a single system and 16 PB in a single namespace. The storage system, which replaces the HP Ibrix X9720 model, does typical NAS functions but it is also designed for high-volume, long-term active archiving for unstructured data. The array is three times faster on writes and five times faster on reads compared to the 9720, said Patrick Osborne, a director of product management at HP’s storage division. “This system is bigger and denser,” Osborne said. “You can deploy a 1.7-petabyte cluster in about two hours from the time you power it on. The system is meant for tier three or four archiving. We are not selling it for high-performance, parallel computing. The software in the system if more for longer data storage but you can use it as an unstructured data repository. It’s a NAS system at the end of the day.” The HP Ibrix X9730 is 5U and scales up to 16 file server nodes and eight capacity blocks, with each block containing 70 drives. The system now supports 3 TB and 2 TB midline SAS drives, as well as CIFS, NFS, HTTP, HTTP/S, WebDAV, FTP, FTP/S and NDMP protocols. A two-node 210 TB configuration is priced at $223,589 or $1 a Gigabyte, Osborne said. In comparison, the 9720 scaled up to 1.2 PB. That product is designated as end-of-life but will be supported for five years. Like the 9720, the 9730 system is targeted for media, entertainment and content depository. It supports archive applications such as Symantec Enterprise Vault and CommVault Simpana. The 9730 comes with the HP Ibrix Constant Validation Software that generates check sums to determine data is not corrupted. It also comes with a data mobility feature for tiering data in the same namespace based on data access and file type. A WORM data retention capability marks files as retained. HP’s Ibrix operating system software v6.1 streamlines and simplifies the Ibrix storage system deployment so it can be implement in a shorter time. The system is based on a pay-as-you-grow architecture, reducing the chance of over-provisioning.  Comment on this Post
http://itknowledgeexchange.techtarget.com/storage-soup/hp-debuts-news-ibrix-scale-out-nas-system/
CC-MAIN-2014-52
refinedweb
401
65.22
KritaTextLayout KoText is a library for general use that extends the QText framework (codenamed scribe) with an enhanced text-layout which adds features required by ODF and general word-processing applications.You can use KoText at all places where you would normally use a QTextDocument as the main text layout class in scribe can be replaced on any QTextDocument instance using QTextDocument::setDocumentLayout(). This means you can use the Qt API as normal, but you will be able to use extra features like the plugins, the variables and the ODF loading and saving for all the ODF text-layout features. TextShape Flake-Plugin Closely coupled with the kotext library is the text plugin that is build on flake technology. All the user interaction dialogs and code will reside in that plugin, and the actual heavy lifting of the layout also is present only in that plugin. In other words; this library will supply you with the APIs but without having the text shape plugin loaded you can't show or layout the text. The goal is to keep it cheap to link to this library and only provide the bare minimum of functionality is the way to get there. The feature- package will be completed by the optional text-plugin. QTextDocument compatibility The actual content is stored in the QTextDocument, as mentioned before. In KoText we support a lot more features than Qt does in its layout and this library will allow you to enrich your document with those features. The core design goal is that you can use an externally created QTextDocument with KoText. This has the implication that all the extra content is stored inside the document. We add QTextFormat based properties for that as can be seen in the styles (see KoParagraphStyle::Properties for instance), and we allow managers to be stored on the document too. So for example a KoStyleManager will be stored as a property on the QTextDocument and you can access that using the KoTextDocument API. Note that you can use the KoTextDocument class while using only a QTextDocument instance. Plugins There are various plugins for KoText that make it possible for 3rd parties to extend the KoText functionality, see the techbase page; ODF compatibility Loading and saving of documents can be done to and from ODF using the open document classes. Important classes; KoTextDocumentLayout the main layout class to be set on the QTextDocument. KoInlineTextObject plugin base for inline objects (and variables) KoTextEditingPlugin plugin base for text editing plugins. KoText namespace. Documentation copyright © 1996-2020 The KDE developers. Generated on Sat May 9 2020 05:29:13 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/extragear-api/graphics-apidocs/krita/plugins/flake/textshape/textlayout/html/index.html
CC-MAIN-2020-29
refinedweb
453
50.36
Some Basic Stuff: The Writer Monad Edit: Clarified some of the code. Edit II: Comment about laziness. In this post, Magnus Therning gives a number of solutions to the n-queens problem in Haskell. The problem is just to arrange n queens on an n x n chess board so that neither is threatening any of the others. It’s a classic problem that’s solved with backtracking. That is, you try something, and if it doesn’t work you back up and try something else. Simple enough. It reminded me that when I was first learning Haskell, I wrote an n-queens solution using the Writer monad. This monad just augments the pure functional environment with a new instruction called “tell”. For those new to Haskell but with some knowledge of Python, consider it equivalent to Python’s “yield”. Here’s the code: import Control.Monad import Control.Monad.Writer import Data.List diagonal (x1,y1) (x2,y2) = x1 + y1 == x2 + y2 || x1 - y1 == x2 - y2 nqueens n = execWriter $ f [1..n] 1 [] where f [] _ ps = tell [ps] f cs r ps = forM_ cs $ \c -> unless (any (diagonal (r,c)) ps) $ f (delete c cs) (r + 1) ((r,c):ps) And that’s it. The diagonal function determines if two positions (as order pairs of row and column) are diagonal from each other. The nqueens function then uses execWriter to run something in the Writer monad and extract the list of answers that were “told” during its execution. Then I call the workhorse function, which for lack of a better name is just called f. This function assigns one queen to each row, from the top down. It is recursive, so it tracks state in its parameters: the first is a list of free columns, the second is the row number, and the third is the list of positions where queens have been placed so far. If there are no more free columns, then we must have placed all the queens, so we tell the solution. If there are free columns, we loop through them and try putting a queen in each free column at the current row. Formally, this returns a list of all solutions to the problem. However, it’s a lazy list; so if you only use the first one, the remainder of the list will never be calculated. So if you only want one solution, just do head (nqueens 8), and you’ll get the first solution. Okay, nothing phenomenal here. Just a quick example of some Haskell code. Massive Abz wrote: Umm… huh? Sturdy I’m finding learning Haskell difficult because of monads. Your example helped. Thanks! very interesting, but I don’t agree with you Idetrorce
https://cdsmith.wordpress.com/2007/12/09/some-basic-stuff-the-writer-monad/?like=1&_wpnonce=2839c90b72
CC-MAIN-2015-22
refinedweb
454
73.78
Notifications The notify component makes it possible to send notifications to a wide variety of platforms. Please check the sidebar for a full list of platforms that are supported. Configuration # Example configuration.yaml entry notify: - platform: pushbullet name: paulus api_key: ABCDEFG The name parameter is optional but needed if you want to use multiple platforms. The platform will be exposed as service notify/<name>. The name will default to notify if not supplied. Service Once loaded, the notify platform will expose a service that can be called to send notifications. The notification component supports specifying templates with data_template. This will allow you to use the current state of Home Assistant in your notifications. In an action of your automation setup it could look like this with a customized subject. action: service: notify.notify data: message: "Your message goes here" title: "Custom subject" Test if it works A simple way to test if you have set up your notify platform correctly is to use Services from the Developer Tools. Choose your service (notify/xyz) from the list of Available services: and enter something like the sample below into the Service Data field and hit CALL SERVICE. { "message": "The sun is {% if is_state('sun.sun', 'above_horizon') %}up{% else %}down{% endif %}!" } For services which have support for sending images. { "message": "Test plugin", "data": { "photo": { "url": "" } } } If the service support sending the location, the data from this sample can be used. { "message": "Test plugin", "data": { "location": { "latitude": 7.3284, "longitude": 46.38234 } } }
https://home-assistant.io/components/notify/
CC-MAIN-2017-34
refinedweb
248
50.23
#include <VOP_CodeGenerator.h> =========================================================================== Class containing info about a scope level at which to generate/compile the nested shaders. Usually they use global level, implying that they use full node path as shader function name. But when compiling HDAs, the shaders nested inside them are anchored to the HDA and should use relative path as shader function name. Also, this class can store all the nested shaders that need own compilation. Definition at line 814 of file VOP_CodeGenerator.h. Definition at line 822 of file VOP_CodeGenerator.h. Definition at line 820 of file VOP_CodeGenerator.h. Removes the hda-specific prefix. Replaces the scene-specific prefix with an hda-specific one. Returns true if the node generates code that should be isolated to the space.
http://www.sidefx.com/docs/hdk/class_v_o_p___shader_space_info.html
CC-MAIN-2018-43
refinedweb
123
51.34
Oh, well, the title has clearly been inspired by another article "The faster smart pointer of the west", not really because I want to create a counterpart, but simply because I thought that a certain situation not addressed in that implementation should however find an answer. I started to think of smart pointer in terms of "reference counting pointers", but I found some difficulties in the following situation: So, I thought to implement a dual reference counting mechanism, and a pointer type conversion mechanism. While doing this, I found certain aspects in common, so I grouped pointers and counters (and optionally even objects) in common base classes. It may seem things become a bit complicated, but it isn’t. In general, we’ve to deal with three types of pointers: class* NULL And we can classify the objects into two categories: This can help to solve certain “conversion” problems and again, we can reclassify the objects into two other categories: I found three answers: I considered the risk of 3) compared with 2) and the constraints of 1), and I decided to implement 3) with a chance to 1) if needed. So ref-counting is implemented in a dedicated template class containing: template<class R> struct RefCount: public RefCount_base { private: LONG _cntStrong; LONG _cntWeak; R* _ptr; ... }; Because the counter functions do not depend on R, I found convenient in implementation, to derive all the templates from a single common abstract base (Refcount_base) defining all reference counting functions as “pure virtual” (in fact it’s more an “interface” than a “struct”) R Refcount_base Note that both RefCount and its base are put into an unnamed namespace: you cannot use them directly. Note also that increment and decrement are done using the W32 API InterlockedIncrement and InterlockedDecrement. You can replace this with a simple ++ and –- but you may have trouble with multithreading. (In fact, apart from this, I didn’t address the multithreading problem, leaving it for future.) RefCount InterlockedIncrement InterlockedDecrement ++ –- I’m not referring specifically to the “COM” concept of “aggregate”, but in a situation where an object in based by a set of other objects. This is typical in class inheritance or in members embedding. Consider this: C derives from A and B. You create C through a strong pointer, than you pass it to a strong A pointer. You leave out C from it’s original pointer. (The pointer to A is still in place.) C A B. For those reasons, smart pointers refer to two entities: the object they represent (may be a subcomponent) and the ref-counter that tracks it. And ref-counter refers to the aggregator object. Or … uhmmm … in fact: the object for which the ref-counter had been instantiated. (This may lead to some nasty bugs, but we can come out, don’t worry!) template<class T> class _PtrSmart: public _PtrSmart_base { friend class PtrStrong; friend class PtrWeak; protected: T* _pT; //the referenced object; //NOTE: it may be different that the //referred by RefCount, //because it may be a sub or super object RefCount_base* _pRefCnt; }; Note: _PtrSmart is the base for both PtrStrong<T> and PtrWeak<T> pointers. The difference is the way they manage counters, not the way they refer objects. _PtrSmart PtrStrong<T> PtrWeak<T> Assignment between smart pointers, converts the type they refer, but copies the reference to the ref-counter, making this possible: class A { public: A() { std::cout << "Construct A\n";} ~A(){ std::cout << "Destruct A\n";}; void Hello() { std::cout << "Hello from A\n";} virtual Virt() {std::cout << "Virt from A\n";} bool operator<(const A& a)const {returnfalse;} }; class C: public A { public: C() {std::cout << "Construct C\n";} ~C() { std::cout << "Destruct C\n";} void Hello() { std::cout << "Hello from C\n";} virtual Virt() {std::cout << "Virt from C\n";} }; int _tmain(int argc, _TCHAR* argv[]) { GE::Safe::PtrStrong<A> hA; GE::Safe::PtrStrong<C> hC(new C); hC->Hello(); hA = hC; hC = (C*)NULL; hA->Hello(); hA->Virt(); return 0; } When doing hA = hC, the C* in hC becomes a A* in hA, but hA uses the same ref-count object of hC (and increments). hA = hC C* hC A* hA When hC gets null, it decrements, hence, the counter goes to one. So hA is still valid and A still alive. null Finally, when hA goes out of scope (and is destroyed) it decrements the counter. Now the counter is zero, and so the counter object (not the smart pointer): delete this Sounds good, but there are some limitations: What really converts C* into A*? Only the fact that C “is an” A? And what about to convert A* to C*? And if C derives from A and B, why don’t convert B* to A*, if referred to instances of B and A as bases of a same C? Will dynamic-cast be a solution? B B* And if A and B are not “base” but “members” of C? Why not do the same again? (uhmm .. it’s my impression, or is it really semantically the same of a COM QueryInterface?) QueryInterface And then: when a “dumb” pointer is assigned to a “smart” pointer, how can the smart pointer properly know what is the ref-counter eventually already associated to the object (it is assigned via “dumb” pointer, but another smart pointer somewhere else may already have created it), without the risk to create a new one, with the result to have two independent counters to the same object both with a same right to kill the object? (C++ can even kill twice, but your memory may not like it!) All this problems are addressed in the following arguments: "Conversions" and "Object Strength" When a smart pointer is assigned to another, the receiving pointer must receive a reference to the ref-count object the assigning pointer is using, and must convert the type referred by the originating pointer to the type it points. The mother of all this conversion is the template function T* smart_cast<T,U,C>(U*). T* smart_cast<T,U,C>(U*) The third parameter is a functional object (a class implementing operator()) I called “caster”. operator() template<class T, class U> T* smart_cast(U* pU) { T* pT = NULL; //try using the function pT = FPtrConvertFn<T,U>(pU); if(pT) return pT; //successful conversion //try using functional PtrConvert<U>()(pT, pU); if(pT) return pT; //successfull conversion return C()(pU); }; In fact, what smart_cast does is try to find a way to convert. smart_cast It first tries with a template function, then through template operator() onto template classes. To construct a PtrConvert<U> (U is the "from" type) call its operator()<T>(T*&, U*). The default implementation of this template member of template function simply sets T* to NULL (failed conversion). PtrConvert<U> U operator()<T>(T*&, U*) T* If you are in a situation like: class A { ... }; class B { ... }; class C { public: A m_a; B m_b; }; You can easily specialize a: class PtrConvert<C> { void operator()<A>(A*& pA, C* pC) { pA = &pC->m_a;} void operator()<B>(B*& pB, C* pC) { pB = &pC->m_b;} }; If you don’t (or let a particular type to the default), smart_cast will try also with FPtrConvertFn<T,U>. FPtrConvertFn<T,U> It’s not a functional object. Just an ordinary template function, you can specialize for a particular type pair. For example in our case: C* FPtrConvert<C,A>(A* pA) { return (C*)(((BYTE*)pA)-ofsetof(C,m_a)); } C* FPtrConvert<C,B>(B* pB) { return (C*)(((BYTE*)pB)-ofsetof(C,m_b)); } The default still returns NULL (failed). At this point, if no T* has till been found, smart_cast tries the ax by calling C()(pU), where C is the third template parameter. ax C()(pU) This template parameter is taken from the second parameter of both strong and weak pointers, and the default value is FDynamicCast<T>. FDynamicCast<T> In my header I defined it, and I also define a FStaticCast, in the following way: FStaticCast template<class T> struct FDynamicCast { template<class U> T operator() (U u) {return dynamic_cast<T>(u);} }; template<class T> struct FStaticCast { template<class U> T operator() (U u) {return static_cast<T>(u);} }; Of course, they will never work with the previous example, but may be good defaults in case of derivation, where is: class C: public A, public B { ... }; Enabling RTTI (/GR option of C++ compiler, or Language section of project property page, “Enable Run Time Type Information), a default to dynamic-cast is always working consistently. dynamic-cast The only drawback is, it doesn’t work if nothing of virtual exist in A, B and C (non-polymorphic types). In this case static_cast must be used (I provided FStaticCast just for those cases). But, in this case, there is another drawback: you cannot convert A* to B* or vice versa (The fact they are or not both into a same C object depends on the object instance, not on the definition). Thus, a FPtrConvert specialization may be required. static_cast FPtrConvert There is still an open problem: the assignment of a “dumb” pointer to a "smart" one. The receiving pointer has no way to know about the ref-counter, because the "dumb" pointer doesn’t know about it. The only thing it can do is – because it needs one- create a new one. This is a completely unsafe operation. If other smart pointers are already in place pointing to that object you are left alone in an inconsistent environment. For this reason, this kind of assignment, in a completely safe application should be avoided, and all pointers should be smart, and new objects should be created with the New(...) function(s) of the smart pointers themselves. This assures that object and ref-counters are always one-to-one. New(...) But there is another possibility: put the knowledge about the ref-counting into the objects themselves. By doing so, the ref-counter can be identified even through a dumb pointer. This is what ObjStrong does. ObjStrong ObjStrong, in fact, is a class designed to be the base for every object wishing to be “strong”. It carries a signature (see later) and derives virtually from ObjStrong_base (that is internal to the header). ObjStrong_base Why virtually? Because if A and B are both "Strong" (hence: derive from ObjStrong) and C derives from A and B (and even ObjStrong again), we must be sure that only one ObjStrong_base exists: why? Because it is – in fact – the creator and destructor for the ref-counter! So, when a smart pointer receives a dumb pointer, and needs a ref-counter object, it calls the local helper GetRefCountBase. This function attempts to verify if the referred object ... IsSmart , by reinterpreting the pointer (C-style cast) and verifying the smart-object signature is present. If it is, the cast is correct, and the ref-counter is retrieved. GetRefCountBase IsSmart If it isn’t, a new ref-counter is created. Sorry. I found this implementation very flexible in a variety of situations, and I used it in various applications (MFC or not). The only thing to take care in MFC are objects whose creation and deletion is managed internally by MFC (like Document, Frame or Views). You cannot use smart pointers with those objects apart the cases where you intercept and - in fact - disable, MFC creation / deletion mechanisms. Serialization is also a problem: in most of the cases serializing "dumb pointers" obtained by smart pointers and deserializing into "dumb" pointer to assign to smart pointers works. But serialization is a more general problem, I promise to afford in another article. During a discussion with a colleague, he gave me an important suggestion: in my implementation, when a strong counter decrements to zero, the referred object is simply deleted. This works in most of the cases, but there are cases where an object may not like this. There are objects that don't like to be deleted, instead, they like to delete themselves after a deletion function (may perform some cleanup or delay deletion after a particular event) has been called. For this reason, I decided to add another template "functor" (GE_::Safe::FDeletor<T>) whose operator()(T* pT) by default just does delete pT, and modifies the delete _ptr in RefCount::ReleaseStrong with a call to this functor (FDeletor<R>()(_ptr)). GE_::Safe::FDeletor<T> operator()(T* pT) delete pT delete _ptr RefCount::ReleaseStrong FDeletor<R>()(_ptr) Normally nothing changes, but now, you can specialize that functor for a particular type to do something else than “delete”. The class that "functor" will refer is the class for which the Refcount has been created. Normally this is: Refcount For ObjStrong_base, I added a new virtual function (Destroy) and I specialize the FDeletor to call this function. The default implementation, just calls delete this. Destroy FDeletor So, for ObjStrong derived, you shouldn't specialize the FDeletor: you must instead override the Destroy function. For complex objects you cannot (or don't want to) derive from ObjStrong, I suggest to always assign every "new" instance to a smart pointer of that instance type first (and eventually reassign to a subtype -smart or not- pointer). This assures that the ref-counter object refers always your type and that FDeletor you can specialize is the one for your class. What happens if an object that is “smart pointed” is “deleted” by a call to "delete" into a “somebody else function” not aware of the existence of smart pointers? Clearly, this is inconsistent with all what we said up to now: smart pointers cannot know about that action, outside their control. But there is a case when we can do something: ObjStrong derived objects: they know about reference counting objects. In this case, we can – in ObjStrong_base destructor, set the "aggregator reference" in the ref counter to NULL. Because all smart pointers, when dereferencing, always checks this condition, this is enough to make all smart pointers to behave as they’ve been set all together to NULL. Probably not so beautiful (a pointer that becomes NULL if you don’t expect ...) but better than to have invalid pointers! This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) #pragma once #ifndef __GE_SMARTPTR_H__ #define __GE_SMARTPTR_H__ //just put all the header content inside here //... //... #endif //__GE_SMARTPTR_H__ // end-of-file. cout TextOut CString std::tr1::shared_ptr General News Suggestion Question Bug Answer Joke Praise 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/Articles/5126/The-Safest-Smart-Pointer-of-the-East?msg=985417
CC-MAIN-2015-48
refinedweb
2,428
57.91
Key Takeaways - A cloud IDE workflow provides excellent convenience in terms of being accessible across any device or location. - When configured correctly, it is arguably more secure than a local workflow as no code or tools are stored locally. - Speed of onboarding increases tenfold as complete workstations can be automated and stood up with a single command. - Local operating systems become irrelevant, allowing users to use the hardware and operating systems that best suit their workflow. - Cloud-based development opens up a world of flexibility by abstracting your engineering environment from all local resources and dependencies. With the recent announcement of products such as Visual Studio Codespaces and GitHub Codespaces, it is clear there is a demand for cloud-based engineering workflows. While working on a local machine may feel safe and familiar, the cloud IDE workflow offers users significant benefits such as power and flexibility. For several months, I have been using self-hosted cloud IDEs on a range of public cloud providers. I have been doing so via the open-source version of Code Server from the talented folks over at Coder. Working in the cloud is now my primary workflow for my personal and professional work as a DevOps engineer. With a remotely-accessible instance of VSCode and its built-in terminal, all I need is a web browser to get to work. Whether self-hosted or managed, this article is going to cover five reasons why a cloud IDE may be precisely what you or your company needs to boost productivity to the next level. One: Convenience Working in the cloud is not a new concept. We've all been using products like Google Drive, Dropbox, iCloud and Office 365 for the last decade or so. The convenience of storing your work in the cloud and being able to come back and pick up right where you left off is a game-changer. With cloud IDEs hitting the scene, us engineers can now enjoy the same convenience and productivity. No longer do I need to be tied down to local hardware forever shuffling around keys, juggling different versions of tooling and languages, and trying to achieve optimal compatibility between my Mac and Linux machines. With my remote cloud IDE, I can work from any device and location as long as I have an internet connection and browser. While a required internet connection may sound like a downside, in today's world of distributed teams, pair programming and CI/CD workflows, an internet connection is generally already a must in most scenarios. Offloading my workflow to a remote instance also means the associated load is no longer a burden on my local machine. Lowering the CPU, memory and hard drive load significantly improves performance, thermals, and battery life on my laptop. Working in the browser also has other convenient benefits. The main one being an isolated work environment. For instance, I use Firefox as a personal browser and Chrome as a work browser. Now I can contain my entire work environment within a single browser. Doing so provides an exceptional level of convenience, but also touches on my second point, security. Two: Security As previously mentioned, working in the cloud means my work environment and its related resources remain isolated in a browser profile. Containing my work in such a way means no tools, keys or code are on my local filesystem. I'm sure you've heard the, "you must encrypt your drive in case of a stolen system" lecture during onboarding. While I do still recommend and encrypt all my drives, my local hardware now becomes substantially less relevant to a would-be attacker. Having my workload execute from a remote network also means my local network holds little value if compromised. All keys and permissions to execute workloads are locked down and authenticated from my remote instance, not my local network and computer terminals. How the network stack is configured and locked down is a vital part of maintaining optimal security while working in the cloud. There are a few different ways to go about this. The simplest way to securely access a cloud IDE, with no extra configuration required, would be forwarding the local port of the IDE instance through an SSH tunnel. By doing so, it is not exposed to the public internet. Now all work is being conducted through an encrypted tunnel. While straightforward and secure, this does limit one to needing the correct SSH keys and an SSH client. As mentioned in part one, a key benefit of a cloud IDE is the ability to access it from any device. To achieve this, I do need to expose a web server via the public internet. The easiest way to accomplish this is with something like Caddy. A simple web server with automatic HTTPS via Let's Encrypt. In a matter of minutes, I can have a cloud IDE being served securely over TLS. I, however, choose to house my remote instances in private networks. Traffic is then routed to my IDE instance port via a TLS encrypted load balancer at the edge. This keeps the instance itself off the internet. Whether choosing to route directly to the instance or via a load balancer, I now have a password-protected cloud IDE running over TLS. Basic authentication is still a little lack-lustre by today's standards. To beef up security to an acceptable level, I would recommend implementing MFA. The best way to do so is by using a reverse proxy that supports this like Cloudflare or OAuth2 Proxy. Now I have a universally browser-accessible cloud IDE workstation with TLS, password, and MFA protection. Implementing these security procedures only applies when self-hosting the cloud IDE, of course. Managed services, such as Visual Studio Codespaces, generally provide and take care of security measures as mentioned above with excellent quality assurance. Another notable security benefit is the ability to have different instances for different work environments. By having these separate instances, it means all associated security measures for their respective work environments are isolated. Gone are the days of having several sets of keys and access rights on a single machine, creating a blast radius that could take out multiple systems and networks if compromised. One last point on security, regardless of whether you are using a self-hosted or managed service, make sure the underlying platform meets security compliance. Certifications like SOC 1 Type II, SOC 2 Type II, and in particular, ISO/IEC 27001:2013 are paramount for security assurance. Equally important, though, is that your chosen public cloud provider or managed service is on your company's trusted vendor list. You don't want to wake up to a message in your inbox from a security architect! Three: Speed A major constraint in delivering value when starting at a new company is the onboarding process. "What access do I need? What specific tools, languages and versions does my role require? Are these versions up-to-date with what my colleagues are currently using?" Getting yourself into a position to deliver value for the company can take days or weeks. Even then, tooling and versioning are still subject to change amongst individual contributors. This is where the speed of delivery and productivity comes into play with cloud workflows. With tools like Terraform and Packer, the whole stack from the underlying infrastructure platform, to the tooling and access requirements on the instance itself, can be standardized and automated. Imagine a scenario in which there are three different teams for a particular product: an ops team, backend team, and frontend team. Each has requirements for tooling, languages, versioning and access for their respective layer of the product. In a cloud workflow, we can have three ready-to-go workstation images on the shelf for each team. We treat these images like products, with owners and maintainers. When a new team member joins, let's say the backend team, they now run a single command to spin up a new cloud IDE instance from the "backend team" image. In a matter of minutes, they are delivering value with a fully functional VSCode instance running on a secure VPS loaded with the correct tools, versions and access they require. From a team perspective, having a centralized image that all cloud workstations build from drastically decreases non-value add work. It does so by removing drift between tooling and versioning across workstations. When a team decides it's time to upgrade to a new version of Go, for instance, the maintainers of that team's image update the version, and all associated instances upgrade from the new image release. Now we have an opinionated workflow in which everyone is working with the same tools and versions. There is also a drastic increase in terms of technical delivery speed. Rather than working from a domestic home or office internet connection, the workload is running in a high-speed data center. That Docker image that used to take two minutes to pull down now takes 15 seconds. The required speed to work in the cloud is not high. I've worked with a 10mbps connection from Sydney, Australia on a cloud IDE housed in a Digital Ocean data center in Singapore. It reacted as if it were running as a native app on my local machine. Four: Operating Systems A point of contention for some time now is the fact that most of the tech industry supply and work on Macs, while the systems we build generally run on Linux. I understand the appeal of the Apple ecosystem; a standardized set of hardware and software with excellent support. However, It does create an engineering dilemma. While some may make the argument that BSD and GNU are not that different, the truth is, they are different enough. To accurately test against Linux architecture from my Mac, I need to run either VM's, containers, or CI/CD builds. Even when running containers on Mac, I am still technically chewing up extra resources running a Linux VM under the hood to use Docker. This is because the Docker daemon interacts directly with the Linux kernel to create its namespaces and control groups. What I'm alluding to here is that engineering work generally makes more technical sense to be conducted on a Linux base. With a cloud IDE workflow, my local operating system becomes irrelevant. I can still use my company-supplied Mac along with all the excellent productivity apps like Mail, Calendar, Slack, and of course, Spotify. At the same time, my engineering workstation and IDE is a high-powered Linux-based VPS running in a browser tab. For that real native zen mode, I like to give the IDE its own workspace and go full screen! The above is, of course, applicable to Windows as well. I'm not judging… Five: Flexibility My last point, and also to recap, is flexibility. Ultimately what cloud IDE workflows provide are flexibility and freedom. I can now work from Mac, Windows, Linux, iOS, Android; it doesn't matter. The tools I need to get my engineering work done are now on a remote instance and accessible from any location or device in the world. Yes, I have tested this from my Google Pixel 4! Self-hosted workstations do initially involve a little more legwork to get automated and stood up, but as a result, I have fine-grained control over exactly what I need. I can achieve vertical elasticity based on the resource load. I can (and do) mount my home directories to separate immutable drives, allowing me to blow away, recreate or change my underlying instance. I can choose whether to run my cloud IDE as a container or native daemon. Plus, I can move to different public cloud providers with ease. If all you need is a remote IDE to write and test code, then the several managed services out there are an easy way to work remotely and securely. They have the benefits of freedom and flexibility, without the extra overhead. Whether you choose to go down the self-hosted or managed service path, there is a whole new world of power and flexibility that a cloud workflow can provide. Spending days setting up new machines and backing up hard drives are a thing of the past. We live in a world where, with the press of a button, I can stream a movie in 4K from a catalog of thousands in a data center hundreds of miles away. With technology like this, it was only a matter of time before we started working in the cloud and not just on the cloud. I am happy to say that day is here, and it's damn impressive! About the Author Ben Vilnis grew up around computers from a young age as his father opened a computer store in the ’90s which then grew into an ISP and hosting company in the early 2000s. He very quickly found an affinity for computer technology and started building computers and websites during high school. In his senior year, he discovered his passion for Linux, system administration and networking. Skip forward several years, and Ben now works at Envato as a DevOps engineer and has a strong passion for composable infrastructure, Lean IT, and Platform-as-a-Product. Ben is also a lifelong musician and singer/songwriter and serves as a volunteer firefighter in the New South Wales Rural Fire Brigade. Community comments
https://www.infoq.com/articles/devs-working-in-cloud/?itm_source=articles_about_Security&itm_medium=link&itm_campaign=Security
CC-MAIN-2020-34
refinedweb
2,254
61.16
Deno is the new Node? About. What are the main issues with Node.js? Any program can write to the filesystem and the network This might be a security problem, especially when intalling untrusted packages from npm. The crossenv incident is an example. If crossenvhad not had writing permissions, this would not have happened. Bad ageing async APIs Promises were included in 2009 but removed in february 2010 from Node.js. This has provoked that many libraries out there are still using callbacks as their way to manage async code.). I’ve tried this by myself with a small project and yes, it’s a pain. The module system and npm The main problem here is that the module system isn’t compatible with browsers so our code isn’t fully isomorphic. This is mainly caused by two reasons: storing dependencies in node_modules and having a package.json. What is Deno? “Deno is a secure TypeScript runtime built on V8” ― Ryan Dahl As Typescript is a superset of Javascript, it’s also a runtime for Javascript. Deno is a new project created by Ryan Dahl (the inventor of Node.js) that aims to fix Node.js design mistakes that I’ve mentioned before. Deno’s top features Security Deno by default won’t allow performing delicate actions, like reading environment variables or writing into the file system. We need to pass specific flags Deno process runs in a “non-privilege” mode by default, and for accessing delicate things like environment variables All the code runs without filesystem write, environment and network permissions. To allow this we must invoke demo with the --allow-write and --allow-net. All communications between Deno’s privileged process and v8 are by message passing (previously written in Go, now migrated to Rust). This allows a single auditable point for all communications. Module system No package.json, no node_modules. Source files can be imported using a relative path, an absolute path or a fully qualified URL of a source file: import { test } from "" import { log } from "./util.ts" All source files are cached by default. If we need to refresh our dependencies we can use the argument --reload. This is like the browsers’ F5. TypeScript support out of the box TypeScript is supported by default in Deno. Yup. No gotchas. Without any config. Trying out Deno v0.1.4 First, we need to download Deno binary: $ mkdir deno-test && cd deno-test $ wget $ gunzip -c deno_linux_x64.gz > deno $ chmod u+x deno $ ./deno --version deno: 0.1.4 v8: 7.0.247-deno Now we can create our typescript file and execute it: $ ./deno myscript.ts Hello world We can also try URL imports. The only requirement for this is to have the .ts file extension at the end of the URL. $ ./deno myimport.ts Downloading 3628800 When executing the script, it’ll download and cache the module. If we want to refresh this cache, we can invoke Deno with --reload, which is the equivalent to F5 or Ctrl+R. Here is a more advanced example, using a shallow implementation of the axios library: The only gotcha is, that VSCode isn’t able to load the typings from the remote, so in the editor we’ll get the following error: An import path cannot end with a '.ts' extension. But the code still works and gives the correct output: ./deno --allow-net axios-test.ts User name: Leanne Graham Conclusion There still a long time until Deno reachs a production-ready state, but I think it’s on the right path in order to be a better Javascript runtime than Node.js. Thanks for reading! 👋👋
https://medium.com/lean-mind/deno-node-js-killer-718c8969770b
CC-MAIN-2019-04
refinedweb
609
66.84
PROBLEM:PROBLEM:Code:#include <iostream.h> #include <conio> using namespace std; int main(){ char array[10]; for (int i = 0; i <= 9; i++){ cout << "Line " << i + 1 << ": "; cin.getline(*(array + i)); //while(cin.get() != '\n'){} //cin.ignore(); //getch(); cout << endl; } cout << endl; for (int i = 0; i <= 9; i++) cout << "Line " << i + 1 << "contains string: " << *(array + i) << endl; return 0; } //end int main Write a function that accepts ten lines of user-input text and stores the entered lines as ten individual strings. Use a pointer array in your function. REAL PROBLEM: I can't clear the input buffer correctly. I've tried everything. Cin.getline won't work either
http://cboard.cprogramming.com/cplusplus-programming/26351-pointer-arrays-oo-fun-urg.html
CC-MAIN-2014-10
refinedweb
110
74.59
BitArray.RightShift() Method in C# with Examples BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.RightShift(Int32) method is used to shift the bits of the bit array to the right by one position and adds zeros on the shifted position. Original BitArray object will be modified on performing the operation right shift. Syntax: public System.Collections.BitArray Right right by two positions. The final result is 00100. False False True False False Example 2: Suppose we have the bit array 100011 we want to shift it right by three positions. The final result is 011000. False True True False False False Reference:
https://www.geeksforgeeks.org/bitarray-rightshift-method-in-c-sharp-with-examples/?ref=lbp
CC-MAIN-2021-39
refinedweb
129
67.45
Ethereum Smart Contracts are more than just “the new hot thing.” It’s my belief that they (or something related) are poised to change the way that humans do business with one another in the upcoming new age of the internet. Time will tell if that’s the case. This is the first of a three-part article on Ethereum smart contract development with Solidity, most specifically exploring the use of contracts with so-called “oracles”—which are basically contracts which pump data into the blockchain for use by other smart contracts. - Part 1: An introduction to development with Truffle, and project setup for further experimentation - Part 2: Delving into the code for deeper examination - Part 3: A conceptual discussion of oracles with smart contracts The goal of this, part 1 of the series, is not to get much into the concept of oracle contracts, the philosophy behind them, or even very deeply into what they are; the goal of this part of our Ethereum oracle tutorial is simply to: - Get you set up with building smart contracts with Truffle. - Build a smart contract project which will serve us in parts 2 and 3. - Introduce a few concepts related to Ethereum smart contracts and coding of smart contracts. - Introduce the compile/run/debug cycle with Truffle and smart contracts. Definition: Oracle. A means for smart contracts to access data from the world outside the blockchain. A type of smart contract themselves, oracles take data from the outside world and put it into the blockchain for other smart contracts to consume. The first part of this article will consist of getting set up with all the prerequisites. Then, we’ll set up a single Ethereum contract and test it with Truffle. Finally, we’ll separate the oracle from the client and test them jointly. Software Requirements - Any major OS will work, though some of the installation and setup will of course be different on different systems. I have done all of this on Ubuntu Linux (16.04). I have also had no problems setting up the environment on Windows. I have not tried Mac, though I am aware that it’s common to do so on Mac as well. - It is not necessary to run a full eth node; we will use Truffle, which comes with its own testnet. If you know a bit about what you’re doing, you can use any other testnet of your choosing; Truffle’s local dev testnet is just the easiest and most accessible for purposes of this tutorial. Knowledge Requirements - Basic knowledge of how blockchain works - Understanding of what a blockchain-based smart contract is - Some basic hello-worldish experience with smart contract development will be helpful, but not necessary if you’re smart and ambitious. (And I know that you are!) This article series can serve as a very first introduction to smart contracts, but it ramps up very quickly into more advanced concepts. If it’s your first eth smart contract tutorial, be prepared to climb to altitude quickly. If you feel confident, great; if not, feel free to get a simpler “hello world” type of tutorial or two under your belt first. Check out one of or previous Ethereum articles and Cryptozombies, for starters. Caveat: The smart contract space, being so new, changes quickly. Solidity syntax features that were new when this article was written may be deprecated or obsolete by the time you’re reading this. Geth versions may have come and go. Solidity is always adding new language features and deprecating old ones. Many new features are currently in the works. So, be prepared if necessary to adapt the information in this article to the new landscape of the future; if you’re serious about learning smart contract development, then I have faith in you. Description of Example App Use case: Users bet on boxing matches. - The user can pull a list of bet-able boxing matches. - The user can choose a match and place a bet on the winner. - The user can bet any amount above a specified minimum. - If the user’s pick loses, the user loses the entire amount of the bet. - If the user’s pick wins, the user gets a portion of the pot based on the size of his/her bet and the total amount bet on the loser of the match, after the house (the contract owner) takes a small percentage of the winnings. What Is an Ethereum Oracle? Smart contracts are still kind of a new thing; they’ve yet to take the mainstream, and so many aspects of how they will work have not yet been hammered out and standardized. I will briefly explain the impetus behind the idea of the “oracle”—and be patient; we’ll get into it in more depth in later parts. Engineering a blockchain contract is not like programming a client-server app. One important difference is that data with which the contract interacts, must already be on the blockchain. There is no calling out of the blockchain. Not only is it not supported by the language, it’s not supported by the blockchain paradigm. The contract can take bets in the form of Ethereum-based currency, store them in the contract, and release them to the correct wallet addresses according to a formula, when the winner of a match is declared. But how does the contract know the winner? It can’t query a REST API or anything like that. It can only use data that’s already in the blockchain! Many many use cases of smart contracts run into a similar problem—they are seriously limited unless they can interact with the world outside the blockchain. If the contract can only interact with data on the blockchain, an obvious solution is to inject the necessary data into the blockchain. And that’s what an oracle is. An oracle is another contract, which injects data into the blockchain, allowing other contracts to consume it. While that may raise questions about trust and trustlessness, just accept for now that that’s what an oracle is. In part 3 of this series, we’ll discuss those nuances. In our example use case, the oracle will be the contract that injects data into the blockchain, regarding (a) what matches are available and (b) who won those matches, once decided. Setting Up the Ethereum Development Environment For basic setup, we will install: - Geth (optional for now) - Truffle - Ganache CLI (optional) - A development environment (optional) This article does not have the space to be a full guide to environment setup but acts as just a rough guide. That’s ok, though, because there are already plenty of more complete setup guides for your particular OS and the internet doesn’t really need a new one. So I will take you quickly down the path and point you toward some resources for getting more details as needed. Be prepared to install requirements and prereqs as your system requires and as Google directs you. Install Geth (optional) Geth is Go-ethereum, the Ethereum core software; while it’s not necessary for this exercise at all, it would behoove any would-be Ethereum developer to have it and be familiar with it. It will be necessary if you’re ever going to deploy your smart contract to the live Ethereum network. - - - Install Truffle Truffle is the main thing we’re going to use for development, and absolutely is a requirement for this guide. Find and follow the specific instructions for your OS to install Truffle. Below are some links that will hopefully help you. - - - Install Ganache CLI (optional) I recommend installing Ganache CLI to use as another testing tool, though we won’t actually use it for our tutorial. It’s optional. Ethereum Development Environment It would be more than possible to do this whole tutorial with any simple text editor, like Notepad++, gedit, vi, or any text editor or IDE of your choosing. I personally am using Visual Studio Code with the following extensions: - Solidity - Solidity extended - Material icon theme Note: The extensions are not required—they just make for a better coding environment. Setting Up the Code Project Setup Truffle is a very convenient tool for compiling smart contracts, migrating them to a blockchain, and also it provides development and debugging utilities. Some project setup will be necessary in order to integrate with Truffle. Now we’ll set up the shell for our project, both in Truffle and in the directory structure. Just sit back, follow the steps robotically for now, and enjoy. Create a directory to house all the code; call it oracle-example. Inside the root directory, create two subdirectories, because eventually, the project will consist of two sub-projects. Create the directories: - /oracle-example/client - /oracle-example/oracle Go into the client folder, because that’s the first project we’re going to develop. Open a terminal (command line) window in the /oracle-example/client folder. Run the command truffle init. Note that among many files created are truffle-config.js and truffle.js. We don’t need both of them, so delete truffle-config.js (just to avoid confusion and clutter). We need to edit truffle.js, in order to point Truffle in the right direction for testing. Replace the contents of truffle.js with the following: module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } }; Note that Truffle init created a directory called migrations (oracle-example/client/migrations). Inside that folder should be a file named 1_initial_migration.js. Add another file in the migrations directory and name it 2_deploy_contracts.js, with the following content: var BoxingBets = artifacts.require("BoxingBets"); module.exports = function(deployer) { deployer.deploy(BoxingBets); }; Adding the Code Now that the simple setup is out of the way, we’re set to begin coding. Remember, this part of the article is still introduction and setup, so we’re going to go rather quickly through the code. We’ll get into more in-depth explanations of the code in part 2, and more in-depth discussion of the architecture and concept in part 3. That said, we’ll touch quickly upon some core concepts evident in the code. Follow carefully to keep up. The full code for this step in the process is available on GitHub: Contracts in Solidity A “contract” in Solidity is roughly analogous to a class in other object-oriented languages. The language itself has been compared to Golang and JavaScript, among others. Some other language constructs in Solidity—which we’ll have examples of later—are modifiers, libraries, and interfaces. Inheritance (including multiple inheritance) is supported for contracts. Solidity contract files have a .sol extension. Oracle Interface Add this file to your project: /oracle-example/client/contracts/OracleInterface.sol Normally, the oracle interface would be just that—an interface. For this very first iteration, it’s just a simple class contained within the Solidity project, just as a placeholder for now. We’ll move it out in the very next step, after we successfully compile and run the contract on Truffle. After we convert this to an actual interface later on, the function implementations will be empty. Client Contract Add this file to your project: /oracle-example/client/contracts/BoxingBets.sol This is the contract which consumes the boxing match data, allows users to query available matches, and place bets on them. In later iterations, it will calculate and pay out winnings. Compiling and Running Now is when we’ll see if we got everything right the first time! Compile and Migrate the Contract Open a terminal in the /oracle-example/client/ folder Compile the code with this command: truffle compile Alternate: Use my recompile.sh shell script (). Note that you will see a lot of warnings, because our code is not yet in its final form! Open the Truffle development console: truffle develop Now, in the Truffle developer console, migrate to the test network: truffle(develop)> migrate Run the Contract At the development console prompt, enter the following line of code: truffle(develop)> BoxingBets.deployed().then(inst => { instance = inst }) Now, “instance” is the variable which refers to the BoxingBets contract and can be used to call its public methods. Test it using the following command: truffle(develop)> instance.test(3, 4) Note that we’ve included a public “test” function in BoxingBets.sol. It adds together whatever two numbers you pass to it, just to demonstrate that the contract is executing code, and that we can call it from the Truffle development console. If we get a sane-looking response (see below) then our job here is done (for now at least). Separate the Ethereum Oracle If everything has succeeded so far, then we’re over the hump. The next thing we’ll do is separate the oracle contract from the BoxingBets contract. In real usage, the oracle’s contract will exist separately from the client contract on the blockchain, so we’ll need to be able to: - Instantiate it by blockchain address. - Dynamically change the oracle address that the client contract uses to reference the oracle. So in short, what we’re going to do now is separate the oracle and the client into two separate blockchain contract entities, and make them talk to each other. The client will instantiate the oracle by address and call it. Client Contract First, we’re going to change the client contract (client) so that it refers to a dynamic interface to an oracle rather than a concrete class. Then we’ll make sure that it instantiates the oracle from an outside contract. Go into /oracle-example/client/contracts/OracleInterface.sol. As we noted before, this is currently not an interface, but we’re about to make it one. Replace what’s in there with the contents of: pragma solidity ^0.4.17; contract OracleInterface { enum MatchOutcome { Pending, //match has not been fought to decision Underway, //match has started & is underway Draw, //anything other than a clear winner (e.g. cancelled) Decided //index of participant who is the winner } function getPendingMatches() public view returns (bytes32[]); function getAllMatches() public view returns (bytes32[]); function matchExists(bytes32 _matchId) public view returns (bool); function getMatch(bytes32 _matchId) public view returns ( bytes32 id, string name, string participants, uint8 participantCount, uint date, MatchOutcome outcome, int8 winner); function getMostRecentMatch(bool _pending) public view returns ( bytes32 id, string name, string participants, uint participantCount, uint date, MatchOutcome outcome, int8 winner); function testConnection() public pure returns (bool); function addTestData() public; } In BoxingBets.sol, we’re going to replace this line: OracleInterface internal boxingOracle = new OracleInterface(); With these two lines: address internal boxingOracleAddr = 0; OracleInterface internal boxingOracle = OracleInterface(boxingOracleAddr); Now what we want is a way to set the address of the oracle, dynamically, and a function that we can call to find out the current oracle address. Add these two functions to BoxingBets.sol: /// (); } /// @notice gets the address of the boxing oracle being used /// @return the address of the currently set oracle function getOracleAddress() external view returns (address) { return boxingOracleAddr; } And finally, for testing the connection between the client and the oracle, we can replace the test function in BoxingBets with a function to test the oracle connection: /// @notice for testing; tests that the boxing oracle is callable /// @return true if connection successful function testOracleConnection() public view returns (bool) { return boxingOracle.testConnection(); } Ownable Notice that the definition for setOracleAddress has an onlyOwner modifier following it. That restricts this function from being called by anyone other than the contract’s owner, even though the function is public. That is not a language feature. That’s provided to us by the Ownable contract, which is lifted out of OpenZeppelin’s library of general-utility Solidity contracts. We will get into the details of that in Part 2, but in order to facilitate the use of that onlyOwner modifier, we need to make a few changes: Copy Ownable.sol from into /oracle-example/client/contracts/. Add a reference to it at the top of BoxingBets.sol, like so: import "./Ownable.sol"; (You can add it just under the line that imports OracleInterface.sol.) Modify the contract declaration of BoxingBets to make it inherit from Ownable, from this: contract BoxingBets { To this: contract BoxingBets is Ownable { And we should be all set. Full code is here in case you got lost: Oracle Contracts Setup Now that the BoxingBets contract is attempting to refer to a completely separate contract (that is the oracle) by address, our next job is to create that oracle contract. So now we’re going to create a whole separate project that will contain the oracle contract. It’s essentially the same setup that we’ve already done for the client contract project; that is, setting up Truffle for compiling and developing. You should already have a folder called /oracle-example/oracle/ which we created in a previous step (or if not, go ahead and create that empty directory now). Open a terminal in that directory. - Run the command truffle init. - Delete /oracle-example/oracle/truffle-config.js. - Edit /oracle-example/oracle/truffle.js like so: module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } }; See the example here: Inside /oracle-example/oracle/migrations/, create a file called 2_deploy_contracts.js, with the following content: var BoxingOracle = artifacts.require("BoxingOracle"); module.exports = function(deployer) { deployer.deploy(BoxingOracle); }; See the example here: Oracle Code For this step, simply copy the following three files from into your /oracle-example/oracle/contracts/ folder: - BoxingOracle.sol: The main oracle contract. - Ownable.sol: For owner-only functions, as we used in the client contract already. - DateLib.sol: A date library. We’ll look at it in more depth in Part 2 of this series. Testing the Oracle Now, in the project’s current iteration, we really need to thoroughly test our smart contract oracle, since that will be our base on which we’ll build the rest of the project. So, now that we’ve set up the oracle project and copied the code, we will want to: - Compile the oracle. - Make sure that the oracle runs. - Run a few functions in the Truffle console to ensure that the oracle is working as expected. Compile and Migrate the Oracle Still in a terminal open to /oracle-example/oracle/, run the following commands. Again, these steps are identical to what we’ve already done to compile and migrate the client contract. truffle compile Alternate: Use my recompile.sh shell script (). Open the Truffle development console: truffle develop Migrate to the test network: truffle(develop)> migrate Run and Test the Oracle Still in the Truffle development console, enter this to capture a usable pointer to the oracle contract: truffle(develop)> BoxingOracle.deployed().then(inst => { instance = inst }) Now we can (and should) run a suite of tests on our oracle contract to test it. Try running the following commands, each in turn, and examine the results. truffle(develop)> instance.testConnection() ... truffle(develop)> instance.getAllMatches() ... truffle(develop)> instance.addTestData() ... truffle(develop)> instance.getAllMatches() ... You are encouraged at this point to have a look through the oracle code, see what public methods are available, read the comments in the code, and come up with some of your own tests to run (and run them here in the console, as shown above). Testing and Debugging Now we’re ready for the final test: to test that the client contract can call the oracle contract that’s already on the blockchain, and pull in and use its data. If all of this works, then we have a client-oracle pair that we can use for further experimentation. Our steps to run the end-to-end test: - Compile and run the oracle contract - Compile and run the client contract - Get the address of the oracle contract - Set the oracle address in the client contract - Add test data to the oracle contract - Test that we can retrieve that data in the client contract Open two terminal windows: - One in /oracle-example/client/ - And the other in /oracle-example/oracle/ I suggest that you keep the /oracle-example/client/ one open on the left and the /oracle-example/oracle/ one open on the right, and follow along closely to avoid confusion. Compile and Run the Oracle Contract Execute the following commands in the /oracle-example/oracle/ terminal: bash recompile.sh truffle develop truffle(develop)> migrate truffle(develop)> BoxingOracle.deployed().then(inst => { instance = inst }) Compile and Run the Client Contract Execute the following commands in the /oracle-example/client/ terminal: bash recompile.sh truffle develop truffle(develop)> migrate truffle(develop)> BoxingBets.deployed().then(inst => { instance = inst }) Get the Address of the Oracle Contract Execute the following command to Truffle in the /oracle-example/oracle/ terminal: truffle(develop)> instance.getAddress() Copy the address which is the output from this call; and use it in the next step. Set the Oracle Address in the Client Contract Execute the following command to truffle in the /oracle-example/client/ terminal: truffle(develop)> instance.setOracleAddress('<insert address here, single quotes included>') And test it: truffle(develop)> instance.testOracleConnection() If the output is true, then we’re good to go. Test that we can Retrieve that Data in the Client Contract Execute the following command to truffle in the /oracle-example/client/ terminal: truffle(develop)> instance.getBettableMatches() It should return an empty array, because no test data has yet been added to the oracle side. Execute the following command to truffle in the /oracle-example/oracle/ terminal to add test data: truffle(develop)> instance.addTestData() Execute the following command to truffle in the /oracle-example/client/ terminal, to see if we can pick up the newly added test data from the client: truffle(develop)> instance.getBettableMatches() Now, if you take individual addresses from the array returned by getBettableMatches(), and plug them into getMatch(). You are encouraged at this point to have a look through the client code, see what public methods are available, read the comments in the code, and come up with some of your own tests to run (and run them here in the console, as above). Conclusion of Part One Our results from this exercise are limited, but then so were our goals, in order to keep a realistic pace. Our client does not yet have the ability to take bets, handle funds, divvy up the winnings, etc. What we do have—aside from the knowledge and experienced gained—is: - A mostly functional smart contract oracle - A client that can connect to and interact with the oracle - A framework for further development and learning And that’s not too bad for a short article. In part two of this series, we will delve more deeply into the code and look at some of the features that are unique to smart contract development as well as some of the language features which are specific to Solidity. Many of the things that were just glossed over in this part will be explained in the next. In part three of this series, we will discuss a bit about the philosophy and design of smart contracts, specifically in relation to their use with oracles. Further Optional Steps Solo experimentation is a good way to learn. Here are a few simple suggestions if you’re thinking of ways to extend this tutorial for greater knowledge (none of the following will be covered in Parts 2 and 3): - Deploy the contracts to Ganache (formerly testrpc) and run the same tests to verify function. - Deploy the contracts to ropsten or rinkeby testnets and run the same tests to verify function. - Build a web3js front end for either the oracle, or the client (or both). Good luck, and please feel free to contact me with any questions. I can’t guarantee a speedy reply necessarily, but I will do my best. Understanding the basics The programming language used in Ethereum development is Solidity. It is a contract-oriented programming language inspired by JavaScript, Python, and C++..
https://www.toptal.com/ethereum/ethereum-oracle-contracts-tutorial-pt1
CC-MAIN-2022-05
refinedweb
4,002
52.7