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
/* ** (c) COPYRIGHT MIT 1995. ** Please first read the full copyright statement in the file COPYRIGH. */ This is the basic include files and the core include files necessary in order to use the W3C Sample Code Library. It contains all core specific modules which are required to compile and build the Library. No converter streams or protocol modules are included in this file as they are for the application to set up. The Library has a special include file called WWWApp.h which contains all converters and protocol modules known to the Library. You can include this one if the application is to use all the functionality of the Library. #ifndef WWWLIB_H #define WWWLIB Basic Utility interface is mostly container modules, dynamic strings and other stuff that you can't live without when building applications. The modules are used by the core part of the W3C Sample Code Library but can also be used by the application. #include "WWWUtil.h" This is the basic include file for the core of the W3C Sample Code Library. The core part of the Library is designed as a set of registration modules with no real functionality in itself. Instead all the functionality comes when the application registeres the modules that provides a desired functionaly, for example accessing HTTP servers or the local file system. #include "WWWCore.h" #ifdef __cplusplus } /* end extern C definitions */ #endif #endif
http://www.w3.org/Library/src/WWWLib.html
CC-MAIN-2015-27
refinedweb
231
63.49
End-to-end encrypted channels (BETA) Note on key rotation: Currently, if a client is unable to decrypt a message, it will make another request to your auth endpoint to obtain a new decryption key. If the client is still unable to decrypt the message with the new key, it will throw an error. We’re thinking about better solutions to this problem, so this may change in the future.!", ) ); pusher_client = pusher.Pusher( app_id='your-app-id', key='your-key', secret='your-secret', ssl: Limitations This feature hides the sensitive data field of your messages. However, by design, there are many things which this feature does not do, and it is important that you are aware of these. They include: - It does not encrypt channel names. Pusher needs to inspect the message’s channel name to determine which clients to send it to. - It does not encrypt event names. Pusher needs to inspect the message’s event name to restrict namespaces (for example, only Pusher can publish events with the prefix pusher:). - It does not encrypt client events. Client events are disallowed on private-encrypted-channels. (We may lift this restriction in future.) - It does not encrypt messages published to channels without the private-encrypted-prefix, even if you have set a master encryption key. - It does not encrypt messages published by server libraries which do not have this feature implemented. Check that your library version is up-to-date. The debug console in your dashboard may help demonstrate which things are encrypted, and which are not. Library Support At the moment encrypted channels are in Beta and library support is limited to those listed below. If you want to use encrypted channels and your library isn’t listed, please let us know! - Client - pusher-js - Supported from version 4.3.0 onwards. - pusher-angular - Supported as long as the pusher-js version used with it is >= 4.3.0. - Server - pusher-http-go - Supported from version 1.1.0 onwards. - pusher-http-php - Supported from version 3.2.0 onwards. - pusher-http-python - Supported from version 2.1.1 onwards. Client events are not currently supported..
https://www.pusher.com/docs/client_api_guide/client_encrypted_channels
CC-MAIN-2019-04
refinedweb
357
57.98
Sven Lankes wrote: On Tue, Dec 09, 2008 at 11:02:30AM +0100, Patrice Dumas wrote:Sometime it is better to push directly to stable, when the package is already broken, when it is a security fix, or for packages with few users.Which then leads to the question, why a broken package was pushed to stable in the first place. We should try to get the bohdi-karma-mechanism more popular. I have updates-testing activated on both my F10 machines but I haven't set a single karma-point yet. The reason is that it's not easy after a day or two to review that last updates and send a +1 on them if I have used them and they didn't break. Maybe a small gui tool showing the latest testing-updates and allowing to send (positive) bohdi-karma would encourage more people to actually send the karma which in turn would encourage developers to use updates-testing more. First of all this falls on to testers... Developers should spend their time developing. Testers should spend their time testing that's what we are here for.And please developers redirect all QA/Test related mail to that "accidentally" falls on to this list to the test-list where testers and QA resides ( Developers should be subscribed to that list to ). Secondly a small bodhi voting gui does not cut it.Testers need know what to test to ensure that the component behaves as it should so you need an application that... A) Fetches the test case for a component and B) Has the ability to log in and vote in bodhi. I suppose I can add that to my TODO list since i'm going to developer ( and hopefully others as well ) the "Fedora-Bug-Reporting" application( Would not be surprised if it ends up being a full blown fedora-test-suite. ) Let's see how easy to learn python really is :) This all hangs on the "QA namespace" where each component will be listedwith info how to test what to report etc.. More on this will be posted to this list ( and ofcourse the test-list ) when we have working examples on the wiki. There is work on the way to address several QA issues. ( Mostly in the implementation discussion stage at this point ) Expected results 2+ releases from now. For those that did not know this is our wiki page.. Will Woods ( wwoods ) is the "Commander in chief" of QA and the Bug Hunters squad ( we should form a band ) The fedora-test list is "our" mailing list. We hang on #fedora-qa We usually hold meetings 1600 UTC on Wednesdays . Previous meetings info can be found here and here
https://listman.redhat.com/archives/fedora-devel-list/2008-December/msg00780.html
CC-MAIN-2021-21
refinedweb
456
68.6
Xamarin team! I am in need of a solution at current for an iOS focused solution (potentially future Android) which will allow an object from a local HTML file which is displayed within a UIWebView to be populated using JavaScript, but calculating the value via C#. The HTML files which I will be utilizing have associating JavaScript files which include business logic that dictates on the HTML form on what is available to the user based off their selection. This is a critical point to the app (and a major reason why a Web View based application is being considered). I have seen the Razor Hybrid project on the Xamarin Blog, however this is not a viable solution due to the fact that the parent data-layer MVC project is not PCL compliant. Looking at the example for the JsBridge package, available on the Component Store (knowing fully aware that it is only for iOS), I do not directly see a way to interact/modify existing objects within the HTML file which is opened in the UIWebView. For example, I wish to have a text-box in my HTML source code which the value to it gets populated through JavaScript via C# (and then later retrieve the value from the text-box). If it is possible, would someone be able to explain how? I have attempted to create a reference via ID of the object in the HTML source, but I have been unsuccessful up to this point in doing so. I have also found in the Xamarin.Forms forum a topic speaking about the HybridWebView as part of the Xamarin.Forms.Labs work (currently this functionality is in alpha), and I was curious if there was someone who could speak on it and give a more detailed explanation of its functionality and if they could explain whether it could meet the criteria which is required? Sources: iOS Android Cross-Platform. Answers I can write a small sample using the HybridWebView. Have you looked at the sample? @SKall, at this time, I have not loaded the sample code to see it in full detail. I was honestly somewhat apprehensive and unsure of its stability given that it is in "alpha" mode. Would you or anyone have any timeline as to when it would come out of "alpha", hit "beta", and then be in the next release of Xamarin.Forms? It may make those above more comfortable for me to tell them that I am using something as part of a major release to Xamarin (rather than test/lab work). Either way, I can pull down the example code and see what it can/can't do, but I would certainly appreciate any insights you can offer on it. It's a bit of a Catch-22 as I wrote the hybrid but I don't have much use for it (nor am I an expert in HTML/JS). I would need more people using it and reporting any issues so I could fix them as needed. It was a curiosity / proof-of-concept project so aside from vector graphics and charting I have not used it much myself. Maybe @MichaelRidland could comment more about its use? I have made some modifications on the Android portion since his article but I am not sure if he has pushed any of his modifications to the Labs branch. Do you have any sample HTML pages you would like to render? If you have the basic HTML already in place it wouldn't take me more than a few minutes to create a sample solution with two-way communication.. Hi. The code is merged over. That blog post mentioned is in depth I think. I will be using it in production, the control isn't very complicated and it's open source so using it isn't a issue for me. Thanks Michael Yes, I read your blog in detail and noticed your changes were the ones to the Func. Just FYI, if you inject a JSON serializer (such as Json.Net or ServiceStack) plugin to the hybrid you can use the CallJsFunction method with parameters. This way there is no need to manually serialize C# objects to JSON. @Skall, thanks so much for your detailed responses, they've been insightful thus far. I'll take a look at your attached demo project and get back to you. At this time, I do not have any raw HTML to show for this project (we're in the process of converting from Web Forms to MVC which must be completed prior to our mobile development if it should function the way we want it too. @SKall, I think the example you provided will certainly help us to proceed. I marked your response with the example solution as the Answer, but it seems like when I did this, it removed the attached zip file after I did so? I'd like to keep it available to anyone who may stumble upon this thread and wishes to see the solution as well. (Perhaps add it back in another comment?) You mention a JSON serializer, with such tie-ins with Json.NET and not having to manually serialize? This has the potential to being beneficial to this project as well. I looked at the source you linked, but I'd like further explanation, if possible. It looks as though you pass a JavaScript function name and then an array of objects, which would be the attribute/values from the JSON stream... would that be an accurate assessment? That said, I'm uncertain as to how the objects from the stream would be tied to an HTML object. What happens if the names are different from the HTML to the JSON stream, like the example below? (Without being clever and ignoring "animal" in the id value of the HTML, this is just to represent a difference in naming between the two.) {"dog":[ {"type":"Labrador", "name":"Lady", "age":"3"} ]} <html> <input id ="animalType", <br /> <input id="animalName", <br /> <input id="animalAge", </html> The function will use the selected JSON serializer to serialize the C# objects to JavaScript here: XLabs has two plugins for JSON, Json.NET & ServiceStack. I used the latter on the sample. You can tweak the C# names to JS names with DataMemberAttribute. Thanks Skall this is what I need i.e. a bare bones implementation that works. Thanks for all your hard work on this! I downloaded the sample project, but It doesnt seem to load the file. Is there something that changed with recent updates? I was trying to see a working sample implementing this functionality. There was a refactoring to better separate functionality. The project is now under XLabs instead of Xamarin.Forms.Labs. You can take the HTML & the page code from the sample and put into a new project. Install package XLabs.Forms & XLabs.Serialization.ServiceStackV3 and fix the namespace in the sample code and it should work.
https://forums.xamarin.com/discussion/comment/82353/
CC-MAIN-2019-43
refinedweb
1,165
70.33
or how Flash broke SQL A few weeks ago, my SQL Server 2005 installation lost the flat file data source option and could not import or export no matter the format. An error was thrown up. ===================================The connection manager could not be created from one or more data sources. (Microsoft Visual Studio)=================================== The connection type "OLEDB" specified for connection manager "{F3C4B394-E196-4AFD-A2F6-37AD9AFCA94D}" is not recognized as a valid connection manager type. This error is returned when an attempt is made to create a connection manager for an unknown connection type. Check the spelling in the connection type name. WTF? After local admins reinstalled, and uninstalled and reinstalled sql server 2005 again to no avail. I fiinaly came across a thread on MSDN: listed below: After compiling and running the code below. I identified 3 keys that as a lowly user, I could not access. After gaining admin access I set the 3 keys to read for everyone, rebooted and was good to go. Get this the keys belonged to Flash. And sure enough, I recall that while having the admin here install the active X control needed for MS virtual labs, (as a lowley user, I could not install it by myself.) the virtual labs prompted for flash to be installed and it was. How flash can break it I am not sure, for most people it appears to be a Lexmark driver that does this. from the post Regarding the access to registry key: it is explained in;en-us;300491. To enumerate connection managers, we are using standard COM API EnumClassesOfCategories (connection managers register under specific category) and the incorrect permissions of that printer driver (or AppCenter in KB) break this API. From the post, link at end: There might be other programs causing this. One way to identify registy keys with incorrect permissions is to compile the program below and run it under low priveleged user account (create a temporary user account, add it only to Users group, run the program). The permissions of the keys identified by the program should be changed to grant Users read access. Compile in C# console app and run under lowest security setting. using namespace { class Program static void Main(string[] args) RegistryKey clsid = Registry.LocalMachine.OpenSubKey(@"Software\Classes\CLSID"); string[] clsids = clsid.GetSubKeyNames(); Console.WriteLine("found {0} keys", clsids.Length); foreach (string s in clsids) try using (RegistryKey clsidKey = clsid.OpenSubKey(s)) using (RegistryKey ic = clsidKey.OpenSubKey("Implemented Categories")) } catch (Exception e) Console.WriteLine("error while reading key {0}: {1}", s, e.Message); Console.ReadLine(); see the post at 24 Dec 2005, 3:58 AM UTC 24 Dec 2005, 3:58 AM UTC
http://geekswithblogs.net/CWeeks/archive/2006/04/14/75190.aspx
CC-MAIN-2013-20
refinedweb
446
56.25
I am trying to parse the following json (org.simple.json) { "TotalCount":4, "Items":[ { "ProductID":879605004504, "Product":{ "Subtitle":"Vibram Fivefingers", "ID":879605004504, "Attributes":[ { "Value":"Vibram Fivefingers", I have a table: A series can be a "root" series, (ParentSeriesID is 0 or null) or it can have a Parent. A series can also be several levels down, i.e. its Parent has a Parent, which has a Parent, etc. ParentSeriesID How can I query the table to get a Series by it's ID and ALL descendant Series' ? Directory is something like: home/ file1.html file2.htmlAnother_Dir/ file8.html Sub_Dir/ file19.html I am using the same PHP Zip class used in PHPMyAdmin . I'm not sure how to zip a directory rather than just a file. Here's what I have to rank the teams in the array "names" (below) in order of who won the most games. If two teams won the same amount of games then I have to compare the wins of the teams that beat them. The code I have so far is below. The full problem statement is given here: So I want to use the comparator recursively. How Ok, well i have been trying to write a recursive version of itoa, this is what i came up with. void itoa(int n, char s[]){ static int i = 0; if(n / 10 != 0) itoa(n/10, s); else if(n < 0) i = 1; /* s[0] is allready taken by - sign */ else i = 0; /* reset i to 0 */ if(n < 0) { itoa recursively I'm trying to link two string together recursively, but not getting the expected results: For the two strings "abcd" and "xyz" - expected output should be "axbyczd": "abcd" "xyz" "axbyczd" def strr(str1, str2): def recstr(str1, str2, prn): if str1 == ': return str2 if str2 == ': retur I want to add the last digit of $colnum as you see in the following. Please refer to comments in the codes. for($c=2;$c<$keynum;$c++){......$studentcomment = ';for($col=1;$col<5;$col++){ $colnum="col".$col."_".$c;// this will find col1_2, col2_2, col3_2, col4_2 $colnum= $this->input->post($colnum);// this will get value from This might seem a bit silly, but I want to try and solve this query in one go. I have a table in a SQL database that links back onto itself. It has an Organization ID and a Parent Organization ID. Top level orgs have a parent ID of 0, and each org at a different level has a parent org of one of the orgs above it. Level of the org used to be determined by another field in the tabl How do i recursively grep all directories and subdirectories ? find . | xargs grep "texthere" * I have the following file name changing log table. ChangeNameLog(Date, OldName, NewName)Primary key: Date, OldName The data of the table looks like (The file name aaa was changed to bbb, and then to c
http://bighow.org/tags/recursively/1
CC-MAIN-2017-26
refinedweb
491
70.33
Re: sfc /scannow won't run - From: "WTC" <bcrawfordjr(remove)@hotmail.com> - Date: Tue, 24 Oct 2006 17:45:54 -0700 Answered inline: "Herb" <hncantor@xxxxxxxxxxxxx> wrote in message news:9FCE1854-FD78-455E-A484-47585FAF2809@xxxxxxxxxxxxxxxx I only have a Toshiba OEM disc, which does not offer the repair function. What if I were to purchase a new XP Home or XP PRo sp2 system disk and attempt a repair or upgrade with one of these? Well this choice is up to you but if you do purchase a Windows XP disc from a retail store, make sure the disc is genuine and the retail store is a reputable dealer. I am not sure if OEM versions allow you to perform repair or upgrade installs but I definitely know retail versions do. Genuine Microsoft Software - How to Tell If you have Windows XP Pro installed then do not purchase a Windows XP Home CD because you cannot downgrade from Pro when using the repair or upgrade method. If you have Windows XP Home installed then you can purchase either Home or Pro. Another question is: do you really need Windows XP Pro? Most users do not require Windows XP Pro since they do not need to encrypt data, run a MS web server, some enhanced security features or have more the 5 concurrent tcp connections. Windows XP Comparision Guide An upgrade retail version of Windows XP should suffice. If you ever need to reinstall Windows XP, you may need to use the Toshiba recovery cd first then upgrade with your purchased XP copy unless you have a qualifying product. Upgrading from Previous Versions of Windows Alternatively, could I wait and do an install of the upcoming VISTA system over the old home xpsp2 now on thne drive? If you do this, make sure your computer can run Vista. There is a link on the following page to check if your computer is ready for Vista. -- William Crawford MS-MVP Windows Shell/User "WTC" wrote: Herb, I now suggest you should perform a repair install of Windows XP. How to Perform a Windows XP Repair Install How to perform an in-place upgrade (reinstallation) of Windows XP -- William Crawford MS-MVP Windows Shell/User "Herb" <hncantor@xxxxxxxxxxxxx> wrote in message news:BA7255FD-10FD-43A7-AB16-772D3F58A53E@xxxxxxxxxxxxxxxx Went through these processes and the Certificate is present. Set it for all functions, restarted and sfc /scannow still won't run! -- Herb "WTC" wrote: Herb, The page is working fine for me. So I quoted a large section from KB296241 for you. <a very big quote from KB296241> When you attempt to use the sfc /scannow command, the command may not work, and you may receive the following error message: Windows File Protection could not be initiate a scan of protected system files. The specific code is 0x000006ba [The RPC Server is unavailable.]. Back to the top CAUSE This behavior can occur if the certificate for VeriSign time stamping has been removed from the computer. This certificate is listed as: "Issued To: No Liability Accepted, (c)97 VeriSign, Inc.". To determine whether this certificate has been removed from the system, follow these steps: 1. Locate a Windows 2000-based computer that exhibits these symptoms. 2. Click Start, click Run, type mmc, and then click OK. 3. In the Microsoft Management Console, click Console, and then click Add/Remove Snap-in. 4. In the Add/Remove dialog box, click Add. 5. Click Certificates, and then click Add. 6. Click Computer Account, and then click Next. 7. Click Local Computer, and then click Finish. 8. Click Close, and then click OK. 9. In the console tree, double-click Certificates (Local Computer). 10. Double-click Trusted Root Certificate Authorities, and then click Certificates. 11. In the details pane, locate the No Liability Accepted certificate. If the certificate is missing, follow the steps in the "Resolution" section to export the certificate from another workstation and import it. Back to the top RESOLUTION To resolve this behavior, the certificate needs to be restored to the original location. To export the certificate from a Windows 2000-based computer, follow these steps: 1. Locate a Windows 2000-based computer. 2. Click Start, and then click Run. 3. In the Open box, type: MMC. 4. When Microsoft Management Console (MMC) is displayed, click Console, and then click Add/Remove Snap-in. 5. On the Add/Remove window, click Add. 6. When the list of available snap-ins are displayed, click Certificates, and then click Add. 7. Click Computer Account. 8. Click Next. 9. Click Local Computer, and then click Finish. 10. Click Close, and then click OK to close out the Add/Remove Snap-in window. 11. Under Console Root, double-click Certificates (Local Computer). 12. Double-click Trusted Root Certificate Authorities, and then double-click Certificates. 13. In the right pane, the installed certificates are displayed. Scroll down the list until you locate the No Liability Accepted certificate. 14. Right-click this certificate, click All Tasks, and then click Export. 15. On the Export Wizard, click Next, click DER encoded Library X.509, and then click Next. 16. In the File name box, enter a file name to save the file (for example, C:\Cert). A .cer extension is added to the file name. 17. Transfer this file to the computer that is receiving the error When the file is transferred to the computer that is receiving the error message, follow these steps to import the file: 1. Click Start, and then click Run. 2. In the Open box, type: MMC. 3. When the MMC starts, click Console, and then click Add/Remove Snap-in. 4. On the Add/Remove Window, click Add. 5. When the list of available snap-ins are displayed, click Certificates, and then click Add. 6. Click Computer Account. 7. Click Next. 8. Click Local Computer, and then click Finish. 9. Click Close, and then click OK to close out the Add/Remove Snap-In window. 10. Under Console Root, double-click Certificates (Local Computer). 11. Right-click Trusted Root Certificate Authorities, click All Tasks, and then click Import. 12. On the wizard, click Next, and then locate the file that you transferred from the other computer. (You may have to change the "Files of Type" field to display the X.509 certificates.) 13. When the file is selected, click Next. 14. Place the certificate in the Trusted Root Certificate Authorities Store, and then click Next. 15. Click Finish. A dialog box is displayed that indicates if the import operation had been successful or not. 16. When the certificate has been transferred, restart the computer, and then observe if the behavior is resolved. Back to the top MORE INFORMATION For more information about Trusted Root certificates, click the following article numbers to view the articles in the Microsoft Knowledge Base: 293781 () Trusted root certificates that are required by Windows Server 2003, by Windows XP, and by Windows 2000 222193 () Description of the Windows File Protection feature </a very big quote from KB296241> -- William Crawford MS-MVP Windows Shell/User "Herb" <hncantor@xxxxxxxxxxxxx> wrote in message news:17857247-E9F9-47BB-8889-A0FB6EC7874D@xxxxxxxxxxxxxxxx link to mspage gets a this page isn't working response -- Herb "WTC" wrote: "Herb" <hncantor@xxxxxxxxxxxxx> wrote in message news:FC8ABC71-F368-4C0C-B3C0-34F4A23E8821@xxxxxxxxxxxxxxxx I get the response "error code 0x000006ba RPC server is unavailable" - how do I correct this problem? This /may/ help you even though the article is for Windows 2000.. Windows File Protection may not start Trusted root certificates that are required by Windows Server 2003, by Windows XP, and by Windows 2000 -- William Crawford MS-MVP Windows Shell/User . - References: - Re: sfc /scannow won't run - From: WTC - Re: sfc /scannow won't run - From: Herb - Re: sfc /scannow won't run - From: WTC - Re: sfc /scannow won't run - From: Herb - Prev by Date: Re: Receiving fax from fax console - Next by Date: Re: No Boot-Up, No Safe Mode, Now What? - Previous by thread: Re: sfc /scannow won't run - Next by thread: Re: adding icons to the system tray - Index(es):
http://www.tech-archive.net/Archive/WinXP/microsoft.public.windowsxp.help_and_support/2006-10/msg03620.html
crawl-002
refinedweb
1,357
71.85
DEBSOURCES Skip Quicknav Patches / attr /1:2.4.48-4 test/run | 2 1 + 1 - 0 ! 1 file changed, 1 insertion(+), 1 deletion(-) [patch 1/9] test: escape left brace in a regex in test/run ... to fix test-suite failure with perl-5.26.0 Bug: man/man1/attr.1 | 17 8 + 9 - 0 ! man/man1/getfattr.1 | 3 2 + 1 - 0 ! man/man1/setfattr.1 | 3 2 + 1 - 0 ! man/man3/attr_get.3 | 3 1 + 2 - 0 ! man/man3/attr_list.3 | 3 1 + 2 - 0 ! man/man3/attr_multi.3 | 3 1 + 2 - 0 ! man/man3/attr_remove.3 | 3 1 + 2 - 0 ! man/man3/attr_set.3 | 3 1 + 2 - 0 ! 8 files changed, 17 insertions(+), 21 deletions(-) [patch 2/9] man: fix bold style in see also section See STYLE GUIDE in man-pages(7) for more details. man/man1/attr.1 | 10 10 + 0 - 0 ! man/man1/getfattr.1 | 5 4 + 1 - 0 ! man/man1/setfattr.1 | 5 4 + 1 - 0 ! 3 files changed, 18 insertions(+), 2 deletions(-) [patch 3/9] man: standardize authors section Point people to the Savannah project now. configure.ac | 1 1 + 0 - 0 ! test/attr.test | 6 6 + 0 - 0 ! 2 files changed, 7 insertions(+) [patch 4/9] enable large-file support on systems that do not enable it by default Invoke AC_SYS_LARGEFILE to enable large-file support. This fix doesn't change the library as much as the tools because the only affected function in libattr is attr_copy_action that calls attr_parse_attr_conf that in turn calls fopen(ATTR_CONF, "r"). What is the most affected is getfattr, without the fix it just cannot process large files, e.g. $ truncate -s2G large-file && getfattr large-file getfattr: large-file: Value too large for defined data type man/man1/getfattr.1 | 6 3 + 3 - 0 ! 1 file changed, 3 insertions(+), 3 deletions(-) [patch 5/9] getfattr.1: by default only user namespace attributes are dumped man/man3/attr_list.3 | 2 1 + 1 - 0 ! 1 file changed, 1 insertion(+), 1 deletion(-) [patch 6/9] attr_list.3: fix the attributes.h include path The header file is located at <attr/attributes.h>. Make the attr_list.3 man page consistent with the other man pages. libattr/syscalls.c | 26 14 + 12 - 0 ! 1 file changed, 14 insertions(+), 12 deletions(-) [patch 7/9] switch back to syscall() Switch back to syscall() for the *xattr system calls. The current mechanism of forwarding those calls to glibc breaks libraries like libfakeroot (fakeroot) and libasan (the gcc address sanitizer; gcc -fsanitize=address). Those libraries provide wrappers for functions defined in other shared libraries, usually glibc, do their own processing, and forward calls to the original symbols looke dup via dlsym(RTLD_NEXT, "symbol_name"). In our case, dlsym returns the libattr_*xattr wrappers. However, when our wrappers try calling glibc, they end up calling the libfakeroot / libasan wrappers instead because those override the original symbols => recursion. The libattr_*xattr wrappers will only be used when symbols are looked up at runtime (dlopen / dlsym). Programs linking against libattr will directly use the glibc provided symbols. Therefore, the slightly worse performance of syscall() won't affect any of the "normal" users of libattr. libattr/libattr.c | 4 2 + 2 - 0 ! 1 file changed, 2 insertions(+), 2 deletions(-) [patch 8/9] attr_multi, attr_multif: don't set errno to -einval When attr_multi or attr_multif are called with an invalid am_opcode, they fail with errno set to -EINVAL. Instead, the errno value should be positive. libattr/libattr.c | 12 7 + 5 - 0 ! 1 file changed, 7 insertions(+), 5 deletions(-) [patch 9/9] attr_list, attr_listf: guard against unterminated buffer attr_list and attr_listf can crash when the listxattr, llistxattr, or flistxattr syscalls incorrectly return an unterminated buffer. Guard against that by always appending a null character. configure.ac | 1 1 + 0 - 0 ! 1 file changed, 1 insertion(+) fix for incompatibility with autoconf2.13 This package will not build if autconf2.13 is installed. Adding AC_PREREQ allows the automatic checks to run the correct version of autconf, whichever is installed, or to get a clear error message about the problem. Bug-Debian: configure.ac | 6 6 + 0 - 0 ! libattr/Makemodule.am | 17 14 + 3 - 0 ! 2 files changed, 20 insertions(+), 3 deletions(-) only include the compat syscall stubs on linux systems These are Linux specific syscalls. Other systems either already have include/Makemodule.am | 3 3 + 0 - 0 ! include/xattr.h | 29 29 + 0 - 0 ! 2 files changed, 32 insertions(+) reintroduce removed xattr.h header for backwards compatibility. There are too many packages still using this header, we cannot just remove it w/o breaking tons of stuff. Let's create a proper transition. . We will later introduce a warning so that programs transition to the header provided by glibc. man/man1/getfattr.1 | 2 1 + 1 - 0 ! man/man3/attr_multi.3 | 6 3 + 3 - 0 ! man/man3/attr_remove.3 | 2 1 + 1 - 0 ! 3 files changed, 5 insertions(+), 5 deletions(-) fix various typos Warned-by: lintian
https://sources.debian.org/patches/attr/1:2.4.48-4/
CC-MAIN-2019-30
refinedweb
824
60.82
Localizing, unit testing and using AJAX in ASP.NET MVC applications Unit testing MVC applications One of the great benefits of ASP.NET MVC applications is the ability to better test your code with unit tests. Although it is possible to test regular ASP.NET WebForms applications, this is often considerably more difficult as the application model leads you into mixing user interfaces, data access and logic into same code files and classes. On the other hand, ASP.NET MVC application structure helps creating more natural boundaries for unit tests. Often, controller classes are the best place to start testing. Since the controller methods do not require any user interface and thus no interactive use to function, they are good candidates for tests. When you start an ASP.NET MVC project, Visual Studio asks whether you want to add a unit testing project to your solution. If you added one, then your solution should look like the one in Figure 3. Figure 3. The default solution structure of an ASP.NET MVC application. The default template suggests creating one unit test for each controller method, but there is no limit to the number of tests you can write. If you have at least Visual Studio 2008 Professional, then you can use the Test/Run/All Tests in Solution menu command to run all available tests in your solution (Figure 4). Figure 4. Unit test results in Visual Studio. Writing your tests for ASP.NET MVC applications is similar to writing them for other .NET application types. You can use the Assert class (defined in the Microsoft.VisualStudio.TestTools.UnitTesting namespace) to let Visual Studio know about the results of your tests. For instance, your test might check whether the controller method Customers returns correct data in the ViewData object: [TestMethod] public void Customers() { HomeController controller = new HomeController(); ViewResult result = controller.Customers() as ViewResult; ViewDataDictionary viewData = result.ViewData; string tableName = "Customers"; Assert.AreEqual(tableName, viewData["tableName"]); } When your tests are fast in their execution, running even hundreds of tests goes swiftly. However, since many ASP.NET MVC applications use SQL databases, testing those access routines can take time. Of course, you should test your data access classes (perhaps the models) as well, but often it's more convenient to simulate database access in testing routines with in-memory static data. One option to implement this is to create a data access interface, which is then implemented by a one class doing the real database access, and another only simulating such access. This simulating class would return static data from memory instead of accessing a real database. With these two implementations, you could use the real one in your application, and the simulating one in your unit tests. For controller tests, this kind of simulated data access is usually enough, and additionally much faster to test. In fact, such simulating classes are often called mock objects. Mock objects can be used in place of real objects, and thus help in writing your unit tests. Database access is one place where such mock objects are useful, but there are other situations as well. For database access, it is often useful to write your own mock objects, but for other testing tasks, such as those requiring authentication, you might want to use ready-made mock object libraries. There are several libraries available for .NET, three quite common ones being EasyMock.NET, Moq and Rhino Mocks. All these are open-source solutions, and can be found from the web addresses shown in the Links section. Using mocks depends on the library, but commonly they require you to initialize the framework, after which you can use the mock objects to substitute the real ones.For instance, if your views are protected so that only authorized users can access them (specified using the Authorize attribute in the controller), then your unit tests might need to construct the proper authentication objects to make the tests succeed. Specifically, this would mean the User and Identity objects. Here is an example of using the Moq library to set up a mock object to help testing views that require authentication: using Moq; using System.Web; using System.Security.Principal; ... HomeController controller = new HomeController(); var context = new Mock<ControllerContext>(); var user = new Mock<IPrincipal>(); var identity = new Mock<IIdentity>(); context.Setup( ctx => ctx.HttpContext.User).Returns( user.Object); user.Setup(ctx => ctx.Identity).Returns( identity.Object); identity.Setup( id => id.IsAuthenticated).Returns(true); identity.Setup( id => id.Name).Returns("John Doe"); controller.ControllerContext = context.Object; The Moq library relies heavily on C# lambda expressions, giving a modern touch to your unit tests. The framework is also quite simple to learn, provided that you already are at least somewhat familiar with the said lambda expressions. Note that if you download a testing framework as only binary files, you might run into security issues. This can happen if you simply copy the DLL file(s) into your solution folder and then try to use the framework using a reference. In such a situation, you might notice that Visual Studio reports "Not Executed" while running your tests. If the error details say something like, "Test Run deployment issue: The location of the file or directory 'library.dll' is not trusted", then it is a security issue. The easiest way to solve this is to go to the DLL file's properties window in Windows Explorer (Alt + double click), and then click the Unblock button. The other option is to add full trust to the assembly with the CasPol utility.<<
https://www.developer.com/print/article.php/10916_3820201_2
CC-MAIN-2019-22
refinedweb
924
56.76
RoboFont › Forums › Help / General › Scripting: nearest oncurve point for a given coordinate This topic contains 2 replies, has 2 voices, and was last updated by Jens K. 6 days, 8 hours ago. - AuthorPosts Anonymous Dear Robofonters, I’ve just started testing this wonderful app for the first time in my life and I’m planning to rewrite my (at least for me) very useful plugin from the GlyphsApp: StemThickness (). For this purpose I need to find the nearest on-curve point for the coordinate of the cursor point. And I’ve found it: (here: ) Right now I’m looking for something I would call “time of the on-curve point”. This is the ratio needed for further calculation for my extension. Following equation is the standard equation for the bezier curve. I have given B (coordinates of the nearest on-curve point), A, B, C, D (curve’s control points). I’m looking for “t” value: B = (1 – t)^3*A + 3*(1 – t)^2 *t*B + 3*(1 – t) *t^2 *C + t^3 * D , 0 <= t <= 1, t=? Do you guys know any fast method for finding “t” value of given on-curve point and bezeir curve’s control points? I hope that this message is quite clear :) I’m not the best at explaining math stuff at forums. Cheers Rafał I have looked for a solution to this myself, and actually ended up taking your numerical approach from the Glyphs plugin ;) As I understand it, there may not be a solution to the equation if the given point is not exactly on the curve, which may already happen because floating point numbers are not exact. So you need to find t so that the distance of P(t) to the given point is minimized. This stackexchange answer may be something, but I didn’t understand the stuff about inversions: If you can make any sense of it, I am very interested :) I found a way to speed up the brute force approach though. If you can use external Python modules: from scipy import spatial tree = spatial.KDTree(t_list) # t_list is a list of pre-calculated point coordinate tuples on the cubic curve distance, index = tree.query(pt) # pt is the given point coordinate tuple t_for_pt = float(index) / (len(tree.data) - 1) t_list must be constructed in a way that the first entry is for t = 0 and the last entry for t = 1. It doesn’t matter how many points for increments of t you calculate, as long as the index in t_list is proportional to t. Smaller increments of t increase the precision of the result, but the list takes longer to build. - AuthorPosts You must be logged in to reply to this topic.
http://doc.robofont.com/forums/topic/scripting-nearest-oncurve-point-for-a-given-coordinate/
CC-MAIN-2017-30
refinedweb
458
67.79
cl-compatpackage This document describes a set of Emacs Lisp facilities borrowed from Common Lisp. All the facilities are described here in detail. While this document does not assume any prior knowledge of Common Lisp, it does assume a basic familiarity with Emacs Lisp. This file documents the GNU Emacs Common Lisp emulation package. Copyright © 1993,, CL adds enough functionality to make Emacs Lisp programming significantly more convenient.. Some Common Lisp features have been omitted from this package for various reasons: assocfunction is incompatible with the Common Lisp assoc. In such cases, this package usually adds the suffix ‘*’.. This. This form is identical to the regular defunform, except that arglist is allowed to be a full Common Lisp argument list. Also, the function body is enclosed in an implicit block called name; see Blocks and Exits. This is just like versions of Emacs, and also generates somewhat more efficient inline expansions. In particular, defsubst*arranges for the processing of keyword arguments, default values, etc., to be done at compile-time whenever possible. This is identical to the regular. This is identical to the regular (var... &optional (var initform svar)... &rest var &key ((keyword var) initform svar)... &aux (var initform)...) Each of the five argument list sections is optional. The svar, initform, and keyword parts are optional; if they are omitted, then ‘(var)’ may be written simply ‘var’., (defun* foo (a &optional b &key c d (e. You can also explicitly specify the keyword argument; it need not be simply the variable name prefixed with a colon. For example, (defun* bar (&key (a 1) ((baz b) 4))) specifies a keyword :a that sets the variable a with default value 1, as well as a keyword baz that sets the variable b with default value 4. In this case, because baz is not self-quoting, you must quote it explicitly in the function call, like this: (bar :a 10 'baz 42): member* from complaining about each others' keywords in the arguments.: (defun* foo (a b &aux (c (+ a b)) d) body) (defun* foo (a b) (let ((c (+ a b)) d) body)): (defmacro* dolist ((var listform &optional resultform) &rest ‘. This form controls when the body forms are evaluated. The situations list may contain any set of the symbols compile, load, and eval(or their long-winded ANSI equivalents, :compile-toplevel, :load-toplevel, and :execute). The eval-whenacts like a prognif evalis specified, and like nil(ignoring the body forms) if not. The rules become more subtle when eval-whens are nested; consult Steele (second edition) for the gruesome details (and some gruesome examples). Some simple examples:;; Top-level forms in foo.el: (eval-when (compile) (setq foo1 'bar)) (eval-when (load) (setq foo2 'bar)) (eval-when (compile load) (setq foo3 'bar)) (eval-when (eval) (setq foo4 'bar)) (eval-when (eval compile) (setq foo5 'bar)) (eval-when (eval load) (setq foo6 'bar)) eval-whens had been, say, inside a defun, then the first three would have been equivalent to nil includes two special forms related to eval-when. One of these, eval-when-compile, is not quite equivalent to any eval-when construct and is described below. The other form, (eval-and-compile ...), is exactly equivalent to ‘(eval-when (compile load eval) ...)’ and so is not itself defined by this package. load-time-valueact exactly like progn.(defun report () (insert "This function was executed on: " (current-time-string) ", compiled on: " (eval-when-compile (current-time-string)) ;; or '#.(current-time-string) in real Common Lisp ", and loaded on: " . This macro defines a new type called name. It is similar to ‘(name args...)’ is expanded by calling the expander with those arguments; the type symbol ‘name’ (deftype unsigned-byte (&optional bits) (list 'integer 0 (if (eq bits '*) bits (1- (lsh 1 bits))))) (unsigned-byte 8) == (integer 0 255) (unsigned-byte) == (integer 0 *) unsigned-byte == (integer 0 *) The last example shows how the Common Lisp unsigned-bytetype specifier could be implemented if desired; this package does not implement unsigned-byteby default. The typecase and check-type macros also use type names. See Conditionals. See Assertions. The map, concatenate, and merge functions take type-name arguments to specify the type of sequence to return. See Sequences.. The features described in the following sections implement various advanced control structures, including the powerful setf facility and a number of looping and conditional constructs. Modify Macros, for the letf and letf* forms which are also related. This form is just like lexical-let, except that the bindings are made sequentially in the manner of let*.. These forms create local macros and “symbol macros.” This form is analogous to:(defmacro* my-dolist ((x list) &rest body) (let ((var (gensym))) (list 'loop 'for var 'on list 'do (list* 'symbol-macrolet (list (list x (list 'car var))) body)))) (setq mylist '(1 2 3 4)) (my-dolist (x mylist) form returns nil. The clauses are of the form(keylist body-forms...) where keylist is a list of key values. If there is exactly one value, and it is not a cons cell or the symbol nilor t, then it can be used by itself as a keylist without being enclosed in a list. All key values in the caseform must be distinct. The final clauses may use tin place of a keylist to indicate a default clause that should be taken if none of the other clauses match. (The symbol otherwiseis also recognized in place of t. To make a clause that matches the actual symbol t, nil, or otherwise, enclose the symbol in a list.) For example, this expression reads a keystroke, then does one of four things depending on whether it is an ‘a’, a ‘b’, a <RET>,(typecase x (integer (munch-integer x)) (float (munch-float x)) (string (munch-integer (string-to-int x))) (t (munch-anything x))) The type specifier tmatches any type of object; the word otherwiseis also allowed. To make one clause match any of several types, use an (or ...)type specifier. This macro is just like typecase, except that if the key does not match any of the clauses, an error is signaled (return-from nilresult ). Common Lisp loops like doand dolistimplicitly enclose themselves in nilblocks.. A loop construct consists of a series of clauses, each introduced by a symbol like. (loop for x from 1 to 100 for y = (* x x) until (>= y 729) finally return (list x (= y 729))) This more complicated loop searches for a number x whose square is 729. For safety's sake it only examines x values up to 100; dropping the phrase ‘tointeger (loop repeat (1+ Accumulation clauses can be followed by ‘into valid for several accumulation clauses of the same type to accumulate into the same place. From Steele: (loop for name in '(fred sue alice joe june) for kids in '((bob ken) () () (kris sunshine) ()) collect name append kids) ⇒ ) ‘= nil’ in the above example is unnecessary.) Bindings made by with are sequential by default, as if by let*. Just like for clauses, with clauses can be linked with and to cause the bindings to be made by let instead. ifcondition: (setq funny-numbers '(6 13 -1)) ⇒ (6 13 -1) (loop for x below 10) (loop <same thing again>) ⇒ loopform. . Common. This package defines several symbol-related features that were missing from Emacs Lisp.function always uses nilas the default; this package's get*is equivalent to Common Lisp's get.) The get*function is setf-able; when used in this fashion, the default argument is allowed but ignored. This function removes the entry for property from the property list of symbol. It returns a true value if.) This function scans the list place as if it were a property list, i.e., a list of alternating property names and values. If an even-numbered element of place is found which is eqto property, the following odd-numbered element is returned. Otherwise, default is returned (or nilif no default is given). In particular,(get sym prop) == (getf (symbol-plist sym) prop) It is valid to use getfas a setfplace, in which case its place argument must itself be a valid setfplace.) == (setf orm, getfplace (cddrplace )), whereas if it occurs later, this simply uses setcdrto splice out the property and value cells..ymin. These functions return t if the specified condition is true of the numerical argument, or nil otherwise. This predicate tests whether number is positive. It is an error if the argument is not a number. This predicate tests whether number is negative. It is an error if the argument is not a number. This predicate tests whether integer is odd. It is an error if the argument is not an integer. This predicate tests whether integer is even. It is an error if the argument is not an integer. This predicate tests whether object is a floating-point number. On systems that support floating-point, this is equivalent to floatp. On other systems, this always returns nil. These functions perform various arithmetic operations on numbers. This function returns the Greatest Common Divisor of the arguments. For one argument, it returns the absolute value of that argument. For zero arguments, it returns zero. This function returns the Least Common Multiple of the arguments. For one argument, it returns the absolute value of that argument. For zero arguments, it returns one. This function computes the “integer square root” of its integer argument, i.e., the greatest integer less than or equal to the true square root of the argument. This function implements the Common Lisp floorfunction. It is called floor*to avoid name conflicts with the simpler floorfunction built-in to Emacs. With one argument, floor*returns, floor*divides number by divisor, and returns the floor of the quotient and the corresponding remainder as a list of two numbers. If (floor*x y )returns (q r ), then q *y +r =x, with r between 0 (inclusive) and r (exclusive). Also, note that (floor*x )is exactly equivalent to (floor*x 1). This function is entirely compatible with Common Lisp's floorfunction, except that it returns the two results in a list since Emacs Lisp does not support multiple-valued functions. This function implements the Common Lisp ceilingfunction, which is analogous to floorexcept that it rounds the argument or quotient of the arguments up toward plus infinity. The remainder will be between 0 and minus r. This function implements the Common Lisp truncatefunction, which is analogous to floorexcept that it rounds the argument or quotient of the arguments toward zero. Thus it is equivalent to floor*if the argument or quotient is positive, or to ceiling*otherwise. The remainder has the same sign as number.. This function returns the same value as the second return value of floor. This function returns the same value as the second return value of truncate. These definitions are compatible with those in the Quiroz cl.el package, except that this package appends ‘*’ to certain function names to avoid conflicts with existing Emacs functions, and that the mechanism for returning multiple values is different. which holds the state of the random number generator. The function modifies this state object as a side effect. If state is omitted, it defaults to the variable *random-state*, which contains a pre-initialized random-stateobject. This variable contains the system “default” random-stateobject, used for calls to random*that do not specify an alternative state object. Since any number of programs in the Emacs process may be accessing *random-state*in interleaved fashion, the sequence generated from this variable will be irreproducible for all intents and purposes. This function creates or copies a random-stateobject. If state is omitted or nil, it returns a new copy of *random-state*. This is a copy in the sense that future sequences of calls to (random*n )and (random*n (make-random-state t)to get a new sequence, then print this sequence to a file. When the program is later rerun, it can read the original run's random-state from the file. This predicate returns tif object is a random-stateobject, or nilotherwise. This package defines several useful constants having to with numbers. The following parameters have to do with floating-point numbers. This package most-positive-floathave been initialized. Until it is called, these parameters will be nil. If this version of Emacs does not support floats, the parameters will remain nil. If the parameters have already been initialized, the function returns immediately. The algorithm makes assumptions that will be valid for most modern least-positive-float. This constant is the negative counterpart of. This is the smallest positive value that can be subtracted from 1.0 to produce a distinct value. For IEEE machines, it is about 1.11e-16. Common Lisp defines a number of functions that operate on sequences, which are either lists, strings, or vectors. Emacs Lisp includes a few of these, notably elt and length; this package defines most of the rest.: (remove* 0 seq :test '=) == ' . This returns a copy of seq with all elements matching item removed. The result may share storage with or be). This deletes all elements of seq which match item. It is a destructive operation. Since Emacs Lisp does not support stretchable strings or vectors, this is the same as. Lists.). This function is like find, except that it returns the integer position in the sequence of the matching item rather than the item itself. The position is relative to the start of the sequence as a whole, even if :startis non-zero. The function returns nilif no matching element was found. This function returns the number of elements of seq which match item. The result is always a nonnegative integer. The find-if, find-if-not, position-if, position-if-not, count-if, and. This function searches seq2 for a subsequence that matches seq1 (or part of it specified. This function sorts seq into increasing order as determined by using predicate to compare pairs of elements. predicate should return true (non. These functions substitute elements throughout a tree of cons cells. (See Sequence Functions, for the substitute function, which works on just the top-level elements of a list.) This function substitutes occurrences of old with new in tree, a tree of cons cells. It returns a substituted tree, which will be a copy except that it may share storage with the argument tree in parts where no substitutions occurred. The original tree is not modified. This function recurses on, and compares against old, both cars and cdrs of the component cons cells. If old is itself a cons cell, then matching cells in the tree are substituted as usual without recursively substituting in that cell. Comparisons with old are done according to the specified test ( eqlby default). The :keyfunction is applied to the elements of the tree but not to old. This function is like.) This function searches for an element whose cdr) ⇒ person which.(defstruct (person1) name age sex) (defstruct (person2 (:type list) :named) name age sex) defstruct facility of this package is entirely compatible with that of Common Lisp.value). If so, it returns nil. If the test is not satisfied,:, check-typesignals a wrong-type-argumenterror. The default error message lists the erroneous value along with type and form themselves. If string is specified, it is included in the error message in place of type. For example: incf a hundred times will execute considerably faster if compiled, and will also garbage-collect less because the macro expansion will not have to be generated, used, and thrown away a hundred times. You can find out how a macro expands by using the cl-prettyexpand function. This function takes a single Lisp form as an argument and inserts a nicely formatted copy of it in the current buffer (which must be in Lisp mode so that indentation works properly). It also expands all Lisp macros which appear in the form. The easiest way to use this function is to go to the defun* and friends) are checked rigorously except for the minor point just mentioned; in particular, keyword arguments are checked for validity, and &allow-other-keys and :allow-other-keys are fully implemented. Keyword validity checking is slightly time consuming (though not too bad in byte-compiled code); you can use &allow-other-keys to omit this check. Functions defined in this package such cl.el package. This package's emulation of multiple return values in functions is incompatible with that of the older package. That package attempted to come as close as possible to true Common Lisp multiple return values; unfortunately, it could not be 100% reliable and so was prone to occasional surprises if used freely. This package uses a simpler method, namely replacing multiple values with lists of values, which is more predictable though more noticeably different from Common Lisp. The defkeyword form and keywordp function are not implemented in this package. The member, floor, ceiling, truncate, round, mod, and rem functions are suffixed by ‘*’-‘ package defines a set of multiple-value macros that are compatible with the old CL package; again, they are heuristic in nature, but they are guaranteed to work in any case where the old package's macros worked. To avoid name collision with the “official” multiple-value facilities, the ones.). Emacs Lisp, by contrast, uses dynamic scoping wherein a binding to a variable is visible even inside functions called from the body. Variables in Common Lisp can be made dynamically scoped by declaring them special or using defvar. In Emacs Lisp it is as if all variables were declared special. Often you can use code that was written for lexical scoping even in a dynamically scoped Lisp, but not always. Here is an example of a Common Lisp code fragment that would fail in Emacs Lisp: (defun map-odd-elements (func list) (loop for x in list for flag = t then (not flag) collect (if flag x (funcall func x)))) (defun add-odd-elements (list x) (map-odd-elements (lambda (a) (+ a x)) list)) In Common Lisp, the two functions' usages of x are completely independent. In Emacs Lisp, the binding to x made by add-odd-elements will have been hidden by the binding in map-odd-elements by the time the (+ a x) function is called. (This package avoids such problems in its own mapping functions by using names like cl-x instead of x internally; as long as you don't use the cl- prefix for your own variables no collision can occur.) See Lexical Bindings, for a description of the lexical-let form which establishes a Common Lisp-style lexical binding, and some examples of how it differs from Emacs' regular let. ', which, tagbody, prog, ldb/dpb, parse-integer,
http://www.gnu.org/software/emacs/manual/html_mono/cl.html#Top
crawl-003
refinedweb
3,124
63.9
newLISP — An Interactive Tutorial This document was reformatted for HTML and a few corrections and updates made by Rick Hanson in May 2006, cryptorick@gmail.com. updates for v.10.0 by L.M. January 2008, December 2011, November 2014. You can download and install newLISP from. Please send any comments or questions regarding this tutorial to jsmall@atlaol.net. Hello World! With newLISP installed on your system, at the shell command line prompt enter newlisp to start the REPL (Read, Eval, Print Loop). On Linux, your console would look something like this:$ newlisp > _ And on Windows platforms, it would look something like this:c:\> newlisp > _ After starting up, newLISP responds with a prompt.> _ Enter the expression below in order to print "Hello World!" on the console.> (println "Hello World!") newLISP prints the value of the expression entered at the REPL prompt before looping and prompting for more input.> (println "Hello World!") Hello World! "Hello World!" > _ Why did it print twice? The println function prints the first line, i.e.Hello World! to the console as a side effect of calling the function. The println function then returns the "Hello World!" string, i.e. its last argument, to the REPL which in turn prints the second line, i.e."Hello World!" The REPL will evaluate any expression and not just function calls.> "Hello World!" "Hello World!" > _ If you enter the string expression "Hello World!", as shown above, it simply returns itself as would any literal expression such as literal numbers.> 1 1 > _ By now you may be turned off by the parentheses. If you are coming to newLISP from a mainstream computer language, it would seem more natural to write a function call like this:println("Hello World!") You'll just have to take my word for it — in time you will actually prefer(println "Hello World!") toprintln("Hello World!") for reasons that cannot be adequately explained until you have seen a lot more examples of symbolic list processing. Source Code and Data are Interchangeable Lisp stands for List Processor. Since lists are used to represent both code and data in Lisp they are essentially interchangable. The previous println expression is really a list with two elements.(println "Hello World!") The first element isprintln and the last element is"Hello World!" Lisp always interprets a list as a function call unless you quote it, thereby indicating that it should be taken literally as a symbolic expression, i.e. data.> '(println "Hello World!") (println "Hello World!") > _ A symbolic expression can be evaluated as source code, however.> (eval '(println "Hello World!")) Hello World! "Hello World!" > _ A Lisp program can literally extend itself at run time by building lists of data and then executing them as source code!> (eval '(eval '(println "Hello World!"))) Hello World! "Hello World!" > _ Actually the ' is syntactical sugar for quote.> (quote (println "Hello World!")) (println "Hello World!") > _ Think of quote as taking its argument literally, i.e. symbolically.> 'x x > (quote x) ' x > '(1 2 three "four") (1 2 three "four") > _ Symbols, such as x and three above, and symbolic lists play a vitally important role in AI, i.e. Artifical Intelligence. This tutorial will not cover AI topics. However, once you know how to program in Lisp, you'll be able to readily follow the ubiquitous Lisp examples found in most textbooks on AI. Consider the following example.> 'Hello Hello > "Hello" "Hello" > _ The symbol 'Hello is not the same as the literal string "Hello". Now you can appreciate why the REPL prints the double quotes to indicate a literal string, thereby distinguishing it from a symbol having the same letters. Function arguments The println function can also take a variable number of arguments.> (println "Hello" " World!") Hello World! " World!" > _ The arguments are merely concatenated on the output stream while the last argument is returned as the value of the function call. Typically, arguments passed to a function are evaluated from left to right and the resulting values are then passed on to the function. The actual arguments to a function are said to be strictly evaluated. This is known as applicative-order evaluation. But notice that, for the quote function, this is not the case.> (quote (println "Hello World!")) (println "Hello World!") > _ If its argument, namely(println "Hello World!") had been strictly evaluated, we would have seenHello World! displayed on the console. The quote function is an atypical function sometimes referred to as a "special form". You can write your own special form functions in newLISP as well. These are called macros and their arguments are said to be called by name, i.e. literally. This is known as normal-order evaluation and we say the evaluation strategy is lazy. In other words, a macro's arguments aren't evaluated until, and only if, you direct them to be evaluated (as we shall see how later). Thus, the argument to quote is taken literally and returned. In a sense, quote is an identity function with a lazy evaluation strategy. It never bothers to evaluate its argument, but instead, simply returns it literally in its symbolic source code form. Without special forms, the flow control constructs found in other languages could not be implemented in a language having only list expressions as syntax to work with. For example, consider the if list below.> (if true (println "Hello") (println "Goodbye")) Hello "Hello" > _ The if special form takes three arguments.syntax: (if condition consequence alternative) condition => true consequence => (println "Hello") alternative => (println "Goodbye") The condition argument is always evaluated, i.e. strict, but the consequence and alternative expressions are lazy. Furthermore the alternative expression is optional. Notice that if is an expression. It returns the value of its consequence or alternative expression depending on whether the condition is true or false respectively. In the example above, we know that the alternative expression wasn't evaluated, because its side effect of printing "Goodbye" on the console never occurred. The value of an if expression with a false condition having no alternative is simply nil. The nil value indicates either void or false depending upon the interpretation required. Note: In most mainstream computer languages if is a statement, and thus doesn't have a return value. If Lisp lacked a lazy evaluation strategy, it could not be used to implement special forms or macros. Without a lazy evaluation strategy, additional keywords and/or syntax would have had to have been added to the language. What syntax have you seen thus far, other than parenthesis and quotes? Answer: not much! The flip side of lazy evaluation is you can now add your own flow control to the language thereby extending the "syntax" of Lisp allowing you to embed application specific mini-languages. Writing functions and macros will be covered in a later section of this tutorial. Side Effects and Contexts Without side effects, having an REPL would be pointless. To see why, consider the following sequence of expressions.> (set 'hello "Hello") "Hello" > (set 'world " World!") " World!" > (println hello world) Hello World! " World!" > _ The set function above has a side effect, as demonstrated below.> hello "Hello" > world " World!" > _ The symbols 'hello and 'world are bound in the current context to "Hello" and " World!" respectively. All the built-in functions are bound to symbols in the MAIN context.> println println <409040> > set set <4080D0> > _ This tells us that println is bound to a function named println with an entry point of 409040. (Different builds of newLISP will obviously have different entry points for println.) The default context is MAIN. A context is essentially a stateful namespace. We'll learn about user defined contexts later. Notice that the literal symbol 'hello evaluates to itself.> 'hello hello > _ Evaluating the 'hello symbol returns the value it is bound to in the current context.> (eval 'hello) "Hello" > _ If the symbol is unbound when evaluated, it simply returns nil.> (eval 'z) nil > _ Actually we don't need the eval, since the symbol without the quote is automatically evaluated in the current context.> hello "Hello" > z nil > _ Thus the value of hello and world below are "Hello" and " World!" respectively.> (println hello world) Hello World! " World!" > _ What would be displayed, if we enter the following?> (println 'hello 'world) ? Think about it for a moment. The println function displays the symbols one immediately after other on the first line.> (println 'hello 'world) helloworld world > _ Expression Sequences A sequence of expressions can be combined into a compound expression with the begin function.> (begin "Hello" " World!") " World!" > _ What happened to "Hello"? Since a compound expression returns a single value, it returns the value of its last expression. But the expressions are indeed evaluated in sequence. It's just that the "Hello" expression has no side effect, so its return value is discarded and you never see any evidence of its evaluation.> (begin (print "Hello") (println " World!")) Hello World! " World!" > _ This time, the side effects of print and println are evidenced in the console window and the last value returned is displayed by the REPL. The begin function is useful in combining expressions into a single expression. Reconsider the if special form.> (if true (begin (print "Hello") (println " newLISP!")) (println "So long Java/Python/Ruby!")) Hello newLISP! " newLISP!" > _ Multi-line statements and functions are entered hitting the [enter] key at the prompt. To exit multi-line mode hit the [enter] key again at the prompt. Recall that the if form only takes three arguments.syntax: (if condition consequence alternative) The (begin ...) expression is used to combine two expressions into a single expression, which is then passed as the consequence argument. Let's rap up this section by seeing how to turn our example into a program. Please note that you can exit the REPL at any time by calling exit.> (exit) $ Or, on windows> (exit) c:\> You can also exit with an optional integer argument.> (exit 3) This would be useful in shell or batch file processing that branched on reported error codes. We can now put our hello world expression sequence into a source file.; This is a comment ; hw.lsp (println "Hello World!") (exit) And we can execute it from the command line, like this:$ newlisp hw.lsp Hello World! Or in windows:c:\> newlisp hw.lsp Hello World! Executables and Dynamic Linking Making platform native executables and linking to dynamic link libraries with newLISP is simple. Depending on your distribution, you should find the link.lsp file in the examples subdirectory or you may have to download the examples and modules separately from. First load link.lsp into newLISP. At the command prompt you would type in:$ newlisp link.lsp or in windows:c:\> newlisp link.lsp Alternatively you can load link.lsp from the newLISP REPL prompt:> (load "link.lsp") > _ To make hw.lsp an executable, you will type either of the following expressions.;; Linux/BSD > (link "newlisp" "hw" "hw.lsp");; Windows > (link "newlisp.exe" "hw.exe" "hw.lsp") You can now execute hw or hw.exe from the the Linux/BSD or Windows command line respectively.> hw Hello World! Linking to a dynamic link library is likewise straight forward. (** Examples for Linux will be added here later.) On Windows platforms, the following will render an alert dialog box.(import "user32.dll" "MessageBoxA") (MessageBoxA 0 "Hello World!" "newLISP Scripting Demo" 0) Please note that MessageBoxA is C function interface in the user library of the win32 system. The example below demonstrates calling an external echo function written in C and compiled with Visual C++.// echo.c #include <STDIO.H> #define DLLEXPORT _declspec(dllexport) DLLEXPORT void echo(const char * msg) { printf(msg); } After compiling the echo.c file above into a DLL, it can be imported with the following code.(import "echo.dll" "echo") (echo "Hello newLISP scripting World!") The ease with which newLISP can link to DLLs is one feature that makes newLISP an ideal component scripting language. Be sure to check out the other examples and modules that demonstrate sockets programming, database connectivity, etc. Binding As shown previously, the set function is used to bind a value to a symbol.(set 'y 'x) In this case the value 'x, a symbol, has been bound to the variable named y. Now consider the following binding.(set y 1) Since there is no quote, y evaluates to 'x and consequently 1 is bound to the variable named x.> y x > x 1 > _ And of course y remains bound to 'x as shown above. The setq function saves you from having to write a quote each time.(setq y 1) Now the variable named y has been rebound to the value 1.> y 1 > _ The define function achieves the same thing.> (define y 2) 2 > y 2 > _ Please note that both set and setq can bind multiple associations at a time.> (set 'x 1 'y 2) 2 > (setq x 3 y 4) 4 > x 3 > y 4 > _(You should verify these examples as we go along so they stick in your memory.) Unlike setq the define function can bind only one association at a time. However there are other uses for define which will be discussed shortly. Obviously the set, setq, and define functions have side effects besides returning a value. The side effect is that an association binding the varible to a value is established in the current, implicit, symbol table. We can visualize this implicit symbol table as an association list.> '((x 1) (y 2)) ((x 1) (y 2)) > _ The association list above is a list of lists. The nested lists have two elements each, i.e. a key-value pair. The first element represents the name of the association while the last element represents its value.> (first '(x 1)) x > (last '(x 1)) 1 > _ The first element of an association list is naturally an association.> (first '((x 1) (y 2))) (x 1) > _ The built-in functions assoc and lookup are provided to facilitate working with association lists.> (assoc 'x '((x 1) (y 2) (x 3))) (x 1) > (lookup 'x '((x 1) (y 2) (x 3))) 1 > _(The lookup function has other uses as well which you can find in the newLISP documentation.) Please be sure to notice that both assoc and lookup returned the association and value respectively of the first association having the key 'x. This point will be important later on as the discussion on symbol tables and scope unfolds. List as a recursive structure Any list including an association list can be thought of as a recursive, perhaps nested, data structure. A list by definition has a first element, a tail list and a last element.> (first '(1 2 3)) 1 > (rest '(1 2 3)) (2 3) > (last '(1 2 3)) 3 But consider the following.> (rest '(1)) () > (rest '()) () > (first '()) nil > (last '()) nil The rest of a empty list or a list with only one element is again the empty list. The first and last elements of an empty list are always nil. Notice that nil never represents an empty list! Only non-existent elements are represented with nil!(Please note that the newLISP definition of a list differs from that found in Lisp and Scheme.) A list can be processed with a recursive algorithm. For example, a recursive algorithm for calculating the length of a generic list could be defined as follows.(define (list-length a-list) (if a-list (+ 1 (list-length (rest a-list))) 0)) First of all, notice that define can be used not only to define variables but also functions. The name of our function is list-length and it takes one argument namely a-list. All remaining arguments to define constitute the body of the function being defined. The names of symbols can use all sorts of characters thereby facilitating rich naming styles not found in typical mainstream langauges. Be sure to consult the newLISP documentation for the complete rules for naming symbols! The if condition interprets any value that is not nil or the empty list, i.e. '(), as being true. Thus we could have simply tested a-list instead with the same effect.(if a-list ... So long as a list has a remaining first or head element, the counting continues by adding 1 to the result of calling list-length on the rest, or tail, of the list. Since the first element of an empty list is nil, the alternative value of zero is returned and this serves as the recursive exit of the algorithm resulting in popping the stack frame of nested recursive calls to list-length. We say that a list is a recursive data structure because its definition is recursive and not simply because it is amenable to recursive processing algorithms. A recursive definition of a list would read something like this.type list ::= empty-list | first * list A list is either the empty list or a list having a first element and a tail which is itself a list. Since computing the length of a list is quite common there is a built-in library functional called length that does the job for us.> (list-length '(1 2 5)) 3 > (length '(1 2 5)) 3 > _ We'll return to our discussion of user defined functions later. The concept of an implicit symbol table can seen as succeeding expressions are evaluated.> (set 'x 1) 1 > (+ x 1) 2 > _ Thus side effects typically effect either the output stream or this implicit context. An association list is but one way to conceptually visualize this implicit symbol table. Suppose we wish now to momentarily change the binding of a variable without over-writing it permanently.> (set 'x 1 'y 2) 2 > (let ((x 3) (y 4)) (println x) (list x y)) 3 (3 4) > x 1 > y 2 > _ Notice that x and y are bound respectively to 1 and 2 in the implicit symbol table. The let expression momentarily (dynamically) rebinds x and y to 3 and 4 for the duration of the let expression. In other words, the first argument of let is an association list and the remaining arguments are executed in sequence. The list function takes a variable number of arguments that are strictly evaluated returning each resulting value in a list. The let form is similar to the begin form shown earlier except it dynamically extends the implicit symbol table momentarily for the life the "let block" which includes all the arguments of the let expression. This is possible because these arguments are lazily evaluated within the extended context of the "let block". If we visualized the implicit symbol table inside the let block it would look like the following extended association list.'((y 4) (x 3) (y 2) (x 1)) Since the lookup starts from the left the rebound values of x and y are returned thereby shadowing their original values outside of the let expression. When the let expression returns the symbol table returns to looking like the following.'((y 2) (x 1)) And consequently x and y evaluate to their original values after the let expression returns. To keep things straight, compare the following.> (begin (+ 1 1) (+ 1 2) (+ 1 3)) 4 > (list (+ 1 1) (+ 1 2) (+ 1 3)) (2 3 4) > (quote (+ 1 1) (+ 1 2) (+ 1 3)) (+ 1 1) > (quote (2 3 4)) (2 3 4) > (let () (+ 1 1) (+ 1 2) (+ 1 3)) 4 Notice quote only takes one argument. (We'll learn later how it is able to ignore additional extraneous arguments.) The let expression with no dynamic bindings defaults to behaving just like begin. Now determine what the following expressions will return (answers follow).> (setq x 3 y 4) > (let ((x 1) (y 2)) x y) ? > x ? > y ? > (setq x 3 y 4) > (begin (set 'x 1 'y 2) x y) ? > x ? > y ? Answers:> (setq x 3 y 4) > (let ((x 1) (y 2)) x y) 2 > x 3 > y 4 > (setq x 3 y 4) > (begin (set 'x 1 'y 2) x y) 2 > x 1 > y 2 Let's try something a little harder this time.> (setq x 3 y 4) > (let ((y 2)) (setq x 5 y 6) x y) ? > x ? > y ? Answer:> (setq x 3 y 4) > (let ((y 2)) (setq x 5 y 6) x y) 6 > x 5 > y 4 To visualize why the above answer is correct consider the following.'((y 2) (y 4) (x 3)) The association list above represents the symbol table upon entering the body of the let expression immediately after the extended (i.e. dynamic) binding of y. After(setq x 5 y 6) the extended symbol table would look like this:'((y 6) (y 4) (x 5)) And upon returning from the let expression it would look like this:'((y 4) (x 5)) Thus set, setq, and define rebind the symbol if it found in the symbol table or else it prefixes the new binding association onto the front of the association list. We'll return to scoping after exploring functions further. Functions User defined functions can be defined (as discussed earlier). The following function f returns the sum of its two arguments.(define (f x y) (+ x y)) This is actually short hand for any of the following.(define f (lambda (x y) (+ x y))) (setq f (lambda (x y) (+ x y))) (set 'f (lambda (x y) (+ x y))) The lambda expression defines an anonymous function, i.e. a nameless function. The first argument of the lambda expression is its formal argument list and the remaining expressions make up a delayed sequence of expressions constituting the body of the function.> (f 1 2) 3 > ((lambda (x y) (+ x y)) 1 2) 3 > _ Recall that an unquoted list is interpreted as a function call where all arguments are strictly evaluated. The first element of the list above is a lambda expression so it is evaluated returning an anonymous function which is then applied to the arguments 1 and 2. Notice that the following two expressions as essentially the same.> (let ((x 1) (y 2)) (+ x y)) 3 > ((lambda (x y) (+ x y)) 1 2) 3 > _ The only real difference is the sequence of expressions in the lambda expression are delayed until it is applied to arguments. Applying the lambda expression to arguments in effect associates a binding of the formal arguments to the actual arguments to which the function is applied. What are the values in the following expressions?> (setq x 3 y 4) > ((lambda (y) (setq x 5 y 6) (+ x y)) 1 2) ? > x ? > y ? Remember the lambda and let expressions are essentially the same.> (setq x 3 y 4) > ((lambda (y) (setq x 5 y 6) (+ x y)) 1 2) 11 > x 5 > y 4 The arguments 1 and 2 are superfluous. The formal argument y shadows the y defined outside of the lambda expression so that setting x to 5 is the only one with lasting effect after the lambda returns. Higher Order Functions Functions in Lisp are first class values. Like data they can be created at run time and passed around like any data value to effect higher order functional programming. Please note that function pointers found in C (and event listeners in Java/C#) for example are not first class functions While they may be passed around like data they never the less cannot be created like data at run time. Perhaps the most commonly used higher order function is map (sometimes called collect in object oriented (constraint) languages which got the idea originally from Lisp via Smalltalk).> (map eval '((+ 1) (+ 1 2 3) 11)) (1 6 11) > _ The map function applies the eval function to each element of the given list. Notice that the + function takes a variable number of arguments. In this case we could have simply written the following.> (list (+ 1) (+ 1 2 3) 11) (1 6 11) > _ But map can do perform more interesting operations as well.> (map string? '(1 "Hello" 2 " World!")) (nil true nil true) > _ The map function can also take more than one list argument.> (map + '(1 2 3 4) '(4 5 6 7) '(8 9 10 11)) (13 16 19 22) > _ On the first iteration + is applied to the first element of each list.> (+ 1 4 8) 13 > _ Let's say we wish to detect which elements are even.> (map (fn (x) (= 0 (% x 2))) '(1 2 3 4)) (nil true nil true) > _fn is shorthand for lambda.> (fn (x) (= 0 (% x 2))) (lambda (x) (= 0 (% x 2))) > _ The remainder operator % is used to determine whether a number is evenly divisible by 2. The filter function is another commonly used higher order function (sometimes called select in OO language libraries).> (filter (fn (x) (= 0 (% x 2))) '(1 2 3 4)) (2 4) > _ The index function can be used instead to identify the indices of the elements in the original list.> (index (fn (x) (= 0 (% x 2))) '(1 2 3 4)) (1 3) > _ The apply function is another higher order function.> (apply + '(1 2 3)) 6 > _ Why not simply write (+ 1 2 3) instead? Sometimes you may not know ahead of time which function will be applied.> (setq op +) + <40727D> > (apply op '(1 2 3)) 6 > _ This approach could be used to implement a dynamic method dispatcher, for example. lambda lists Consider the following function.> (define (f x y) (+ x y z)) (lambda (x y) (+ x y z)) > f (lambda (x y) (+ x y z)) > _ The function is a special kind of list known as a lambda list.> (first f) (x y) > (last f) (+ x y z) > _ Thus a "compiled" function can be introspected at run time. In fact it can even be changed at run time!> (setf (nth 1 f) '(+ x y z 1)) (lambda (x y) (+ x y z 1)) > _(Be sure to check up the nth-set function in the newLISP documentation also.) The expand function is useful for modifying lists in general including lambda lists.> (let ((z 2)) (expand f 'z)) (lambda (x y) (+ x y 2 1)) > _ The expand function takes a list argument and replaces the symbols within by the values of all of its remaining symbolic arguments. Dynamic Scope Consider the following function definition.> (define f (let ((x 1) (y 2)) (lambda (z) (list x y z)))) (lambda (z) (list x y z)) > _ Notice that the value of f is the lambda only.> f (lambda (z) (list x y z)) > (setq x 3 y 4 z 5) 5 > (f 1) (3 4 1) > (let ((x 5)(y 6)(z 7)) (f 1)) (5 6 1) Even though the lambda expression is defined within the lexical scope of the let expression binding x to 1 an y to 2, at the time of its invocation it's the dynamic scope that matters. We say that the binding of newLISP lambda expressions is dynamic (versus lexical binding in Common Lisp and Scheme). Any free variables of a lambda expression are bound dynamically at the time its body of expressions are evaluated. Variables not specified (bound) in the formal argument list are said to be free. We can use the expand function shown previously to close a lambda expression, i.e. bind over all free variables.> (define f (let ((x 1) (y 2)) (expand (lambda (z) (list x y z)) 'x 'y))) (lambda (z) (list 1 2 z)) > _ Notice that the lambda expression does not have any free variables now."Closing" the lambda expression with the expand function is not quite the same thing as the lexical lambda closure found in CL (Common Lisp) and Scheme, however. Lexical closures exist in newLISP and will be discussed in a later section on contexts. Function Argument Lists A newLISP function can have any number of arguments (within reason).> (define (f z , x y) (setq x 1 y 2) (list x y z)) (lambda (z , x y) (setq x 1 y 2) (list x y z)) > _ The four formal arguments of f arez , x y Notice that the comma is the name of an argument (see symbol naming rules). It is used here as a visual gimmick. The only intentional argument is z. If the number of formal arguments exceeds the number of actual arguments to which the function is applied then the remaining formal arguments are simply initialized to nil.> (f 3) (1 2 3) > _ In this case, x y are all three initialized to nil. Since x and y appear as formal arguments they act like local variables so that(setq x 1 y 2) doesn't overwrite the binding of x and y outside the scope of the lambda expression. We could have written the following instead to achieve the same effect of local variables.> (define (f z) (let ((x 1)(y 2)) (list x y z))) (lambda (z) (let ((x 1)(y 2)) (list x y z))) > _ The comma and unused formal arguments is an idiom used often in newLISP to provide local variables. A function can even be called with more actual arguments than it has specified in its formal argument list. In this case the excess arguments are simply ignored. Trailing formal arguments can thus be treated as optional arguments.(define (f z x y) (if (not x) (setq x 1)) (if (not y) (setq y 2)) (list x y z)) Now if f is called with only one argument the x and y default to 1 and 2 respectively. lambda-macro The actual arguments of a lambda-macro function are not strictly evaluated like they are for a lambda function.(define-macro (my-setq _key _value) (set _key (eval _value))) Since _key is not evaluated, it is in symbolic, i.e. quote equivalent, form already. Its _value is also symbolic and must be evaluated therefore.> (my-setq key 1) 1 > key 1 > _ The underscores are used to prevent variable capture. Consider the following.> (my-setq _key 1) 1 > _key nil > _ What happened? The statement(set _key 1) merely set the _key local variable. We say the _key variable was captured by the macro's "expansion." Scheme has "hygenic" macros that are "clean" in that they are guaranteed to prevent variable capture. Usually the leading underscore character used in the macro's formal arguments is sufficient to prevent variable capture however. The define-macro function is shorthand for binding a lambda-macro expression in one step.(define my-setq (lambda-macro (_key _value) (set _key (eval _value)))) The definition above is equivalent to the previous definition of my-setq. Besides lazy evaluation, lambda-macro's provide for a variable number of arguments.(define-macro (my-setq ) (eval (cons 'setq (args)))) The cons function prefixes a list with a new first element.> (cons 1 '(2 3)) (1 2 3) > _ The definition of my-setq is now a more complete implementation allowing for multiple bindings.> (my-setq x 10 y 11) 11 > x 10 > y 11 > _ The (args) function call returns the list all the arguments to the lambda-macro, i.e. unevaluated. Thus the my-setq macro first constructs the symbolic expression shown below.'(setq x 10 y 11) This expression is then evaluated. The main purpose of macros is to extend the syntax of the language however. Suppose we want to introduce repeat until flow control as a syntax extension to the language.(repeat-until condition body ...) The following macro achieves this.(define-macro (repeat-until _condition ) (let ((body (cons 'begin (rest (args))))) (eval (expand (cons 'begin (list body '(while (not _condition) body))) 'body '_condition)))) Using repeat-until:(setq i 0) (repeat-until (> i 5) (println i) (inc i)) ; => 0 1 2 3 4 5 Macros can become quite complex quite quickly. One trick for validating them is to replace eval with list or println to inspect what the expansion looks like just before it is evaluated.(define-macro (repeat-until _condition ) (let ((body (cons 'begin (rest (args))))) (list (expand (cons 'begin (list body '(while _condition body))) 'body '_condition)))) Now we can check what the expansion looks like.> (repeat-until (> i 5) (println i) (inc i)) ((begin (begin (println i) (inc i)) (while (> i 5) (begin (println i) (inc i))))) > _ Contexts Upon startup the default context is MAIN.> (context) MAIN A context is a name space.> (setq x 1) 1 > x 1 > MAIN:x 1 > _ A context variable can be used to fully qualify a variable name. MAIN:x refers to the variable x in context MAIN. To create a new name space use the context function.> (context 'FOO) FOO FOO> _ The statement above creates the namespace FOO, if it doesn't already exist, and switches to it. The prompt tells you the current namespace if it is other than MAIN. Use the context? predicate to determine whether a variable is bound to a context.FOO> (context? FOO) true FOO> (context? MAIN) true FOO> (context? z) nil FOO> _ The set, setq, and define functions bind associations in the current context, i.e. namespace.FOO> (setq x 2) 2 FOO> x 2 FOO> FOO:x 2 FOO> MAIN:x 1 FOO> _ A fully qualified name, e.g. FOO:x, is not required to specify a variable when it is bound in the current context. To switch back to the MAIN (or any other) context use either the variable MAIN or the symbol 'MAIN.FOO> (context MAIN) > _ orFOO> (context 'MAIN) > _ The only time you must use the quote is for creating new contexts. Contexts cannot be nested—they all reside at the top level. Notice in the example below that the name y, which is defined in MAIN, is not known in context FOO.> (setq y 3) 3 > (context FOO) FOO FOO> y nil FOO> MAIN:y 3 FOO> _ The next example shows that MAIN is not special in any way other than being the default context. MAIN does not know about z for example.FOO> (setq z 4) 4 FOO> (context MAIN) MAIN > z nil > FOO:z 4 All the built-in names reside in a special global section of the MAIN context.> println println <409040>> (context FOO) FOO FOO> println println <409040> The println built-in function is known in both the MAIN and FOO contexts. The println function has been "exported" to global status. The sequence of expressions below shows that MAIN:t is not known initially within contexts FOO or BAR until it has been elevated to global status.FOO> (context MAIN) MAIN > (setq t 5) 5 > (context 'BAR) BAR BAR> t nil BAR> (context FOO) FOO FOO> t nil FOO> (context MAIN) MAIN > (global 't) t > (context FOO) FOO FOO> t 5 FOO> (context BAR) BAR BAR> t 5 Only names in MAIN can be elevated to global status. Lexical Scope The set, setq, and define functions bind names in the current context.> (context 'F) F F> (setq x 1 y 2) 2 F> (symbols) (x y) F> _ Notice that the symbols function returns the names of symbols bound in the current context.F> (define (id z) z ) (lambda (z) z) F> (symbols) (id x y z) F> _ The lexical scope of the current context continues until the next context switch. Since you can later switch back to a particular context its lexical scope can be augmented and may appear fragmented in the source file(s).F> (context 'B) B B> (setq a 1 b 2) 2 B> By lexical scope, we mean the scope as defined by the source code. The names x and y occur in the lexical scope of context F while the names a and b occur within the lexical scope of context B. All lambda expressions are lexically scoped in the context in which they are defined. Consequently lambda expressions are ultimately "closed" by the context. The lambda expression below occurs in the lexical scope of MAIN and also in the lexical scope of the (let ((x 3)) ...) expression.> (setq x 1 y 2) 2 > (define foo (let ((x 3)) (lambda () (list x y)))) (lambda () (list x y)) > (foo) (1 2) > _ Recall that lambda invocations in general are dynamically scoped. While this is true notice that this lambda invocation is ultimately "closed" by the lexical scope of the MAIN context and not the let expression. Continuing with the last example we can see this hybrid lexical / dynamic scoping at work.> (let ((x 4)) (foo)) (4 2) > _ The lexical scoped context is dynamically extended during the execution of the let expression this time so that (foo) is invoked in the dynamic scope of the let expression. What will happen if we invoke (foo) in an alien context?> (context 'FOO) FOO FOO> (let ((x 5)) (MAIN:foo)) ? Think about this for a moment. The let expression above dynamically extends the lexical scope of FOO instead of MAIN.FOO> (let ((x 5)) (MAIN:foo)) (1 2) FOO> _ What happened? MAIN:foo's dynamic scope includes only the scope of the MAIN context possibly dynamically extended. Since the let expression extends the dynamic scope of FOO the invocation of MAIN:foo doesn't see the FOO:x => 5 binding. The following expression is revealing.FOO> MAIN:foo (lambda () (list MAIN:x MAIN:y)) FOO> _ When we introspected foo in the MAIN context we didn't see the default MAIN qualifier.> foo (lambda () (list x y)) > _ So even though the FOO context was dynamically extended with the FOO:x => 5 binding, we can now see that when MAIN:foo is executing it confines its lookup to the MAIN (possibly dynamically extended) context only. What would be the value of the following expression?FOO> (let ((MAIN:x 5)) (MAIN:foo)) ? If you answered the following, you are correct.FOO> (let ((MAIN:x 5)) (MAIN:foo)) (5 2) FOO> _ We say that the context, or namespace, is the lexical closure of all functions defined within that context. Understanding how newLISP translates and evaluates source code is vital to your understanding of contexts. Each top level expression is first translated and then evaluated in order by newLISP before stepping forward to the next top level expression. During the translation phase all (unqualified) symbols are understood to be bound in the current context. Thus the context expression is merely a directive to switch (or create and switch) to the indicated context. This has important ramifications as we'll see momentarily.(context 'FOO) (setq r 1 s 2) Each of the expressions above are top level expressions, despite the suggestive indentation. The first expression is translated in the current context. Thus FOO becomes a symbol bound in the current context (i.e. MAIN if it isn't already) before the translated expression is actually evaluated. Once the translated expression is evalauted, the context switch takes place which can be clearly seen when operating in the interpreter mode.> (context 'FOO) FOO> So by the time newLISP gets around to interpretingFOO> (setq r 1 s 2) the current context is now FOO. Now consider the following code snippet> (begin (context 'FOO) (setq z 5)) FOO> z nil FOO> MAIN:z 5 FOO> _ What happened? First the single top level expression(begin (context 'FOO) (setq z 5)) was translated in the MAIN context. Thus z is taken be:(setq MAIN:z 5) As the translated begin compound expression begins to be evaluated first the context is switched, but then the MAIN:z variable is set to 5. Upon returning from the compound expression, the context remains switched to FOO. It helps to keep things straight by thinking about the source code in its two phases, i.e. translation and execution especially when dealing with contexts. Contexts can be used to organize data and/or functions as records or structures, classes, and modules.(context 'POINT) (setq x 0 y 0) (context MAIN) The POINT context shown above can be thought of a structure having two fields (or slots).> POINT:x 0 > _ But contexts can also be cloned, thus serving as a simple class or prototype. The new function as shown below creates a new context called p if it doesn't already exist and then merges a clone of the bindings found in POINT.> (new POINT 'p) p > p:x 0 > (setq p:x 1) 1 > p:x 1 > POINT:x 0 The sequence of expressions above shows that context p is a distinct and separate copy of POINT. The following example shows how contexts could be used to provide a simple structure inheritance mechanism.(context 'POINT) (setq x 0 y 0) (context MAIN) (context 'CIRCLE) (new POINT CIRCLE) (setq radius 1) (context MAIN) (context 'RECTANGLE) (new POINT RECTANGLE) (setq width 1 height 1) (context MAIN) Notice how the new merges the x and y fields of POINT into CIRCLE which adds an additional field called radius. RECTANGLE "inherits" from POINT in a similar fashion. The def-make macro below allows us to define named instances of a context and optionally specify initializers.(define-macro (def-make _name _ctx ) (let ((ctx (new (eval _ctx) _name)) (kw-args (rest (rest (args))))) (while kw-args (let ((slot (pop kw-args)) (val (eval (pop kw-args)))) (set (symbol (name slot) ctx) val))) ctx)) For example we could instantiate a RECTANGLE named r and override the default values for x and height with the following expression.(def-make r RECTANGLE x 2 height 2) The following function will convert a context "instance" to a string.(define (context->string _ctx) (let ((str (list (format "#S(%s" (string _ctx))))) (dotree (slot _ctx) (push (format " %s:%s" (name slot) (string (eval (symbol (name slot) _ctx)))) str -1)) (push ")" str -1) (join str))) Now we can verify the contents of r.> (context->string r) "#S(r height:2 width:1 x:2 y:0)" > _ Notice how various characters such as "->" can be used in identifier names. You know enough about newLISP now to decypher the def-make and context->string definitions above. Be sure to look up in the regular newLISP documentation any primitive operations such as dotree, push, join, etc. that are not familiar to you. Both Common Lisp and Scheme have lexically scoped functions meaning that a closure is exclusive to a particular function. Functions in newLISP can share a lexical closure, i.e. context, which is similar to an object whose methods share a common state. The context examples shown thus far could have included functions as well. The newLISP documentation gives several examples of using contexts as simple objects.
http://www.newlisp.org/newLISP_in_21_minutes.html
CC-MAIN-2015-22
refinedweb
7,117
63.49
Hi Gurus, I'm trying to import my yesterday's production DB on another machine for some testing purpose. I created a clone of my production DB, but with a block size of 4KB unlike as production 8KB. My OS is Linux 7.2 and oracle 9.0.1.4.0 . Import process is starting and at after creating 4 tables, its kicking out saying "Segmentation fault (core dumped)". I set all the Shared memory parameters and all. here are my shared memory parameter values.. [root@cmsprod3 kernel]# cat sem 250 32000 32 128 shmmax 1000000000 shmmni 4096 shmall 2097152 Please help me in solving this problem. Thanks in advance. PNRDBA Imp w/ analyze=n That's a bug that was supposed to be fixed in 9.0.1 "I do not fear computers. I fear the lack of them." Isaac Asimov Oracle Scirpts DBA's need Hi Ken, You mean to say, import with analyze=n?? Thanks Correct. or, you could re-export with statistics=n ken, Getting the same error again even after using analyze=N option. Import: Release 9.0.1.4.0 - Production on Tue Feb 18 17:47:44 2003 Connected to: Oracle9i Enterprise Edition Release 9.0.1.4.0 - Production With the Partitioning option JServer Release 9.0.1.4.0 - Production Export file created by EXPORT:V09.00.01 via conventional path import done in US7ASCII character set and AL16UTF16 NCHAR character set IMP-00046: using FILESIZE value from export file of 2097152000 . importing CMS's objects into CMS . . importing table "ACTION_TEMP" 14392 rows imported . . importing table "ALLINAUB92" 0 rows imported . . importing table "ALLINAUB92D" 0 rows imported . . importing table "AUTO_POSTING_HANDLE" 23 rows imported . . importing table "A_ASSIGNMENTHISTORY"Segmentation fault (core dumped) Type "ulimit -a" and post the results. [oracle@cmsprod3 oracle]$ ulimit -a 81919 virtual memory (kbytes) unlimited [oracle@cmsprod3 oracle]$ That looks good. Are the NLS_LANG's the same? Is this something you do routinely and it just failed today? Ken, I think the max user processes are very less, bcoz the same value for this in my prod DB is .. max user processes 196608 Will this effect? if yes, how can i change this value to the required one? Thanks No, its of some thing like one time job, but when i imported the same DB on some other 2 more machines, with same OS , every thing same, it went fine, but not on this Box. Can you please throw some light on this. B'coz, i need to prepare this today and make it ready for my developers. Many Thanks in advance Forum Rules
http://www.dbasupport.com/forums/showthread.php?33988-Segmentation-fault-(Core-dumped)&p=144482
CC-MAIN-2015-06
refinedweb
434
68.57
Up to [DragonFly] / src / sys / vfs / isofs / cd9660> VFS messaging/interfacing work stage 2/99. This stage retools the vnode ops vector dispatch, making the vop_ops a per-mount structure rather then a per-filesystem structure. Filesystem mount code, typically in blah_vfsops.c, must now register various vop_ops pointers in the struct mount to compile its VOP operations set. This change will allow us to begin adding per-mount hooks to VFSes to support things like kernel-level journaling, various forms of cache coherency management, and so forth. In addition, the vop_*() calls now require a struct vop_ops pointer as the first argument instead of a vnode pointer (note: in this commit the VOP_*() macros currently just pull the vop_ops pointer from the vnode in order to call the vop_*() procedures). This change is intended to allow us to divorce ourselves from the requirement that a vnode pointer always be part of a VOP call. In particular, this will allow namespace based routines such as remove(), mkdir(), stat(), and so forth to pass namecache pointers rather then locked vnodes and is a very important precursor to the goal of using the namecache for namespace locking. VFS messaging/interfacing work stage 1/99. This stage replaces the old dynamic VFS descriptor and inlined wrapper mess with a fixed structure and fixed procedural wrappers. Most of the work is straightforward except for vfs_init, which was basically rewritten (and greatly simplified). It is my intention to make the vop_*() call wrappers eventually handle range locking and cache coherency issues as well as implementing the direct call -> messaging interface layer. The call wrappers will also API translation as we shift the APIs over to new, more powerful mechanisms in order to allow the work to be incrementally committed. This is the first stage of what is likely to be a huge number of stages to modernize the VFS subsystem. __P()!=wanted, remove old style prototypes from the vfs subtree
http://www.dragonflybsd.org/cvsweb/src/sys/vfs/isofs/cd9660/iso.h
CC-MAIN-2014-41
refinedweb
325
58.62
Overview Last week I wrote an article about the pexpect module in Python and how you can use it to take care of some of the automation needs, like ssh and ftp. I would like to continue on that topic and write about it's pxssh class. With the pxssh module, it's easy to access other servers over SSH. This article is based on the official documentation found here: What is pxssh? Pxssh is based on pexpect. It's class extends pexpect.spawn to specialize setting up SSH connections. I use pxssh frequently for making ssh connections in python. Module documentation Open up a terminal and type in the following commands to get help about the module import pxssh help(pxssh) Help on module pxssh: NAME pxssh FILE /usr/lib/python2.7/dist-packages/pxssh.py DESCRIPTION This class extends pexpect.spawn to specialize setting up SSH connections. This adds methods for login, logout, and expecting the shell prompt. $Id: pxssh.py 513 2008-02-09 18:26:13Z noah $ CLASSES pexpect.ExceptionPexpect(exceptions.Exception) ExceptionPxssh pexpect.spawn(__builtin__.object) pxssh You can also see the help here Methods and login process Pxssh adds methods for login, logout, and expecting the shell prompt. It does various tricky things to handle many situations in the SSH login process. For example, if the session is your first login, then pxssh automatically accepts the remote certificate; or if you have public key authentication setup then pxssh won't wait for the password prompt. How does pxssh works? pxssh uses the shell prompt to synchronize output from the remote host. In order to make this more robust it sets the shell prompt to something more unique than just $ or #. This should work on most Borne/Bash or Csh style shells. Example This example runs a few commands on a remote server and prints the result. First we import the modules that we need. (pxssh and getpass) We import the getpass module, which will prompt the user for a password, without echoing what they type to the console. import pxssh import getpass try: s = pxssh.pxssh() hostname = raw_input('hostname: ') username = raw_input('username: ') password = getpass.getpass('password: ') s.login (hostname, username, password) s.sendline ('uptime') # run a command s.prompt() # match the prompt print s.before # print everything before the prompt. s.sendline ('ls -l') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.logout() except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e) Run a command on a remote SSH server Let's show one more example. To run a command ('uptime') ('uptime') s.prompt() # match the prompt print s.before # print everything before the prompt. s.logout() #We can also execute multiple command like this: s.sendline ('uptime;df -h') For more information about pxssh,:
https://www.pythonforbeginners.com/code-snippets-source-code/ssh-connection-with-python
CC-MAIN-2020-16
refinedweb
470
69.79
Sample problem: I’ve written this test code: class MyProgram { int count = 0; public static void main(String[] args) { System.out.println(count); } } But it gives the following error: Main.java:6: error: non-static variable count cannot be referenced from a static context System.out.println(count); ^ How do I get my methods to recognize my class variables? Non-static variable cannot be referenced from a static context – Answer #1: ou must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it’s a car even if you can’t see which model or type. This is because you compare what you see with the class “car”. The class contains which is similar to all cars. Think of it as a template or an idea. At the same time, the car you see is an instance of the class “car” since it has all the properties which you expect: There is someone driving it, it has an engine, wheels. So the class says “all cars have a color” and the instance says “this specific car is red”. In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static. Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it’s usually constants (like car types, i.e. something where you have a limited set which doesn’t change often). To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don’t want). In your case, try this code as a starting block: public static void main (String[] args) { try { MyProgram7 obj = new MyProgram7 (); obj.run (args); } catch (Exception e) { e.printStackTrace (); } } // instance variables here public void run (String[] args) throws Exception { // put your code here } The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method ( run()). Answer #2: Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a ‘normal’ (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields. The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then: class Programm { public static void main(String[] args) { Programm programm = new Programm(); programm.start(); } public void start() { // can now access non-static fields } } Answer #3: The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator. The lifecycle of a class, in broad terms, is: - the source code for the class is written creating a template or pattern or stamp which can then be used to - create an object with the newoperator using the class to make an instance of the class as an actual object and then when done with the object - destroy the object reclaiming the resources it is holding such as memory during garbage collection. In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available. The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method. So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded. However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error. import java.io.*; class HelloWorld { int myInt; // this is a class variable that is unique to each object static int myInt2; // this is a class variable shared by all objects of this class static void main (String [] args) { // this is the main entry point for this Java application System.out.println ("Hello, World\n"); myInt2 = 14; // able to access the static int HelloWorld myWorld = new HelloWorld(); myWorld.myInt = 32; // able to access non-static through an object } } Answer #4: Let’s analyze your program first.. In your program, your first method is main(), and keep it in mind it is the static method… Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can’t use those variables outside that method. This is the basic error u made. Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing. *Static method calls only the static method and use only the static variable. *Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class) *Because of this you call it as a class variable or a class method. And a lot more is there about the “static” keyword. I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods). And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that. Non-static variable cannot be referenced from a static context- Answer #5: To be able to access them from your static methods they need to be static member variables, like this: public class MyProgram7 { static Scanner scan = new Scanner(System.in); static int compareCount = 0; static int low = 0; static int high = 0; static int mid = 0; static int key = 0; static Scanner temp; static int[]list; static String menu, outputString; static int option = 1; static boolean found = false; public static void main (String[]args) throws IOException { ... Answer #6: Now you can add/use instances with in the method public class Myprogram7 { Scanner scan; int compareCount = 0; int low = 0; int high = 0; int mid = 0; int key = 0; Scanner temp; int[]list; String menu, outputString; int option = 1; boolean found = false; private void readLine() { } private void findkey() { } private void printCount() { } public static void main(String[] args){ Myprogram7 myprg=new Myprogram7(); myprg.readLine(); myprg.findkey(); myprg.printCount(); } } Hope you learned something from this post. Follow Programming Articles for more!
https://programming-articles.com/non-static-variable-cannot-be-referenced-from-a-static-context-java-answered/
CC-MAIN-2022-40
refinedweb
1,520
68.3
Opened 10 years ago Closed 3 years ago #3111 closed New feature (wontfix) newforms: Add as_tr(), as_li() methods to BoundField Description A great function to add to fields would be "as_tr()" and "as_li()", it would render just one row of the form table, as well as the corresponding error if needed. It's very useful when you want to specially define the layout of a specific field, but you want the rest to be default. Otherwise if you want to define just one field, then you have to define them all. Change History (18) comment:1 Changed 10 years ago by comment:2 Changed 10 years ago by Yes, that would be ideal. Especially since you could over-ride the as_tr() method on your class, and then not have to change the as_table() method. comment:3 Changed 10 years ago by But you couldn't override as_tr() on your field class, because as_tr() would be on BoundField, not on Field... comment:4 Changed 10 years ago by To implement this, we'd have to add an as_tr() hook to Widget, not BoundField, because client code never deals with BoundField classes directly. The basic Widget.as_tr() method would look something like this: def as_tr(self, label, rendered): # 'rendered' is the result of widget.render() return u'<tr><th>%s</th><td>%s</td></tr>' % (label, rendered) Then Form.as_table() would call this, and we'd have to add as_p() and as_li() methods to Widget to mirror as_p() and as_ul() on the Form. Would it be worth it? comment:5 Changed 10 years ago by comment:6 Changed 10 years ago by I certainly think it would. The flexibility this adds is quite remarkable once you start using it. comment:7 Changed 10 years ago by I'd personally be -1 on this; the use case presented is custom presentation, and default methods are never going to be able to handle the entire slippery slope of one-off custom cases people will want, so I'd say the solution is to just do the form presentation yourself in the template, or override a form-level method like as_table to omit the single field you want to present specially. comment:8 Changed 9 years ago by If it's good enough for Adrian, it's good enough for me :) comment:9 Changed 9 years ago by Ubernostrum, you cad! Of course it's not going to be able to handle the entire slippery slope, but this cuts it in half and handles much of it. It's really a pain when you have a long form and need to customize just one field. This makes it much simpler, and is an elegant solution. comment:10 Changed 9 years ago by comment:11 Changed 9 years ago by These can also make simple helper methods for the as_ul() and as_table() methods. comment:12 Changed 9 years ago by comment:13 Changed 8 years ago by Milestone post-1.0 deleted comment:14 Changed 6 years ago by comment:15 Changed 6 years ago by comment:16 Changed 5 years ago by Is django really going to have even more html generated in python? comment:17 Changed 3 years ago by I agree with @kmike, HTML in python is technical debt that we should fix, adding more as_method() feels counterproductive. This is an 8 years old ticket, I propose we close it, any objections? Good idea! Ideally we'd reuse some of the HTML generation in Form.as_ul()and Form.as_table(), but I'm not sure whether that can be done elegantly.
https://code.djangoproject.com/ticket/3111
CC-MAIN-2017-22
refinedweb
597
66.98
A callable plist data structure for Emacs Posted April 16, 2017 at 04:44 PM | categories: elisp, macro, emacs | tags: | View Comments Updated April 21, 2017 at 08:01 PM Table of Contents Emacs lisp has a few data structures that store key-value pairs. Here are some canonical examples of these data structures and the way to get data out of them. - a-lists (let ((data '((key1 . 4) (key2 . "tree")))) (cdr (assoc 'key2 data))) - p-lists (let ((data '(:key1 4 :key2 "tree"))) (plist-get data :key2)) - A hash table (let ((data #s(hash-table data (key1 4 key2 "tree")))) (gethash 'key2 data)) Each of these uses some function to get data out of them. I have been learning about closures today, and realized a way you can make a "callable" data structure using them. In a closure, the data is stored as part of a function. We will use a "let over lambda" with a defalias in a lexical environment to achieve this. I will wrap a p-list with this approach, but it could work with any of the examples above. We will make the function have a few behaviors that allow us to see the whole data structure with no args, to get a value with one arg that is a key, and to set a value if there are more than two args add them as key-val pairs to the data structure. This block binds the function to the symbol "d" which is then a callable function. (let ((data '(:key1 4 :key2 "tree"))) (defalias 'd (lambda (&rest key-vals) (cond ;; no args, return data ((= 0 (length key-vals)) data) ;; just a key, get val ((= 1 (length key-vals)) (plist-get data (car key-vals))) (t (loop for key in (-slice key-vals 0 nil 2) for val in (-slice key-vals 1 nil 2) do (plist-put data key val)) data))))) Now we can use it like to get some data out: (d :key2) And add new values like: (d :key3 "oak") You can update a value with this too: (d :key3 "pine") or add multiple values like this: (d :key4 0 :key5 9) And see the whole plist with no args: (d) Pretty nice! It seems like there ought to be a macro to facilitate creating those. Here is one. This macro basically expands to the same code as above, but for fun I add a default value option. (defmacro default-dict (var &optional default &rest key-vals) "Bind a callable plist to VAR that contains KEY-VALS." (let () `(let ((data ',key-vals)) (defalias ',var (lambda (&rest key-vals) (message "%s" key-vals) (cond ;; no args, return data ((= 0 (length key-vals)) data) ;; just a key, get val ((= 1 (length key-vals)) (or (plist-get data (car key-vals)) ,default)) (t (loop for key in (-slice key-vals 0 nil 2) for val in (-slice key-vals 1 nil 2) do (plist-put data key val)) data))))))) Here is an instance of it. (default-dict d2 "None" :key1 4 :key2 "tree") And here it is in use. (d2 :key1) (d2 :new-key) Not bad. If you come from Python, you might find this style of data structure to be more similar to what you are used to seeing. It sure seems less verbose than the usual plist boilerplate I have used before. 1 An update One (perhaps undesirable even) feature of the approach above is that it creates a function in the global namespace. This might have unintended consequences with name clashes or shadowing, and if you later use the same variable name for a plist, you would change the function behavior. Here we consider a way to limit the scope of where these functions exist and work. The labels macro provides one way to do this, we just create temporary functions that only exist within a scope. There is a lot of backticking and comma operators in this, and it took quite a few iterations to get it working! This macro creates temporary functions for each keyword that return the value in the plist. (defmacro with-dict (key-vals &rest body) "A context-manager for a plist where each key is a callable function that returns the value." (declare (indent 1)) (let* ((g (if (symbolp key-vals) (symbol-value key-vals) key-vals)) (keys (-slice g 0 nil 2))) `(labels ,(loop for key in keys collect (list key '() `(plist-get ',g ,key))) ,@body))) Here is how we use it: (with-dict (:a 1 :b 'some-symbol :c 3) (:b)) We can also use it with variables that hold mappings like this. (let ((d '(:key1 1 :key2 some-other-symbol :key3 3))) (with-dict d (format "We got %s" (:key2)))) That is pretty interesting! In case that looks similar to a context manager in Python, now you know where Python got that idea ;) Another related idea is to let-bind the values to variables withing a scope. We can't use the keywords directly here, so I use some hackery to strip off the colon so it is a regular symbol. That is not quite as nice I guess since you have to remember to remove the : from the symbols in the body of your code. (defmacro with-plist-vals (plist &rest body) "Bind the values of a plist to variables with the name of the keys." (declare (indent 1)) `(let ,(loop for key in (-slice plist 0 nil 2) for val in (-slice plist 1 nil 2) collect (list (intern (substring (symbol-name key) 1)) val)) ,@body)) Here is an example usage. (with-plist-vals (:a 4 :b 6) (* 2 a)) Obviously that is just an alternate syntax for the let statement, but it lets you leverage the plist syntax for multiple purposes. Copyright (C) 2017 by John Kitchin. See the License for information about copying. Org-mode version = 9.0.5
http://kitchingroup.cheme.cmu.edu/blog/2017/04/16/A-callable-plist-data-structure-for-Emacs/
CC-MAIN-2017-39
refinedweb
979
72.19
.NET Framework 2.0 breaks: The sky is (not really) falling Reports of compatibility issues between .Net Framework 1.1 and the beta 2.0 aren't as drastic as they were first reported to be -- especially for smart developers. A week or two back Microsoft released some information on compatibility between the .NET Framework 1.1 and the current beta version of the .NET Framework 2.0. This document uses scary words like "breaking changes" and was seized on immediately by some parts of the computer press as an excuse to write headlines along the lines of ".NET 2.0 Breaks Existing Applications." It's always easy to go for the cheap shot against Microsoft, especially when you're on a deadline. But the real story is a good deal more interesting - and better for developers. First, if you actually read the document, you'll find that there are only a few edge cases where an existing 1.1 application can actually fail due to a 2.0 breaking change. The most important of these is that if a 1.1 application is run on a computer with only the 2.0 Framework installed, it will run with the 2.0 Framework. The easy mitigation: make sure you install the 1.1 Framework with your 1.1 application, and configure the application to request the 1.1 Framework, which avoids the problem in all cases. So, the time to be concerned is when you're migrating 1.1 code to 2.0. If you're a smart developer -- and you are, right? -- you're not going to migrate without testing your code. In this case, Microsoft's publication of the list of changes helps you, by giving you a list of things to look for. In fact, it's an incredibly detailed list; there's an entire help file you can download that exhaustively details every breaking change of which the team is aware, no matter how trivial. As a random example, here's one breaking change from the System.Windows.Forms namespace: "In previous versions of the Framework, when a user set up a form with a RadioButton group and no radio button was selected, the first radio button in the group would become selected. Now, an item is only selected if the user presses the space bar or one of the arrow keys when focus is in the radio button group. The .NET Framework 2.0 behavior now matches that of standard Windows dialogs and Web pages." There are not likely to be many applications out there that depend on the (non-standard) behavior of the .NET 1.1 Framework in this area. But armed with the list of changes, it's pretty easy to inspect all of the radio button groups on your application and to take corrective action if yours is one of them. Most of the breaking changes are of a similarly trivial level. There are some for which there's no way to get back to the previous behavior: these are generally corrections to conform with external standards (The ISO tag in System.Globalization for Kyrgyzstan was updated from KZ to KY) or fixes to security holes in the Framework where the previous behavior was dangerous. But for the most part, the story here is this: the .NET team has gone out of their way to make your life easier if you're a developer upgrading a .NET 1.1 application to run on .NET 2.0. The increased transparency we've seen throughout the .NET 2.0 beta cycle is being translated into continued transparency as the product nears release, with practical guidance from Microsoft on all aspects of .NET development. And rather than a dastardly plan to break applications, that's actually a good
https://searchwindevelopment.techtarget.com/news/1094760/NET-Framework-20-breaks-The-sky-is-not-really-falling
CC-MAIN-2019-47
refinedweb
633
66.84
Learn Java in a day Learn Java in a day  ... structure. Initially learn to develop a class in java. To meet this purpose the calendar and using the Date class, we have got the date of that day. Example... to date or subtract days from date) for java applications. Anyone can learn Java in 21 days, all they need is dedication and concentration. Java Guide at RoseIndia can help you learn Java in 21 days. The course... of the class, method, keyword, function and other important parts of a Java learn learn how to input value in java How we learn java How we learn java what is class in java? what is object in java? what is interface in java and use? what is inheritence and its type Find the Day of the Week Find the Day of the Week This example finds the specified date of an year and a day of a week from calendar. The Calendar class is an abstract base class that extends  ... by the Java compiler into byte code that are stored in .class file. The JVM..., TextPad etc. Java program is a class with a main method in it. The main method Class Class, Object and Methods Class : Whatever we can see in this world all the things... is termed as a class. All the objects are direct interacted with its class How to learn Java easily? If you are wondering how to learn Java easily, well its simple, learn... Java learning. The students opting to learn Java are of two types, either... a simple language and easy way to understand and learn the language. Java on its Best way to learn Java Best way to learn Java is through online learning because you can learn it from the comfort of your home. Online learning of Java is also free, the only..., explaining Java features, Java keywords, methods, class and how to use them How to learn Java? to learn Java language than there are two ways you can do that. One is the classroom... training. A young developer who is seeking a career in Java can learn the language..., class, function, method, keyword, etc. there is to learn. Every topic can a class in java How to create a class in java I am a beginner in programming and tried to learn how to do programming in Java. Friends please explain how can I create a class in Java Java Date Class Java Date Class Hi Friend, I need to have a code to get the days..., the days would be saturday, sunday and monday, the code I gave simply get one day... class DateClassExample { public static void main(String[] args) { Scanner Learn Java online can learn at his/her pace. Learning Java online is not difficult because every... and web-applications. JRE includes JVM (Java Virtual Machine) Java class library...Learning Java is now as easy as never before. Many websites today class Java class What is the purpose of the Runtime class Learn Java in 24 hours you understand the concepts behind Java class, method, keyword, function, etc... find it easy to understand the example. To learn Java in 24 hours, you must clear... systems. Java is based on class, method and objects. What is programming How to learn programming free? , Here are the tutorials: Beginners Java Tutorial Learn Java in a day Master Java...How to learn programming free? Is there any tutorial for learning Java absolutely free? Thanks Hi, There are many tutorials on Java Class in Java Class in Java In this section, we will discuss about java classes and its structure. First of all learn: what is a class in java and then move on to its Java Class Question? Java Class Question? Write an application that prompts the user... the user enters a selection. Create a class named TVShow.java. Data Fields can include a String containing the Name of the show, a String containing the day Online Java Training their online class. Learn online Java programming training ensures that students...Learn Online Java Training It would be safe to say that the advancements... of the advancements in Java online Training. It has thus become exceedingly java class - Getting Previous, Current and Next Day Date Getting Previous, Current and Next Day Date In this section, you will learn how to get previous, current and next date in java. The java util package provides How to Learn Java , how to learn Java? Learning Java is not that difficult just the right start is needed. The best way to learn Java today without spending money in through... or twice. If you are opting to learn Java online the only thing required Marvellous chance to learn java from the Java Experts Marvellous chance to learn java from the Java Experts A foundation course on Java technology which... for Software Development on Java Platform. Learn to implement java class - Java Beginners java class Define a class product with the following data members 1.Product number int(Auto generated) 2.Product name char [20] 3.Price float... program to execute the above class ad functions for 5 products Get Class Location Java Get Class Location In this section, you will learn how to get the class location. For this, we have used the classes URL and ClassLoader. The class java Class - Java Beginners java Class Can anyone please explain what this code means? import java.util.TreeMap; import java.util.Iterator; //Please tell me what this class declaration means???????????? public class ST, Val> implements Iterable Java Class Size Java Class Size How to determine size of java class java class - Java Beginners java class hi sir, i have to compile two classes(eg:controller.java and client.java) and i have imported some packages in it using jar files(like Activation.jar and servlet.jar) when ever i am running in command promt Learn Java for beginners Beginners can learn Java online though the complete Java courses provided at Roseindia for free. This Java course covers the whole of Java programming... a programmer from basic to advance level of Java. New programmers prefer to learn Java Class class. Now we will learn, how to define a class having methods, objects... C:\roseindia>java Classtest It's a example of class... class method in java class method in java How to write a class method in Java? You must read Java - Class, Object and Methods in Java Java adapter class Java adapter class What is adapter class Java dictionary class Java dictionary class What is the Dictionary class JDBC batch insert using Java bean class In this tutorial, you will learn about JDBC batch insert using java bean / model class Java inner class Java inner class What are inner class and anonymous class Java abstract class Java abstract class Can an abstract class be final Java file class Java file class What is the purpose of the File class Java System class Java System class What is the purpose of the System class java Math class java Math class Why are the methods of the Math class static Java math class Java math class Can you instantiate the Math class abstact class - Java Beginners abstact class write a java program to implement an animal abstact class java installing - Java Beginners :// Hope...java installing HI sir.... can any tell me in detail that how can I download java software and install in my system(windows vista 2007 java inner class - Java Beginners java inner class What is the difference between the nested class and inner class? Explain with suitable example. Hi Friend, Differences: 1)Nested class is declared inside another class with the static keyword java anonymous class java anonymous class Can an anonymous class be declared as implementing an interface and extending a class Void class in Java - Java Beginners Void class in Java Hi, What is the purpose of Void class? Thanks Hi Friend, It is an uninstantiable class that hold a reference to the Class object representing the primitive Java type void. Thanks Learn Java Programming in it, Learn Java programming online with tutorials and simple examples... of the programmer wants to learn this language quickly. The basic of Java tutorials... knowledge of these languages then it will be comparatively easy for you to learn java.util.*; import java.io.*; public class AGECALC { public static void main(String[] args) throws IOException { int day = 1, month = 0... day of your date of birth : "); day = Integer.parseInt Servlet tutorials: Learn Servlet Easily Servlet is a Java programming language class, which helps to improve server... applications, without the performance limitations of CGI programs. Moreover, Java... and stays in memory. Java applet makes the tasks to be performed faster Java component class Java component class Which method of the Component class is used to set the position and size of a component with out class - Java Beginners with out class can we write a program with out a class in core java?if yes,give example Java Online Class and professional we offers java online class so that they can learn the language from...Java Online Class The advent of e-learning has made learning fun, as students... a recompile. Among other features that make java online class convenient is, its Java Date The Java Date class allows the developers to manipulate date and time from within the Java program. The Java Date class is very useful..., some where in your program you will have to use the Java Class to manipulate Java inner class and static nested class Java inner class and static nested class Java inner class and static nested class Working with java Collections class Working with java Collections class In this section we will learn how to wok with Collections class of java.util package. Actually java collections framework java object class methods java object class methods What are the methods in Object class? There are lots of methods in object class. the list of some methods are as- clone equals wait finalize getClass hashCode notify notifyAll
http://www.roseindia.net/tutorialhelp/comment/45503
CC-MAIN-2015-14
refinedweb
1,678
63.49
sphinx-readable-theme 1.1.0 Sphinx Readable Theme A clean and readable Sphinx theme with focus on autodoc – documentation from docstrings. Inspired by flask-sphinx-themes. Installation and setup Install from PyPI: $ pip install sphinx-readable-theme And add this to your conf.py: import sphinx_readable_theme html_theme_path = [sphinx_readable_theme.get_html_theme_path()] html_theme = 'readable' Documentation and examples Documentation with examples is available at License Sphinx Readable Theme is licensed under the MIT license. Changelog Version 1.1.0 - Fixed footnote tables width – thanks, Nick Zaccardi! Version 1.0.0 - Fixed continuation lines in long ordered and unordered list items - Fixed references in Autodoc example Version 0.1.0 First release - Downloads (All Versions): - 15 downloads in the last day - 207 downloads in the last week - 833 downloads in the last month - Author: Ignacy Sokolowski - License: Copyright (c) 2013 Ignacy Sokołowski: ignacy.sokolowski - DOAP record: sphinx-readable-theme-1.1.0.xml
https://pypi.python.org/pypi/sphinx-readable-theme/1.1.0
CC-MAIN-2015-40
refinedweb
149
50.23
- assigned_to: nobody --> phd - status: open --> open-invalid Patch is located inline below. Apparently, you need to specialize the check because no Binary() method exists as of pgdb v3.6+ (possibly earlier too, I don't know). dbconnection.orig is the original file and dbconnection.py is the updated file that now works --- dbconnection.py.orig 2006-10-16 14:09:01.000000000 -0400 +++ dbconnection.py 2006-10-16 14:10:58.000000000 -0400 @@ -213,7 +213,10 @@ self._pool = [] self._poolLock = threading.Lock() DBConnection.__init__(self, **kw) - self._binaryType = type(self.module.Binary('')) + if self.usePygresql: + self._binaryType = type(self.module.BINARY) + else: + self._binaryType = type(self.module.Binary('')) def _runWithConnection(self, meth, *args): conn = self.getConnection() Logged In: YES user_id=4799 First, the patch is invalid. self.usePygresql is defined only in PostgresConnection, hence that "if" will fail for any other connection class. Then, the absence of Binary() means Pygresql doesn't implement DB API 2.0 specification properly. Third, there are more calls to Binary() in the SQLObject. Logged In: YES user_id=1622325 Ok, apparently I'm an idiot. At any rate, without the change above, I wasn't able to to use SQLObject. I don't know what this means in the grand scheme of things for how to fix the issue I ran across. I was just trying to be helpful and point out that something wasn't working properly and (naively) suggest the steps I took to fix it. Logged In: YES user_id=4799 Please don't take this to the personal level. It is the patch that's invalid, not you. But the patch is invalid and cannot be applied. Either you are going to work on it further, or it will wait until someone (including me) finds time to work on it. Log in to post a comment.
https://sourceforge.net/p/sqlobject/patches/74/
CC-MAIN-2017-22
refinedweb
305
61.93
Opened 9 years ago Closed 3 years ago #8618 closed New feature (duplicate) Many-to-many intermediary tables can't have multiple foreign keys to source/target models Description The following schema: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) vacations = models.ManyToManyField('Location', through='Vacation', blank=True) class Location(models.Model): city = models.CharField(max_length=100) country = models.CharField(max_length=100) class Vacation(models.Model): person = models.ForeignKey(Person) location = models.ForeignKey(Location) date = models.DateField() travel_agent = models.ForeignKey(Person, related_name='booked_vacations') doesn't pass validation because "Intermediary model Vacation has more than one foreign key to Person, which is ambiguous and is not permitted." It looks to me like the only reason for this error is because django doesn't have a way to specify which foreign keys on the intermediary model are relevant (or that there is no default behavior specified). There's obviously more than one way around this, and probably someone can come up with a nicer example schema than I did. The simplest thing would be to get rid of that validation check, which (i think) would cause django to use the first key found for each model. Change History (14) comment:1 Changed 9 years ago by comment:2 Changed 9 years ago by. comment:3 Changed 9 years ago by comment:4 Changed 9 years ago by comment:5 Changed 8 years ago by Milestone post-1.0 deleted comment:6 Changed 8 years ago by Convention: Select the foreign key named to.__name__.lower(). comment:7 Changed 6 years ago by comment:8 Changed 6 years ago by comment:9 Changed 5 years ago by Change UI/UX from NULL to False. comment:10 Changed 5 years ago by Change Easy pickings from NULL to False. comment:11 Changed 4 years ago by comment:12 Changed 4 years ago by 1) Convention: the foreign key _without_ a related field is the field for the M2M relation every time. 2) A new option; something in the Meta class to identify the fields that should be used for the through. [...]. I find the third option to be the most natural notation. Also, I wonder what notation the first two options would have for an intermediary table that describes more than one M2M relationship... comment:13 Changed 3 years ago by This ticket seems to be already resolved in Django 1.7: comment:14 Changed 3 years ago by Indeed, it seems that this ticket was a duplicate of #14549 which was fixed in c627da0ccc12861163f28177aa7538b420a9d310. Thanks for the heads up! If you read the ticket (#6095) and mailing list discussions surrounding this feature, this was discussed at the time. There were a few suggestions on how to do this. Simply removing the check isn't an option - there is no reason to believe that the first foreign key will be the correct one. Two possible options:
https://code.djangoproject.com/ticket/8618
CC-MAIN-2017-26
refinedweb
488
57.77
No SSR. - Improve the time-to-interactive by only rendering what's important (with the deferproperty). Server and Client <Box sx={{ p: 2, bgcolor: 'primary.main', color: 'primary.contrastText' }}> Server and Client </Box> <NoSsr> <Box sx={{ p: 2, bgcolor: 'secondary.main', color: 'secondary.contrastText' }} > Client only </Box> </NoSsr> Frame deferring At its core, the NoSsr component's purpose is to defer rendering. As it's illustrated in the previous demo, you can use it to defer the rendering from the server to the client. But you can also use it to defer the rendering within the client itself. You can wait a screen frame with the defer property to render the children. React does 2 commits instead of 1. Unstyled As the component does not have any styles, it also comes with the Base package. import NoSsr from '@mui/base/NoSsr';
https://next--material-ui.netlify.app/material-ui/react-no-ssr/
CC-MAIN-2022-21
refinedweb
141
60.51
Stacks used during the function call in a process address space and the physical address mapping can be illustrated below. Figure 1: Stack in process address space. FUNCTION CALLING CONVENTION in assembly example: /* example of __cdecl */ push arg1 push arg2 call function add ebp, 12 ;stack cleanup And for __stdcall example: /* example of __stdcall */ push arg1 push arg2 call function /* no stack cleanup, it will be done by caller */ Functions in C and C++ programs are known internally by their decorated names. A decorated name is a string created by the compiler during compilation of the function definition or prototype. In Microsoft Visual C++, by default, C++ uses the function name, parameters, and return type to create a linker name for the function. Consider the following function header: void CALLTYPE TestFunc(void) The following table shows the linker name (decorated names) examples for three calling conventions used by Microsoft Visual C++. extern "C" is used to call a C function from C++ and in another situation extern "C" forces the use of the C naming convention for non-class C++ functions. Name decoration incorporates the parameters of a function into the final decorated function name. Examples: The decorated names are strictly a linker facility and are not visible to a C program but you can see it when you debug your program in assembly (disassembled). The following example shows the results of making a function call using the __stdcall calling conventions and the stack frame layout. You can replace __stdcall with another two calling convention in the function prototype skeleton. // function prototype void __stdcall TestFunc(int i, char c, short s, double f); ... // function definition void TestFunc(int i, char c, short s, double f) { ... } ... // function call TestFunc(100, 'p', 10, 1.2345); The result of the stack frame layout illustration for the function call using the __stdcall, compiled using Visual C++ is shown below. Figure 2: Stack frame layout. Other than using the calling conventions explicitly in the program source code, compilers normally provide options that can be used to set the calling conventions. If the compiler’s option is not set and in the program source code also not used explicitly, the default setting of the compiler will be used, normally the __cdecl. For __cdecl and __stdcall conventions, there are three registers involved during the function call that create the stack frame: THE STACK Hopefully the previous sections have given you the big picture. Now we are going to narrow down our discussion just to a stack. To fully understand how the environment in which a buffer overflow can occur, the layout and the operation of the stack must be fully understood. As discussed previously, stack segment contains a stack, one entry/out, LIFO structure. On the x86 architecture, stacks grow downward, meaning that newer data will be allocated at addresses less than elements pushed onto the stack earlier. This stack normally called a stack frame (or a procedure activation record in java) when there are the boundaries pointed by EBP at the bottom and ESP at the top of the stack. Each function call creates a new stack frame and “stacked down” onto the previous stack(s), each one keeps track of the call chain or sequence that is which routine called it and where to return to, once it’s done (Figure 3). Using a very simple C program skeleton, the following tries to figure out function calls and stack frames construction/destruction. #include <stdio.h> int a(); int b(); int c(); int a() { b(); c(); return 0; } int b() { return 0; } int c() { return 0; } int main() { a(); return 0; } By taking the stack area only, the following is what happen when the above program is run. At the end there should be equilibrium. Figure 3: Stack frame and function call. By referring the previous program example and Figure. Further reading and digging: Assembly language tutorial using NASM (Netwide). The High Level Assembly (HLA) language. IA-32 and IA-64 Intel® Architecture Software Developer's Manuals/documentation and downloads. Another Intel microprocessor resources and download. Linux based assembly language resources.
http://www.tenouk.com/Bufferoverflowc/Bufferoverflow2.html
crawl-002
refinedweb
685
52.09
In this section we will discuss about continue statement in java. continue is one of the branching statement used in most of the programming languages like C,C++ and java etc. Sometime we need to skip some of the condition in the loop, we can do this with the use of continue statement. Difference between break and continue is, break exit from the loop but continue will skip the statemen, which is written in the loop. continue statement stop the normal flow of the loop and control return to the loop without executing the statement written after the continue statement. Here is the example which shows the use of continue in the loop. There are two form of continue statement: Example : Unlabeled continue statement for(i=0;i<5;i++) { for(j=0;j<5;j++) { if(j==3) continue; System.out.println(" i "+i); } } In the above example when j become 3 inner for loop will skip the remaining code and control goes to the outer for loop. Example : Labeled continue statement outer :for(i=0;i<5;i++) { for(j=0j<5;j++) { if(j==3)continue outer; System.out.println(" i " +i); } } When j become 3, inner for loop will jump to outer for loop which is labeled with the outer and next iteration of outer loop will be executed. Example : A program using continue statement public class ContinueStatement { public static void main(String args[]) { for(int i=0; i<5; i++) { for(int j=0;j<5;j++) { if(j==3)continue outer; System.out.println("i = " + i + " j = " + j); } } } } Output : After compiling and executing the above program. Advertisements Posted on: June: Continue statement in java Post your Comment
http://www.roseindia.net/java/beginners/java-Continue.shtml
CC-MAIN-2017-04
refinedweb
283
52.8
Problem You have two ranges, and you need to compare them for equality or you need to see which one comes first based on some ordering on the elements. Solution Depending on what kind of comparison you want to do, use one of the standard algorithms equal, lexicographical_compare, or mismatch, defined in . Example 7-4 shows several of them in action. Example 7-4. Different kinds of comparisons #include #include #include #include #include "utils.h" using namespace std; using namespace utils; int main( ) { vector vec1, vec2; vec1.push_back("Charles"); vec1.push_back("in"); vec1.push_back("Charge"); vec2.push_back("Charles"); vec2.push_back("in"); vec2.push_back("charge"); // Note the small "c" if (equal(vec1.begin( ), vec1.end( ), vec2.begin( ))) { cout << "The two ranges are equal!" << endl; } else { cout << "The two ranges are NOT equal!" << endl; } string s1 = "abcde"; string s2 = "abcdf"; string s3 = "abc"; cout << boolalpha // Show bools as "true" or "false" << lexicographical_compare(s1.begin( ), s1.end( ), s1.begin( ), s1.end( )) << endl; cout << lexicographical_compare(s1.begin( ), s1.end( ), s2.begin( ), s2.end( )) << endl; cout << lexicographical_compare(s2.begin( ), s2.end( ), s1.begin( ), s1.end( )) << endl; cout << lexicographical_compare(s1.begin( ), s1.end( ), s3.begin( ), s3.end( )) << endl; cout << lexicographical_compare(s3.begin( ), s3.end( ), s1.begin( ), s1.end( )) << endl; pair iters = mismatch(s1.begin( ), s1.end( ), s2.begin( )); cout << "first mismatch = " << *(iters.first) << endl; cout << "second mismatch = " << *(iters.second) << endl; } The output of Example 7-4 looks like this: The two sequences are NOT equal! false true false false true first mismatch = e second mismatch = f Discussion Use equal to compare two sequences for equality. It takes three or four arguments, depending on the version you use. Here's how equal is declared: bool equal(In1 first1, In1 last1, In2 first2); bool equal(In1 first1, In1 last1, In2 first2, BinPred pred); equal compares each element between first1 and last1 with each element starting at first2 using operator==. If you supply pred, equal uses that to test equality instead. Ensure that the sequences each have the same length before calling equal; it assumes the second range is at least as long as the first, and if it isn't, the behavior is undefined. If you want to know more about how or where two sequences differ, you can use lexicographical_compare or mismatch. lexicographical_compare compares two sequences and returns true if the first is lexicographically less than the second, which means that each pair of elements in the two sequences is compared using the < operator. The declaration of lexicographical_compare looks like this: bool lexicographical_compare(In1 first1, In1 last1, In2 first2, In2 last2); bool lexicographical_compare(In1 first1, In1 last1, In2 first2, In2 last2, Compare comp); As soon as operator< returns true, or the first sequence ends before the second, true is returned. Otherwise, false is returned. Consider the character sequences in Example 7-4: string s1 = "abcde"; string s2 = "abcdf"; string s3 = "abc"; lexicographical_compare(s1.begin( ), s1.end( ), // abcde < abcde s1.begin( ), s1.end( )); // = false lexicographical_compare(s1.begin( ), s1.end( ), // abcde < abcdf s2.begin( ), s2.end( )); // = true lexicographical_compare(s2.begin( ), s2.end( ), // abcdf < abcde s1.begin( ), s1.end( )); // = false lexicographical_compare(s1.begin( ), s1.end( ), // abcde < abc s3.begin( ), s3.end( )); // = false lexicographical_compare(s3.begin( ), s3.end( ), // abc < abcde s1.begin( ), s1.end( )); // = true The complexity of lexicographical_compare is linear and will do a number of comparisons equal to the minimum of the two sequence lengths, or until the first time an element in one of the sequences is less than the corresponding element in the other. The comparisons are implemented entirely using operator<, so if iter1 and iter2 are iterators into the two sequences, the comparison stops as soon as *iter1 < *iter2 or *iter2 < *iter1. mismatch will tell you where two sequences differ. Its declaration is a little different than equal and lexicographical_compare, though, because it returns a pair<> of iterators instead of a bool. Here it is: pair mismatch(In1 first1, In1 last1, In2 first2); pair mismatch(In1 first1, In1 last1, In2 first2, BinPred); The two iterators returned point to the differing elements in each of the sequences. Consider Example 7-4: string s1 = "abcde"; string s2 = "abcdf"; pair iters = mismatch(s1.begin( ), s1.end( ), s2.begin( )); cout << "first mismatch = " << *(iters.first) << ' '; // 'e' cout << "second mismatch = " << *(iters.second) << ' ';// 'f' You have to ensure that the second range is at least as long as the first. If the second sequence is shorter than the first, mismatch has no way to know it and will continue making comparisons to elements past the end of the second sequence, which has undefined behavior if it extends past the end of the second sequence. Additionally, if there is no mismatch, the first iterator will be pointing to last1, which may not be valid (e.g., if you passed in end( ) as last1). You may have noticed from the declarations of each of these algorithms that the types of the iterators for each of the two sequences are different. This means that the two sequences can be containers of different types, so long as the type of the element those iterators refer to have operator< defined for them. For example, you may want to compare a string to a vector: string s = "Coke"; vector v; v.push_back('c'); v.push_back('o'); v.push_back('k'); v.push_back('e'); std::cout << std::lexicographical_compare(s.begin( ), s.end( ), v.begin( ), v.end( )) << ' '; This compares each of the characters in the two sequences without regard for the type of container that holds them. The C++ standard library provides several different ways to compare sequences. If none of these suits your needs, look at the source code for them; it will provide a good example of how you can write your own efficient, generic algorithm. See Also Recipe 7.1 Building C++ Applications Code Organization Numbers Strings and Text Dates and Times Managing Data with Containers Algorithms Classes Exceptions and Safety Streams and Files Science and Mathematics Multithreading Internationalization XML Miscellaneous Index
https://flylib.com/books/en/2.131.1/comparing_ranges.html
CC-MAIN-2021-21
refinedweb
983
55.95
This one time, at band camp, Oliver Fuchs said: > On Wed, 11 Dec 2002, Sandip P Deshmukh wrote: > > > i would like to know if i can: > > > > - automatically move these messages to a particular folder - say > > spam > > > > Hi, > add this to your .procmailrc file: > > :0: > * ^X-Spam-Status: Yes > caughtspam ISTR that Sandip sai (in another post) that he's not using procmail. If that's so, just use exim's native filtering abilities. Put this is your ~/.forward: # Spam Drop if $h_X-Spam-Status contains "Yes" then save $home/Mail/SPAM finish endif Exim's filtering ability is fine for most straightforwad filters - My mail goes into about 25 folders based on header keywords, and it's worked reliably here. I understand procmail is more versatile, but so far I haven't needed it. -- -------------------------------------------------------------------------- | Stephen Gran | Help! I'm trapped in a PDP 11/70! | | steve@lobefin.net | | | | | -------------------------------------------------------------------------- Attachment: pgprxlXPCs1Eu.pgp Description: PGP signature
https://lists.debian.org/debian-user/2002/12/msg02089.html
CC-MAIN-2017-34
refinedweb
154
66.03
OnixS::FIX::Message::set method must be used. If there is no field of a given tag number available in the message, this member creates an association. If the field already exists, this member updates its value with the new value. Also, there are Set methods for each standard type (Int32, Int64, Decimal, etc.). OnixS::FIX::Message::setV methods. a need to serialize such values, however, if you perform a large amount of typed set/get operations with the message object on the critical path, then these methods are the best choice from the performance point of view. OnixS::FIX::Message class supports the Short String Optimization (SSO). If the size of the string presentation of a field value less than the size of the internal field value buffer (15 bytes for 32-bit and 23 bytes for 64-bit) then such a value is stored directly in this buffer without any new memory allocation. Therefore, setting short string values is faster because the dynamical memory allocation is not performed. Also, subsequent access to a field with the short string can work faster due to the better data locality, however, please note that SSO is not applied if a long string is set earlier to the field. To get a field value, the OnixS::FIX::Message::get method must be used. To check the field presence, the OnixS::FIX::Message::contain method must be used. To remove a field, the OnixS::FIX::Message::erase method must be used. To iterate over all fields of a FIX message you can use the OnixS::FIX::FieldSet::ConstIterator class. This iterator does not iterate over fields from a repeating group. To iterate over fields of the repeating group you need to get the corresponding OnixS::FIX::GroupInstance object from the repeating group, please see the FIX Repeating Groups. The following example demonstrates the basic operations over message fields. In each sub-namespace, which corresponds to certain FIX version (like OnixS::FIX::FIX40), the OnixS::FIX::FIX40::Tags namespace is defined. This namespace contains the constants for all-known tag numbers. Additionally, there are the OnixS::FIX::FIX40::Values and OnixS::FIX::FIX40::TypedValues namespaces. These namespaces contain the constants for all-known tag values. The OnixS::FIX::FIX40::Values namespace contains only string constant values, the OnixS::FIX::FIX40::TypedValues namespace contains typed constant values (string, char, int) in accordance with FIX protocol types. Both namespaces contain the same values, however, typed values can be more convenient in some cases, for example, you can compare directly your internal char or int variables with corresponding typed constant without the conversion from string to char, int. Also, there is the OnixS::FIX::FIX50_SP2_Latest namespace. It contains tag numbers and values for the latest extension pack (e.g., EP264). The usage of all mentioned constants makes the source code more readable.
https://ref.onixs.biz/cpp-fix-engine-guide/group__manipulating-fix-message-fields.html
CC-MAIN-2022-27
refinedweb
475
54.12
Dijkstra did understand what he was talking about. Dijkstra was urging the community to move forward and work with higher abstractions. Dijkstra points out that our intellectual powers are limited in a fashion that should make us strive to shorten the conceptual gap between the static program and the dynamic process. A modern example of this conceptual gap is found when adding an element to a collection and extracting it in the Java™ Programming Language before the advent of generic types: List strings = new ArrayList(); // list of strings strings.add("Hello"); ... String s = (String)strings.get(0); Notice how the programmer is required to bridge a conceptual gap by adding comments and casts that aren't enforced by the compiler as it is with generic types: List<String> strings = new ArrayList<String>(); strings.add("Hello"); ... String s = strings.get(0); Also notice that the compiler will notify the developer if he makes mistakes: Integer i = (Integer)strings.get(0); // compile-time error strings.add(1); // compile-time error The benefits should be clear and I like to think if Dijkstra had been consulted on generics he would have said: "not having generic types should be considered harmful". Ken Arnold doesn't understand generics and thus he suggest that generics should be considered harmful. Let's examine Ken's arguments: My colleague told me something I misunderstood, but when I follow my wrong conclusions to the end, it doesn't make sense. Thus generics is considered harmful. And so Ken declares that you shouldn't do this: interface Holder<T> { T[] toArray(); } Allow me to correct your misunderstanding. You can't do this: class Box<T> { T[] array = new T[10]; // compile-time error } You should not try to work around it: class Box<T> { T[] array = (T[])new Object[10]; // BAD and causes a warning } This is an unfortunate side-effect of erasure, the VM doesn't know what T is at runtime, so the compiler has no way to generate code that can construct an array of the right type. In the VM, all arrays must record their element type. This is because arrays should be considered harmful: public class Test { public static void main(String... args) { Object[] array = new String[10]; array[0] = new Object(); // causes a run-time error, ArrayStoreException } }The "intuitively correct" type rule that allows the first assignment demonstrates that arrays aren't statically type safe. However, they are type safe: the VM eventually rejects the problematic assignment. If you replace arrays with the generic ArrayList, you get this program: import java.util.*; public class Test { public static void main(String... args) { List<Object> array = new ArrayList<String>(10); // compile-time error array.add(0, new Object()); } } So Ken and others should consider arrays harmful, not generics. Ken also says that because he and David can't understand the declaration of Enum then it must be evil. Let's look at Enum, it's not that complicated: class Enum<E extends Enum<E>> { ... } This is called an F-bound, I'm not exactly sure what the F means but think of it as function bounds. The bound on the type variable is a function (F) of the type variable. Yes, I know that probably didn't help your understanding. Hold on, here goes... Since Enum is a special implementation class used for the new enum types, let's look at Comparable instead. The definition of Collections.sort looks like this: public static <T extends Comparable<? super T>> void sort(List<T> list) T should be a type which implements Comparable of a supertype of T. In other words: T must be comparable to it self (or a supertype of itself). This is a simple recursive definition. So how do you validate that a given type meets the criteria (is within the bounds of T). It's simple: substitute T for the type and check if the statement is true. For example, Integer implements Comparable<Integer>, so the question is does Integer extend Comparable<? super Integer> The answer is yes. Integer implements Comparable<Integer> which is a subtype of Comparable<? super Integer>. Piece of cake.
http://blogs.sun.com/ahe/date/20050727
crawl-002
refinedweb
689
55.95
This tip is a continuation to my earlier one on JavaScript performance that can be found here. Tips mentioned in both these articles go hand in hand and front end developers, especially beginners, should be aware of these nitty gritty details. The intended audience for this tip is JavaScript beginners with a few years of programming experience. JavaScript nowadays is found in majority of the web apps hosted on the Internet. One common observation in most of these applications is that the way people code JavaScript more often than not causes maintenance nightmares! It either isn't object oriented enough or the code isn't structured well! Often, developers either overlook or are ignorant about JavaScript coding practices. The intent of this tip is not to provide developers with a laundry list of check points. There are lots of websites out there on the Internet which provide those details. The idea behind writing this tip is to simply capture often repeated bad practices and provide some tips on how to correct them so that when your code goes into maintenance, people don't curse you. So hopefully this tip and the performance tips should provide developers with atleast some basic insight on how to start writing maintainable, high performing code. //MyScript.js function doSomeThing() { } //....More functions like above //....Still more global functions!!! function doSomeThingElse() { } The issue with global functions is that they are all appended to window namespace. In case another script file uses the same function name, the function in the script that’s loaded last will execute causing unexpected behavior. var MyApp = { }; MyApp.Utilities = { doSomething : function(){ }, doSomethingElse : function(){ } }; Tip: As a best practice, try to use camel case for your function names and Pascal case for namespaces and classes. var MyApp = { }; MyApp.Utilities = (function() { this.c1 = ""; //public variable var c2 = ""; //private variable //private function function doSomething() { } return { //public function doSomeThingElse: function() { //Logic doSomething(); } }; })(); if(something){ if(something){; //Recommended if (something) { } for (i = 0; i < 10; i += 1) { } //Not recommended - consumes space unless minified if (something) { } Note: We shouldn’t take the JS Engine for granted and skip semi colons always. Do not forget to include semicolon at the end of function expression but you can skip semicolon at the end of function declarations. var m = new Array(1);//This is Ok var n = new Array(1.5);//Not Ok To avoid this, it's best to use the literal notation to initialize an array. var n = [1, 1.5];//Simple and easy! Similarly, avoid using built-ins for Boolean. var b = new Boolean(0);//b is true since we are using new var b = Boolean(0);//b is false since we are evaluating the expression parseInt parseFloat parseInt("9", 10);//gives 9 parseInt("9", 8);//gives NaN parseInt("10", 8);//gives 8 typeof function foo(g){ if(typeof g === 'function'){ //Do your stuff.. } } If you find this tip useful, please share it with the developer community. Happy learning. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/Tips/624810/Javascript-Maintenance-Tips?PageFlow=FixedWidth
CC-MAIN-2014-52
refinedweb
509
55.34
Bug #1885 Proper comparison of recursive Struct & Range Description =begin The following code freezes the latest ruby 1.9: MyClass = Struct.new(:foo) x = MyClass.new; x[:foo] = x y = MyClass.new; y[:foo] = y x == y # Loops forever (can not be interrupted) Solution: rb_struct_equal & rb_struct_eql should handle recursion in a similar fashion as Array and Hash (i.e. by calling rb_exec_recursive_paired and returning Qtrue if recursion is detected). I could make a patch if needed. Searching the source code for rb_exec_recursive revealed that Range is potentially recursive too (see range_inspect). The ==, eql? and === methods do not call rb_exec_recursive_paired and are thus also potentially troublesome. To build a recursive Range is not trivial though; either some intermediate container class is needed or else some crazy thing like: class CrazyRange < Range def initialize super(self..self) end def <=>(x) 0 # Needed so CrazyRange can be the begin and end values of a range... end end CrazyRange.new == CrazyRange.new # Loops forever (can not be interrupted) I'm not sure that it is worth modifying ==, eql? and === to use rb_exec_recursive_paired and make them bulletproof. Note that both Struct#hash and Range#hash face the same issue than Array#hash & Hash#hash (see issue #1852) =end Files History Updated by marcandre (Marc-Andre Lafortune) over 10 years ago - File struct_comparison.diff struct_comparison.diff added =begin Here is a patch for the latest 1.9.x that fixes comparison between recursive Struct. The right result is now returned, instead of looping forever. Note: this fixes Struct only; Range has not been patched. Rubyspecs have been updated. =end Updated by marcandre (Marc-Andre Lafortune) about 10 years ago - Status changed from Open to Closed - % Done changed from 0 to 100 =begin Applied in changeset r25010. =end Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/1885
CC-MAIN-2019-51
refinedweb
296
58.89
grokcore.view 2.9 Grok-like configuration for Zope browser pages This package provides support for writing browser pages for Zope and registering them directly in Python (without ZCML). Contents - Setting up grokcore.view - Examples - API overview - Changes - 2.9 (2014-05-15) - 2.8 (2012-12-11) - 2.7 (2012-05-01) - 2.6.1 (2011-06-28) - 2.6 (2011-06-28) - 2.5 (2011-04-04) - 2.4 (2011-03-01) - 2.3 (2011-01-04) - 2.2 (2010-12-16) - 2.1 (2010-11-03) - 2.0 (2010-11-01) - 1.12.1 (2009-09-17) - 1.12 (2009-09-17) - 1.11 (2009-09-15) - 1.10 (2009-09-14) - 1.9 (2009-07-04) - 1.8 (2009-07-04) - 1.7 (2009-05-19) - 1.6 (2009-04-28) - 1.5 (2009-04-10) - 1.4 (2009-04-08) - 1.3 (2009-01-28) - 1.2 (2008-10-16) - 1.1 (2008-09-22) - 1.0 (2006-08-07) (or implement the render method for direct control) - a context that it’s registered for as a view - a name (which is, if not specified explicitly, the class’s name in lower case characters). A browser page that does not use a template but just outputs some computed data also subclasses the grokcore.view.View baseclass.!”: import grokcore.view import zope.interface class Hello(grokcore.view.View):. Implement the render method to forgo looking up a template and show the result of calling the render method instead.. - render(**kw) - Return either an encoded 8-bit string or a unicode string. The method can take arbitrary keyword parameters which are filled from request values. If not implemented, a template is looked up in the template dir instead.. Changes 2.9 (2014-05-15) - Make possible to disable the template warning with the help of the GROK_DISABLE_TEMPLATE_WARNING environment variable. - The skin option of grokcore.view.util.url now accepts strings that will be used as skin name as possible alternative to a skin interface. - The skin directive can now be used on interfaces that inherits only from IRequest instead of IBrowserRequest. 2.8 (2012-12-11) - Add a skin=[skin component] argument to the grokcore.view.util.url() function and grokcore.view.components.View.url method. This allows for computing URLs on a specific skin. Note that it is not verified whether the computed URL actually exist on the specified skin. 2.7 (2012-05-01) - Use the component registration api in grokcore.component. - Improve error message when a templatedir() directive points to a non- existent directory. (fix launchpad issue 680528). - Improve error message when a template is required for a component but cannot be found (Fix Launchpad issue #225855, #242698). - Fix how the static resource are found. Instead of using as name the package name where the component is defined, using as name the package where the template for the component is defined, or the base component. This is done by setting an attribute __static_name__ on the component that specify which resource directory should be used. This fix missing resources when you extend the component and don’t redefined the template. 2.6.1 (2011-06-28) - Fix bug where zope.browserpage was not correctly declared as a dependency. 2.6 (2011-06-28) - Add the ContentProvider component. 2.5 (2011-04-04) - Fix a test that relied on older zope.testbrowser behaviour. 2.4 (2011-03-01) - grok.View component can optionally use the grok.provides directive, specifying an interface that the component provides (instead of the zope.interface.Interface that views by default provide). - Add a new ZCML directive, ignoreTemplates that let you configure which template filename pattern should be ignored by the template registry. The pattern attribute of the directive accepts regular expresssion that will be matched against the (template) file extension. - Use the zope configuration action ordering feature to have templates registered for all packages and modules, before trying to associate the templates. Checking for unassociated templates is done very very late in the configuration action order. - Inherited grok.template() information is looked up against the module of the view class that uses the grok.template() directive. This allows for subclassing view components that use the grok.template() directive from other packages. 2.3 (2011-01-04) - Removed the static directory grokker in order to make way for using fanstatic. 2.2 (2010-12-16) - Factor out a base template grokker that associate templates for viewish components. - Merge support for a global template registry that removes unnecessary warnings about unassociated templates in “shared” template directories. 2.1 (2010-11-03) - Use an update martian and grokcore.component. - The custom zope publication has now moved from the grok package to grokcore.view. The registration of the publication is optional, and is used by grok and the grokcore.json package. - The util function make_checker has been moved from the grok package to grokcore.view. 2.0 (2010-11-01) The view directive has been moved from grokcore.viewlet to grokcore.view. The IGrokSecurityView has been moved from grok to grokcore.view. Fix the url() function to behave properly while passed an empty data dict. Fix the url() method to accept the “status” and “trusted” arguments, passed on to the redirect method on the response object. grokcore.view no longer depends on zope.app.testing and related packages. Instead we now use zope.app.wsgi.testlayer to run functional tests. Made package comply to zope.org repository policy. Fixed launchpad bug #395061 : removed the default_fallback_to_name function. It can be imported from grokcore.security if needed. grokcore.view no longer depends on zope.app.zcmlfiles. We removed all the extra dependencies and fixed one test that used zope.app.rotterdam and zope.app.basicskin. Back-ported the changes of the 1.13 branch related to the directory resource registration, using the latest ztk packages. Factor out generally useful methods and properties for view-ish components into components.ViewSupport mixin. Works with new Martian (0.13) and grokcore.component 2.1. Test fix: support windows paths. Warnings are now emitted as log messages with level logging.WARNING to a logger named grokcore.view with level logging.ERROR. That means that by default no warnings are emitted anymore (while errors will still appear). To get the warnings back, reduce the level of logger grokcore.view to logging.WARNING or lower. This can be done in Python or via a logging conf file, for instance in the .ini files of regular grokprojects. See the Python standard lib logging module for details. 1.12.1 (2009-09-17) - A compatibility fix to support grokcore.viewlet. 1.12 (2009-09-17) Use 1.0b1 versions.cfg in Grok’s release info instead of a local copy; a local copy for all grokcore packages is just too hard to maintain. Revert the splitting CodeView/View. The original reasons for the split have been obsoleted by the recent martain developments regarding inheritted module level directives. At the same time the split up components proved cumbersome to use and a too big a change between the 1.0a and 1.0b releases of Grok. View components will now again behave like it did up until the latest alpha release of Grok. CodeView is still available as a backwards compatibility alias for View. Please update all references to CodeView to View. Fix the template registry and grokker for views to let View and other components using View as base class to be associated with a template directly by setting it as ‘template’ attribute on the view class. Example: class MyView(grokcore.view.View): template = grokcore.view.PageTemplate('<p>hello</p>') This isn’t exactly officially supported but enough people depend on it and have documented it so that we don’t want to just break it. 1.11 (2009-09-15) - The response attribute needs to be available in CodeView as well. 1.10 (2009-09-14) - Up the version requirement for grokcore.security to 1.2. - Bring versions.cfg in line with current grok versions.cfg. ‘static’ resource directory if the ‘static’ ‘ - Download URL: - License: ZPL - Categories - Package Index Owner: philikon, ctheune, thefunny42, faassen, jw, reinout, janjaapdriessen, ulif, trollfot - Package Index Maintainer: thefunny42, janjaapdriessen - DOAP record: grokcore.view-2.9.xml
https://pypi.python.org/pypi/grokcore.view/2.9
CC-MAIN-2016-30
refinedweb
1,377
62.14
Member since 08-12-2016 39 7 Kudos Received 3 Solutions 01-05-2018 10:33 AM 01-05-2018 10:33 AM whatever I tried, all yarn applications ended up in the default queue these are the things I tried: 1) setting property in the titan-hbase-solr.properties (none of the following worked) mapred.job.queue.name=myqueue mapreduce.job.queue.name=myqueue mapred.mapreduce.job.queue.name=myqueue 2) setting property in the gremlin shell gremlin> graph = TitanFactory.open("/usr/iop/4.2.5.0-0000/titan/conf/titan-hbase-solr.properties") gremlin> mgmt = graph.openManagement() gremlin> desc = mgmt.getPropertyKey("desc2") gremlin> mr = new MapReduceIndexManagement(graph) gremlin> mgmt.set('gremlin.hadoop.mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root.gremlin]: hadoop gremlin> mgmt.set('hadoop.mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root]: hadoop Display stack trace? [yN] n gremlin> mgmt.set('titan.hadoop.mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root]: titan Display stack trace? [yN] n gremlin> mgmt.set('mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root]: mapred Display stack trace? [yN] n gremlin> gremlin> mgmt.set('mapreduce.mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root]: mapreduce Display stack trace? [yN] n gremlin> mgmt.set('gremlin.mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root.gremlin]: mapred Display stack trace? [yN] n gremlin> mgmt.set('gremlin.hadoop.mapred.job.queue.name', 'myqueue') Unknown configuration element in namespace [root.gremlin]: hadoop Display stack trace? [yN] n gremlin> ... View more Labels: 1) Start Atlas in debug mode first you want to add extra JVM options in the startup script , so in atlas_start.py replace this line DEFAULT_JVM_OPTS="-Dlog4j.configuration=atlas-log4j.xml -Djava.net.preferIPv4Stack=true -server" with this DEFAULT_JVM_OPTS="-Dlog4j.configuration=atlas-log4j.xml -Djava.net.preferIPv4Stack=true -server -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=54371,server=y,suspend=y " Now, when you start Atlas, it will hang until you connect with the debugger (because of the suspend=y). 2) connect from Eclipse remote debugger Make sure you have imported the Atlas project into Eclipse based on this document: Then create a new debug configurations under the following menu: /Run/Debug Configurations... Make sure the port is set to the same above (54371) and connection type is Standard (socket attach) Use Eclipse JDT launcher. ... View more 08-22-2017 04:00 PM 08-22-2017 04:00 PM Thanks for your response, @bkosaraju, can you give me an example of any of these options you mentioned? ... View more For testing purposes I want to create very large number, let's say 1 million empty directories in hdfs. What I tried to do is use `hdfs dfs -mkdir`, to create 8K directories and repeat this in a for loop. for i in {1..125} do dirs="" for j in {1..8000}; do dirs="$dirs /user/d$i.$j" done echo "$dirs" hdfs dfs -mkdir $dirs done Apparently it takes hours to create 1M folders this way. My question is, what would be the fastest way to create 1M empty folders? ... View more - Hadoop Core - HDFS Labels: 04-20-2017 12:57 PM 04-20-2017 12:57 PM it is not clear, what is being asked here. @manyatha reddy, could you please be more specific? ... View more 03-28-2017 11:53 AM 03-28-2017 11:53 AM What do you exactly mean by "if an user arun is trying to access hdfs"? Are you trying to access a file/folder with the "hadoop fs" command while you are logged into linux as user "arun"? ... View more 03-28-2017 11:49 AM 03-28-2017 11:49 AM Assuming that you will want to connect in direct, binary transport mode, in a nonsecure env, this is how the jdbc connection string should look like (this is what you have tried): jdbc:hive2://<host>:<port>/<db> If your hiveserver runs on m1.hdp.local:10000, and the database name is default, then the connection string you tried should have worked: jdbc:hive2://m1.hdp.local:10000/default Since it did not work, I suppose you hiveserver has different port or runs on an other host. You should be able to check these in Ambari. Please consult to these docs on the various connection modes and corresponding connection strings. ... View more 03-27-2017 01:36 PM 03-27-2017 01:36 PM Not sure if I got your question right, the CreateEvent will contain the HDFS path. The name of the file is part of the HDFS path (comes after the last '/'). I hope this answers your question. see the inotify patch here, /** * Sent when a new file is created (including overwrite). */ public static class CreateEvent extends Event { public static enum INodeType { FILE, DIRECTORY, SYMLINK; } private INodeType iNodeType; private String path; private long ctime; private int replication; private String ownerName; private String groupName; private FsPermission perms; private String symlinkTarget; ... View more 03-27-2017 12:56 PM 03-27-2017 12:56 PM I tried both Virtualbox and Docker on the same Macbook, Docker used less resources and was faster. ... View more 03-23-2017 04:20 PM 03-23-2017 04:20 PM From the error code, it seems that the problem is, you do not have hive-cli-*.jar in the Oozie sharelib folder. Could you also check the error message and post that as well? ... View more You should have posted the code you are trying to run, and how you are trying to run (how you submit the job into Spark). Without that it is harder to get an answer. From the error I can see you are trying to run wordcount on this file: hdfs:%20/user/midhun/f.txt Have you tried something like this? hdfs dfs -put /user/midhun/f.txt spark-submit --class com.cloudera.sparkwordcount.SparkWordCount \ --master local --deploy-mode client --executor-memory 1g \ --name wordcount --conf "spark.app.id=wordcount" \ sparkwordcount-1.0-SNAPSHOT-jar-with-dependencies.jar hdfs://namenode_host:8020/user/midhun/f.txt 2 ... View more 03-23-2017 03:56 PM 03-23-2017 03:56 PM can you please post the whole stack trace of the error message? it seems like you omitted some meaningful parts ... View more This question is too board in this form. You need to understand this: if you want to get advise on which solution (computing engine) to choose, you should give a descrption first on what you are trying to accomplish, what kind of problem are you trying to solve, what is the nature of your workload. ... View more 03-23-2017 03:49 PM 03-23-2017 03:49 PM If I understand correctly, you say you have large tables (3 million records) return a query like this relatively fast: Select * from example_table Limit 10 or Where serial = “SomeID” but when you run similar query against an external table stored on AWS S3, it performs badly. Did you try to copy table data file to hdfs, and then create an external table on the hdfs file? I bet that could make a big difference in the performance. I assume the difference is because in case the table data is stored on S3, hive first needs to copy the data from S3 onto a node where hive runs and the speed of that operation will depend on network bandwidth available. ... View more 03-23-2017 03:36 PM 03-23-2017 03:36 PM Saurabh, it is not possible to answer your question because it contains insufficient information. Please update your post and add the following info: - the configuration that is supposed to tell Falcon to run your shell script, 10 times. - exactly what you see in the oozie web UI ... View more 03-23-2017 03:31 PM 03-23-2017 03:31 PM First of all, I would recommend, that when you describe the solution you have in mind and ask for opinions here, you should also describe what you are trying to accomplish, what are your 'requirements'. Without understanding that task at your hand, it is impossible to advise on the any proposed solution. I would also recommend you consult this doc (please disregard if you have already done that): and then come back here with a more specific question. ... View more 03-23-2017 03:18 PM 03-23-2017 03:18 PM You can use a load balancer that is built in Solr. In case you have only one shard, you can specify a list of replicas to choose from for a single shard (for load balancing purposes) by using the pipe symbol (|):*:*&shards=localhost:7574/solr/gettingstarted|localhost:7500/solr/gettingstarted Consult the docs for more comlex scenarios (like more shards): ... View more 03-23-2017 03:10 PM 03-23-2017 03:10 PM What kind of client do you use? (the client application uses what kind of interface to connect to Solr) ... View more 03-23-2017 03:02 PM 03-23-2017 03:02 PM This error message does not look lit it would be specific to NIFI in any way. I would try to consult to EC2 support about this error and see what they say as potential cause, based on the error message. Then I would come back here and ask about how NIFI could do that ... View more 03-23-2017 02:56 PM 03-23-2017 02:56 PM 1) store PDF files in HDFS It would be possible to store your individual PDF files in HDFS and have the HDFS path as an additional field, stored in the Solr index. What you need to consider here, HDFS is best at storing small number of very large files, so it is not effective to store large number of relatively small PDF files in HDFS. 2) store PDF files in HBase It would also be possible to store the PDF files in a object store, like HBase. This is an option that is definitely feasible and I have seen several real life implementation of this design. In this case, you would store the HBase id in the Solr index. 3) store PDF files in the Solr index itself I think it is also possible to store the original PDF file in the Solr index as well. You would use a BinaryField type and you would set the stored property to true. (Note that you could even accomplish the same with older version of Solr, lacking the BinaryField type. In this case, you would have to convert your PDF into text (e.g. with base64 encoding) then store this text value in a stored=true field. Upon retrieval, you would convert it back to PDF). Without an estimation on the number of PDF files and the average size of a PDF, it would be hard to choose the best design. It could be also in important factor if you want to update your documents frequently or you just add to to the index once and then they won't change anymore. ... View more 03-23-2017 02:07 PM 03-23-2017 02:07 PM By the way is it a final decision that you will store the data in HBase? Kevin, you wrote: > The web application allows the user to specify certain filters that are mandatory, as well as optional. The result coming from HBase are precalculated aggregates based on the filters of the application. I am afraid this is not sufficient information to design your HBase tables. Can you please elaborate on what kind of data will be stored in the db? What kind if filters will be applied, what kind of aggregate calculations will be done? ... View more 03-22-2017 10:18 AM 03-22-2017 10:18 AM have you copied the jar file to the hdfs? if you run this command, what is the result? hadoop fs -ls /path/to/your/spark.jar ... View more linux username/password: root/hadoop this will also help: ... View more 03-21-2017 04:48 PM 03-21-2017 04:48 PM First things first: it was not clear to me, if you can build your project and create a jar file by running a maven command? Once you can build a jar file out of your project, your pom.xml is fine. To check your pom.xml, run this command: mvn package If it returns en error, please update your original post and include the mvn error ... View more 03-21-2017 03:42 PM 03-21-2017 03:42 PM @mayki wogn. ... View more 03-21-2017 02:34 PM 03-21-2017 02:34 PM @Nitin Kaushik, this question seems to be a duplicate, please consult to my answer given to the your similar question ... View more 03-21-2017 02:12 PM 03-21-2017 02:12 PM 03-21-2017 02:10 PM 03-21-2017 02:10 PM 03-21-2017 02:02 PM 03-21-2017 02:02 PM The cause of this error is the JVM cannot find the javax.net.ssl.trustStore required for SSL, or it does not contain the required certificates. This means you will need to properly configure truststore for your nifi installation. Consult the following posts for further help with that ... View more 03-21-2017 01:46 PM 03-21-2017 01:46 PM . ... View more
https://community.cloudera.com/t5/user/viewprofilepage/user-id/58285
CC-MAIN-2020-45
refinedweb
2,244
63.39
This tutorial comes in because I'm tired of debugging code that looks like crap. Most of this tutorial will be writen in pseudocode or C++ or java (which is similar), whatever just comes out. Problem solving: Before you start programming you need to have an idea of what you are going to do that means you don't just bang out code, you waste a lot of time fixing logic and syntax errors that way, take a look at it figure it out if it's a math problem write out the function and how you want it to look do a flow chart or use some pseudocode so when you finally put it into your programming language of choice it looks clean and well thought out. This is one of the most over looked steps in programming and it results in some ugly looking code with lot's of parts that don't need to be there. If you have it figured out before you start codeing it really goes a lot faster. Example: so if you have a problem that requires you to count how many A's you got in a class this year and determine the A by percent. make sure you work it out before hand it doesn't have to be nice you could just jot this down (granted it's a bit simplistic but it's much more effective on really complicated problems like the towers of henoi [try doing that one without any help or jotting it down in advance] has a simple and elegent solution but it takes some reasoning out). if (grade > 90) counterA = ++counterA; These kind of things make it easyer for you to put it down. Programming structures: Back in the day programming was done by telling the program to hop to different lines after that line was completed and resulted in some really confusing stuff to look at, hard to debug too because you weren't sure what was going to be effected by it. Now there are three types of structures. Sequencial: Top to bottum left to right 1 after another. Selection: choices dependent on user imput if statements almost anything involveing booleans go here. Repetion: repeats using for while do/while statements, I'm a while statement fan myself because it's easyer to understand it at first look, but some people like to use for's. Basics of programming Ego notice it at the top, this is very important put as much info as you can including the book your using for programming your name (psudoname if your uncomfortable with your real name), the progam name, what the program is suppose to do [if anything put that one down folks], and cite the sources of code you actually lifted into your program and mabey an original program if your modifying open source. Use remarks but don't over use remarks, here are times to definatly use remarks When you introduce a new variable ( make sure you tell what the variable does) For each part of the actual program ( for each function not each line but like //this part counts the grades. or //this part sorts the array.) When you do something that is generally a confusing step or a few lines that are garbled but compile and work. Variables are your friend, but don't use more variables than you need too, use as many local (variables that only work in a certain part of the code) variables as you possibly can it cuts down on debugging time because you only have worry about certain sections being broke. Moduals, use moduals, a lot of programming is debugging and fixing, make sure that you have your program sectioned in an easy way with small chunks of code so it doesn't look like one emense programs, your buddy might not tell you to get lost when you asking him to help debug your program if it's seperated nicely. Use tabs and spaces, (I'm guilty of forgetting this one here) use tabs and spaces to set aside selection and repetition structures and ANYTHING nested. This is important so the code is pleaseing to look at and also helps organize carage returns and the like. And lastly start small. Take a small chunk of code and make sure it works first don't program the whole thing and hope it compiles. If the code has a bunch of sections that do similar things only write one of those things compile and debug that part of it then adapt it to other parts of the program. If one section works the rest of it has a good chance of working too. to leave you I'll drop a bit of code that I consider from good programming practice this will be in java. //zepherin //antionline teaching text // //cosmos thread //zephprog.java //display a simple text message //Java Software Solutions 2nd ed. by John Lewis and William Loftus public class zephprog //these statements are just the name of the program and setup the main statement area { public static void main (String [] args) { int x = 21; //this variable just holds the place 21 it could be used as anything System.out.println ("I am a piece of text what is your name:"); } } hoped you liked my little tutorial Alternate realities celebrate reality. If you cant handle the reality your in, then you wont be able to handle the one your attempting to escape to. hum.. "counterA = ++counterA; " ? that would be pointlessly redundant... you probably meant: "counterA++;" by itself. and using spaces and tabs is called "indentation". Besides that, you bring up good points. I myself have done a good bit of debugging friends programs in college, and it's such a pain when its poorly written. These weren't even very big programs, but just complex enough to be easily messed up. I mean, I (we, when in teams) had the same programs to do and sometimes, reading friends code, you would think your not even working on the same assignment! :: One thing I like to stress is code modularity (like you mentionned): Use fonctions/methodes. One function/methode should do a single thing, and do it well. Also, stick to your organisation's coding standard. If you don't have one, you might want to consider making one. It makes reading co-workers' code soooo much easier! Ammo PS: Heh, this makes me think it's been a quite a while since I have written significant code... I just realized I miss it... Credit travels up, blame travels down -- The Boss good tutorial for people who already know how to write programs ... but not for newbies. No offense. Cause i like ya zepherin Forum Rules
http://www.antionline.com/showthread.php?230493-Basic-Program-Logic-and-good-programming-practices
CC-MAIN-2017-51
refinedweb
1,129
65.15
Red Hat Bugzilla – Bug 78565 evo 1.2 "override namespace" broken Last modified: 2008-05-01 11:38:04 EDT evolution-1.2-3 from rawhide exhibits the following strange IMAP behavior: previous version(s) of evolution (1.0.x_ I had an IMAP namespace of Mail/ (a Mail/ folder in my home directory). In evolution 1.2, no folders in Mail/ appear, even though I have (previously) subscribed to them... If I uncheck "override namespace" then a folder named Mail/ appears in my IMAP list of folders, and it does contain all my subscribed mailboxes. It seems that there is a problem with the "Override namespace" option. See also the ximian bugzilla report at I filed Bug 78252 describing this behavior. katzj@redhat said that this was an intentional change and closed the bug to WONTFIX, which I think is strange since the behavior is indeed BROKEN by any definition. The nesting as Michael describes is intentional. Some of the namespace has changed in 1.2.1 after feedback on the evolution lists which should handle what you're seeing I believe I hope you're right about evo 1.2.1, because as it is, evo-1.2's imap/namespace behavior is different (imo, broken) than *every* other imap client I've used including ms outlook, ms outlook express, netscape communicator, mozilla mail, pine... Has anyone tried out the new release? I've been leary on taking the step forward since 1.0.8 acts funny with every downgrade (done two so far). I've checked the Ximian bugzilla and there has been no apparent progress on the bug. Evolution 1.2.1 namespace seems to work properly for me. I use IMAP with uw-imapd, all of my mail folders are subscribed within ~/mail/. You could easily backup your home directory and try an upgrade. If things go horribly wrong you can revert easily. After upgrading to evo 1.2.1 (using rawhide's evo-1.2.1-2), I see no change in behavior. Any setting/use of "override namespace" results in *all* my subscribed folders disappearing. Ack. The ximian bug report has had no positive activity, other than others reporting they see similar brokeness. This certainly is not fixed. Warren, you say ~/mail is working for you. What to you enter in the override namespace option? mail/? ~/mail? I'm trying to use ~/Mail, and I've not had any success using any of: Mail, Mail/, ~/Mail, ~/Mail/. Ximian's Bug, 33879, appears to be stopped in the water due to a preference set forth by the maintainer. Since the one person who is in charge of the component refuses to fix the problem because of a personal preference (disagreeing that the behavior which differs from all major IMAP clients is incorrect), there does not seem to be a solution to be made available any time soon. Is there not a patch that Red Hat can provide to change this odd, and unwanted behavior before it gets shoved into the lap of the 8.1 users who cannot use 1.0.8 instead?
https://bugzilla.redhat.com/show_bug.cgi?id=78565
CC-MAIN-2016-50
refinedweb
519
75
Timeline 05/26/10: - 23:36 Changeset [62256] by - Use forward slashes in path parameters to xsltproc. This should hopefully … - 22:39 Changeset [62255] by - add test for internal domain deduction utilities - 21:53 Changeset [62254] by - python_extensions - removed const_aware::registry, replaced with … - 21:25 Ticket #3700 (boost::archive should support basic_strings with different allocators) reopened by - Hi, The problem here is that we have our string object defined as: … - 21:16 Ticket #4264 (boost multi_index hashed_unique erase takes linear time) created by - Hi, We are using a multi_index with several hashed_unique indices. We … - 18:08 Changeset [62253] by - added minkowski sum tutorial - 17:37 Ticket #4263 (Inconsistency between boost::trim_copy_if and trim_copy?) closed by - wontfix - 17:35 Ticket #4262 (Inconsistency between boost::algorithm::trim_copy_if and trim_copy?) closed by - wontfix - 17:31 Ticket #4263 (Inconsistency between boost::trim_copy_if and trim_copy?) created by - Is there any reason why boost::trim_copy_if supports an overloaded version … - 17:10 Ticket #2762 (impossible to build boost 1.38 for iphone) closed by - fixed: (In [62252]) Add detection of LITTLE/BIG_ENDIAN for GCC versions that … - 17:10 Changeset [62252] by - Add detection of LITTLE/BIG_ENDIAN for GCC versions that define them. … - 16:56 Ticket #4262 (Inconsistency between boost::algorithm::trim_copy_if and trim_copy?) created by - Is there any reason why boost::algorithm::trim_copy_if supports an … - 15:34 Changeset [62251] by - Fix version check, as g++ 4.1 still has the PCH bug. Refs #4172. - 15:05 Changeset [62250] by - Time Series Library deemed orphaned. - 15:05 Changeset [62249] by - Bring the boost.jam module up to date - 14:18 Changeset [62248] by - Resolve the ambiguity between the zero argument make_shared and the … - 14:06 Changeset [62247] by - Handle cygwin vs. windows paths for doxygen - 13:49 Changeset [62246] by - DWORD is unsigned long, not unsigned int. Refs #4217. - 13:43 Changeset [62245] by - Applied patch for Sun C++. Refs #4199. - 13:34 Ticket #4108 (C2139 error in VS2010) closed by - fixed: (In [62244]) Merge [61344] to release. Fixes #4108. - 13:34 Changeset [62244] by - Merge [61344] to release. Fixes #4108. - 13:25 Changeset [62243] by - Merge [61574], [61575], [61579] to release. - 13:24 Changeset [62242] by - Review Wizard report for may 2010 released. - 13:03 Ticket #4261 (bug? with boost::find_format_all, boost::regex_finder and custom regex ...) created by - I have a code that has been working for almost 4 years (since boost 1.33) … - 12:30 Changeset [62241] by - Fixed test compilation with C++0x aware compilers. The bind and ref calls … - 11:50 BoostDocs/GettingStarted edited by - Add instructions for Windows command prompt with Cygwin tools (diff) - 10:43 Ticket #4260 (core dump restoring simple archive on 64-bit Solaris) created by - When restoring a simple archive with 4 integers, I get a core dump when … - 10:22 Changeset [62240] by - Import the out-xml rules to the global module so they can be found by … - 08:58 Ticket #4259 (Reference leak in boost::python::function::add_to_namespace()) created by - In libs/python/src/object/function.cpp, there is an obvious reference … - 08:48 Changeset [62239] by - Fixed boost::process::detail::file_handle::win32_dup() - 08:18 Changeset [62238] by - Fix stupid bug, that broke using xsltproc ; - 07:54 Changeset [62237] by - done class matrix - 06:40 Ticket #4015 ([PATCH] boost/program_options gcc warning cleanup) closed by - fixed: (In [62236]) Fix -Wshadow warnings. Closes #4015. Patch from Tatu Kilappa. - 06:40 Changeset [62236] by - Fix -Wshadow warnings. Closes #4015. Patch from Tatu Kilappa. - 05:55 Ticket #3190 (Boost doesn't build on solaris when compiled with libCstd - focus on ...) closed by - wontfix: Unfortunately, it does not seem like I'll have the time to minimize the … - 05:51 Ticket #4069 (Minor mistakes in documentation) closed by - fixed: (In [62235]) Fix types. Closes #4069. - 05:51 Changeset [62235] by - Fix types. Closes #4069. - 05:49 Ticket #3931 (Build boost libraries under HP-UX with GNU C/C++) closed by - wontfix: I am not planning to do anything further. It's compiler problem. - 05:47 Ticket #4138 (Typos in the program_options' docs) closed by - fixed: (In [62234]) Correct typos. Closes #4138. - 05:47 Changeset [62234] by - Correct typos. Closes #4138. - 04:34 Changeset [62233] by - python_extensions - fixed typo in const_aware test - 04:26 Changeset [62232] by - python_extensions - disabled Python no-arg construction for … - 03:47 Changeset [62231] by - Add some missing includes for the parameter library - 03:20 Changeset [62230] by - license and as_mpl_map - 02:48 Changeset [62229] by - Added missing inline - 02:15 Ticket #4258 (Linking with boost thread does not work on mingw/gcc 4.5) created by - Errors: … - 00:07 Changeset [62228] by - Windows CE does not support returning from functions inside the … 05/25/10: - 23:39 Changeset [62227] by - Add some missing files - 23:36 Changeset [62226] by - Checked in the correct Windows CE fix. - 23:27 Changeset [62225] by - - Windows CE does not have the _controlfp_s function - 20:42 Changeset [62224] by - brainstorming iterfaces - 20:39 Changeset [62223] by - python extensions - removed support for def_visitor in … - 20:38 Ticket #3994 (Duplicate error codes on broadcom 2.4 mips chipset) closed by - fixed: (In [62222]) Fix #3994, error values on some Broadcom chips - 20:38 Changeset [62222] by - Fix #3994, error values on some Broadcom chips - 20:31 Changeset [62221] by - Try to adjust the paths in boostbook_catalog.xml to be correct, whether … - 19:47 Ticket #3962 (filesystem operations.cpp calls std::malloc but does not include <cstdlib>) closed by - fixed: (In [62220]) Fix #3962 - 19:47 Changeset [62220] by - Fix #3962 - 19:33 Ticket #3910 (Boost.Filesystem operations_test failure with vacpp on AIX) closed by - fixed: (In [62219]) Fix #3910 - 19:33 Changeset [62219] by - Fix #3910 - 19:18 Ticket #3867 ([filesystem] filesystem::exists() improperly throws on windows when path ...) closed by - fixed: (In [62218]) Fix #3867, both for ERROR_NOT_READY and ERROR_INVALID_DRIVE. … - 19:18 Changeset [62218] by - Fix #3867, both for ERROR_NOT_READY and ERROR_INVALID_DRIVE. These happen … - 17:33 Changeset [62217] by - fixed const correctness of interface - 17:15 Changeset [62216] by - Look for docbook in /opt/local/share since that's the default installation … - 16:58 Changeset [62215] by - fixed gcc error when -fno-rtti set - 16:40 Changeset [62214] by - Use the same syntax highlighting that QuickBook? generates for the … - 14:44 Changeset [62213] by - Libraries added to 1.43. - 14:43 Changeset [62212] by - Always use forward slashes in arguments to xsltproc. The windows xsltproc … - 14:40 Changeset [62211] by - working on different interface ideas for both compile time runtime and a … - 14:28 Changeset [62210] by - Better autoconfiguration for BoostBook? - 14:11 Changeset [62209] by - Added Locale library. Results for Move pending. - 13:22 Changeset [62208] by - #if 0ed non-portable locker template code - 13:19 Changeset [62207] by - fixed Simple initializer. - 13:18 Changeset [62206] by - removed consistency_checking_string call (no longer exists). - 13:18 Changeset [62205] by - added init for thread bound objects. - 13:11 Changeset [62204] by - removed matching else from if (!already ...) - 12:16 Ticket #4257 (Improving invalid signature detection in binary iarchive) created by - Binary iarchive is supposed to throw invalid_signature archive_exception … - 12:15 Changeset [62203] by - Use new symbol visibility macros - 11:53 Changeset [62202] by - Decoupled arg_list and maybe. This removes a few dependencies on other … - 10:51 Changeset [62201] by - Update to use hidden visibility where possible. - 10:45 Changeset [62200] by - Change to use new symbol visibility macros. - 10:38 Changeset [62199] by - Add symbol visibility support to Intel and Sun compilers. - 10:22 Ticket #4223 (boost::python exception translator causes ambiguous call errors with ...) closed by - fixed: (In [62198]) Explicitly qualify bind with boost::. Fixes #4223. - 10:22 Changeset [62198] by - Explicitly qualify bind with boost::. Fixes #4223. - 08:45 Changeset [62197] by - Merge PropertyTree? to release branch. I'm not sure if this worked … - 07:57 Changeset [62196] by - Minor adaption of PTree tutorial to reality. - 07:54 Ticket #4245 (encode_char_entities does not handle empty string properly (affects ...) closed by - fixed: (In [62195]) Make encode_char_entities safe against empty strings, because … - 07:54 Changeset [62195] by - Make encode_char_entities safe against empty strings, because Graph uses … - 07:23 Changeset [62194] by - Fix unconditional use of non-standard glibc specific functions. - 07:03 Ticket #4256 (boost::make_shared() may issue stack overflow while constructing large ...) created by - By default stack size for windows executable is 1Mb. The program below … - 05:49 Ticket #4255 (Documentation: No overflow-checking in accumulators, no precision ...) created by - As discussed … - 04:50 Changeset [62193] by - boost.python extensions - partial rewrite of const_aware, using proxy … - 02:59 Changeset [62192] by - Minor changes - 01:52 Changeset [62191] by - Half of work done; Need to solve a nasty bug. - 00:48 Changeset [62190] by - added tests for embedded and buffered delete. - 00:38 Changeset [62189] by - added testBuffered - 00:17 Changeset [62188] by - fixed .dsw - 00:16 Changeset [62187] by - fixed is_only_reading and other functions. - 00:05 Changeset [62186] by - fixed is_only_reading and associated functions. - 00:00 Changeset [62185] by - added testBufferedDelete.cpp 05/24/10: - 22:55 Changeset [62184] by - Spirit: fixed #4253: Error with lex::_val, added test - 22:54 Ticket #4253 (Error with lex::_val) closed by - fixed: (In [62183]) Spirit: fixed #4253: Error with lex::_val - 22:54 Changeset [62183] by - Spirit: fixed #4253: Error with lex::_val - 20:18 Ticket #4254 (error_code.clear() documents incorrect new category type) created by - The documentation for error_code.clear() says postcondition: value() … - 20:12 Ticket #4253 (Error with lex::_val) created by - lex::_val matches the whole input string instead of token attribute only … - 18:43 Changeset [62182] by - Spirit: fixed a problem with lex::_val - 17:19 Changeset [62181] by - Removed order/closure elements because of dispatch cleanup (it is now as … - 16:52 Changeset [62180] by - Added ever_circling_range_iterator (range version) Small adaptions to … - 15:52 Ticket #4252 (Typoo in boost::asio tutorial) created by - At: … - 15:26 Ticket #4237 (Boost filesystem dynamic failure on darwin) closed by - fixed: (In [62179]) Apply fix #4237 uniformly to all shared builds, in the hope … - 15:26 Changeset [62179] by - Apply fix #4237 uniformly to all shared builds, in the hope that this same … - 14:40 Changeset [62178] by - fixed inspect errors - 14:17 Ticket #4251 (Interprocess failed to communicate in OS X 10.5.8 Leopard under 64 bit ...) created by - This issue only exists explicitly for OSX leopard 64 bits application … - 14:08 Changeset [62177] by - html redirect - 13:43 Ticket #4250 (Interprocess tmp folder permission denied problem) created by - shmData = new shared_memory_object ( create_only, … - 13:40 Changeset [62176] by - Fixed log ambiguity in VC++ 10 - 13:03 Changeset [62175] by - Moved order/closure outside dispatches, not necessary there / more … - 13:03 Changeset [62174] by - fix for diode misinformation and clarification of layout - 10:01 Changeset [62173] by - Jamfile update Fixed perimeter for non-closed rings - 09:54 Changeset [62172] by - Corrected closure for area Added closure for centroid Modified/fixed … - 07:31 Changeset [62171] by - Fixed syntax in equal / closing_iterator (will be iterator_facade) - 05:07 Changeset [62170] by - Added closed / closure Updated jamfiles - 01:55 Ticket #4249 (pin_to_zero should be inlined) created by - boost::detail::pin_to_zero in boost\thread\win32\thread_data.hpp should be … Note: See TracTimeline for information about the timeline view.
https://svn.boost.org/trac/boost/timeline?from=2010-05-26T05%3A49%3A29-04%3A00&precision=second
CC-MAIN-2016-07
refinedweb
1,860
51.07
Right View of a Binary Tree Introduction Let’s assume a scenario in which Ninja decides to move his point of vision to the right side of the tree instead of looking from the front of a binary tree. The right view of the binary tree would contain all the nodes present at the right face of a tree. This means that the nodes to be printed are the rightmost nodes in the tree. We will work on two different approaches to solve this problem. Let’s understand using an example what would be the right view of a binary tree. Just see in the above example the line of sight in the right direction. The right view of the tree wants the Ninja to observe all the nodes through the right and, in the above example, those visible nodes are - 10, 50, 100, 80, and 90. These nodes block the view of the rest of the nodes when the tree is viewed from the right direction, thus giving us only the rightmost nodes of the tree. The problem statement is, Given any binary tree print the right view of the binary tree. We can have two approaches to solve this problem. Let’s understand the concept a bit more before considering the algorithms. In the above figure, we know that the last node in each level of the tree is the right view of the binary tree. So instead of traversing the tree from left to right, we traverse each level from right to left. Let’s have a look at the tree, We can, therefore, say that the first node in this type of traversal is the right view of a binary tree. We have the first node of each level as follows - Right traversal of the tree:- Level 0 (root node) - 10 Level 1 - 50 Level 2 - 100 Level 3 - 80 Level 4 - 90 To obtain the above result, we have two types of traversals that can be used to solve the problem of the right view of a binary tree. - Recursive Traversal - Iterative (Level Order) Traversal Let’s go through the algorithms to understand the approaches mentioned above. Recursive Approach We will be solving the problem using reverse preorder traversal. The general preorder traversal means it follows the below structure - But we would reverse the structure because eventually, we only need the first rightmost nodes, Therefore we will convert the above structure to, The algorithm would use a concept of recursion as the node would pass for all right children and left children according to the level of the tree. Algorithm for Recursive Approach For this approach to find the right view of a binary tree, we will declare a variable level that we would set to 0. We will print all the nodes which are first to be visited when a new level is encountered in the tree. We will reverse the general preorder traversal and call right and then call the left child recursively and update the level whenever the function is called. This approach requires the reversal preorder traversal and the recursion concept to obtain the final result. Let’s go through the algorithm to understand the approach. //set level = 0 //set maxlevel = 0 level = 0 function RightView(node,level) { if(node == null) return //used to check if the level is traversed //or is being visited for the first time if(level == list.size) { Print the value of the node Set maxlevel = level } RightView(node->right, level+1) RightView(node->left, level+1) } Implementation in Java import java.util.*; public class Main { public static class Node { int data = 0; Node left = null; Node right = null; Node(int data) { this.data = data; } } static int idx = 0; static int max_level = 0; public static Node create_Tree(int[] arr) { if (idx == arr.length || arr[idx] == -1) { idx++; return null; } Node node = new Node(arr[idx++]); node.left = create_Tree(arr); node.right = create_Tree(arr); return node; } public static void RightView (Node node, int level) { if (node == null) return; if (max_level < level) { System.out.print(node.data + " "); max_level = level; } RightView(node.right, level + 1); RightView(node.left, level + 1); } public static void viewSet(Node root) { RightView(root,1); } public static void solve() { int[] arr = {10,20,30,-1,-1,40,-1,-1,50,60,70,-1,-1,80,90,-1,-1,-1,100,-1,-1 }; System.out.println("Using Recursion Method"); Node root = create_Tree(arr); viewSet(root); } public static void main(String[] args) { solve(); } } Output Using Recursion Method 10 50 100 80 90 Time Complexity: The Time Complexity of the above approach to find the right view of a binary tree is O(N), where N is the number of nodes in the binary tree. Space Complexity: The Space Complexity of the above approach to find the right view of a binary tree is O(H), where H is the height of the binary tree. In case of skewed trees the height of the tree can become N which gives a worst of O(N). Iterative Approach We will solve the problem by using the classic level order traversal and the queue data structure. So, to perform Level Order Traversal, the nodes would be considered level-wise. This means that each node would access the child at each level before moving to the next level. We have these nodes respective to each level, Level 0 - 10 Level 1 - 20, 50 Level 2 - 30, 40, 60, 100 Level 3 - 70, 80 Level 4 - 90 Notice the last node in each level is the node that is to be printed for the result. Algorithm for Iterative Approach In the algorithm, we would do a level order traversal of the tree and would print the last node of each level. Since we will iterate using a for loop for each node in the level this approach is known as an Iterative Approach. We will use a queue as a data structure to store the last nodes for each level. We will be using the poll function of the queue to find the last element of the level. We will check the element’s position if it’s the previous element using the size of the queue. Now let us go through the algorithm for an iterative approach that is used to display the right view of a binary tree. enqueue root while queue is not empty { // find the length of the queue int size = queue.size() // run a loop from 0 to size for(i =0, i<size, i++) { dequeue root //check if the element is present at last if(i==size-1) { print node.data } enqueue left child enqueue right child } } Implementation in Java import java.util.*; public class Main { public static class Node { int data = 0; Node left = null; Node right = null; Node(int data) { this.data = data; } } static int idx = 0; public static Node create_Tree(int[] arr) { if (idx == arr.length || arr[idx] == -1) { idx++; return null; } Node node = new Node(arr[idx++]); node.left = create_Tree(arr); node.right = create_Tree(arr); return node; } public static void RightView(Node node) { Queue<Node> que = new LinkedList<>(); que.add(node); while (que.size() != 0) { int size = que.size(); for(int i =0;i<size;i++) { Node n = que.poll(); if(i== size-1) { System.out.print(n.data + " "); } if(n.left !=null) { que.add(n.left); } if(n.right != null) { que.add(n.right); } } } } public static void solve() { int [] arr ={10,20,30,-1,-1,40,-1,-1,50,60,70,-1,-1,80,90,-1,-1,-1,100,-1,-1 }; Node root = create_Tree(arr); System.out.println("Using Iterative Approach"); RightView(root); } public static void main(String[] args) { solve(); } } Output Using Iterative Approach 10 50 100 80 90 Time Complexity: The Time complexity of the Iterative Approach to find the right view of a binary tree is O(N), where N is the number of nodes in the tree. Space Complexity: The Space Complexity of the Iterative Approach to find the right view of a binary tree is O(N), where N is the number of nodes in the tree. Frequently Asked Questions - What is the Right view of a Binary Tree? The right view of a binary tree means to print all the nodes visible when the tree is seen from the right direction. The final output would have the nodes, which are the most rightmost in a tree, as these nodes hide the rest of the nodes. When a person limits his line of sight in a single direction, only nodes visible in that area would be visible to him. The right view of a Binary Tree consists of nodes which are the rightmost nodes in a tree. - Which approach is better to find the right view of a binary tree? The recursive approach is better than the iterative approach as a limited space of O(H) is used in the algorithm, where H is the tree’s height. Whereas the Iterative algorithm uses level order traversal, the worst case in a level order traversal is a lot more than the recursive approach. - What is a right-skewed binary tree? A right-skewed binary tree in which all the nodes have the right child or no child at all. A right-skewed binary tree is also known as a right dominating tree. The below image is an example of a Right skewed Binary Tree. - How will you calculate the space-time complexity for a skewed binary tree for a recursive approach? The time complexity of the recursive approach would be O(N) where N is the size of the tree. In this case, instead of a general binary tree, we are given a skewed binary tree therefore, the tree’s height would be the same as the size of the tree as there are no elements in the left section of the binary tree. Hence, in this case, the Space complexity would be O(N) in the recursive approach. Key Takeaways In this blog, we learned how to find the right view of a binary tree and how we can use different approaches to solve this problem. - In the first approach, we used recursion and reverse preorder traversal to find the right view of a binary tree. We declared a variable level that would be set to 0. We would then print all the nodes which are first to be visited when a new level is encountered in the tree. To do so, we would reverse the general preorder traversal and call right and then call the left child recursively and update the level whenever the function. This approach requires the reversal preorder traversal and the recursion concept to obtain the final result. - In the second approach, we used a level order traversal and a queue to solve the problem. We declared a queue that would be used to iterate through each level and find the last node for each level, which we would eventually check with the size of the queue, and if the element is placed at the last of that particular level, we will print the node. This would be called for the left child nodes and the right child nodes. The two key concepts involved in this approach are level order traversal and Queues. If you want to learn about finding the left view of a binary tree, we have a separate article that covers the approaches used to solve the problem. Do give it a read. Visit here to learn more about trees. And practice similar problems on CodeStudio. If you liked this blog, share it with your friends.
https://www.codingninjas.com/codestudio/library/right-view-of-a-binary-tree
CC-MAIN-2022-27
refinedweb
1,935
68.81
In this part of the "Learning Flask" series, we're going to working with query strings. A query string is part of the URL as a string of parameters and values and are used ubiquitously across the web. Query strings are essentially a string of key/value pairs sent by the client to the server. Here's an example of a query string in the URL from a quick Google search for query string: Let's break down the URL: httpsis the protocol the domain /searchis the path ?q=query+stringis the query string Anatomy of a query string Focusing on the query string element of the URL, we see the following components: ?starts the query string qis the first parameter =separates/assigns a value to the parameter query+stringis the value assigned to the qparameter You'll notice the + substitution between "query string". This is because the space charactes is not allowed in a URL so must be replaced with something else. Spaces in query strings are replaced with + or %20 Let's take a look at a slightly more complex query string, again from a Google search for "flask": If you take a closer look at the query string, you'll see multiple parameters and values, separated by the & symbol. We use & to separate parameters and values in the query string. Let's create a query string below with a few sets of params & values: Let's use this query string in our Flask application and learn how to work with it! Flask query strings First up, let's create a new route with the URL /query: app/app/views.py @app.route("/query") def query(): return "No query string received", 200 If you got to /query in your browser, you'll see No query string received in your window. Go ahead and paste the query string we just created above into your browser URL bar and see what happens. You'll notice we don't get any errors, however we're not yet doing anything with our query string. Let's go ahead and serialize it! Serializing query strings To work with any kind of request object or data, we need to import request from flask: app/app/views.py from flask import request Just like we've used request.form for serializing form data and request.get_json() to serialize incoming JSON data, we use request.args to parse and serialize the query string into a Python object. Let's store our query string object as a variable called args and print them: app/app/views.py @app.route("/query") def query(): args = request.args print(args) return "No query string received", 200 Save and reload that same URL with the query string, you'll see the following in your terminal: ImmutableMultiDict([('foo', 'foo'), ('bar', 'bar'), ('baz', 'baz'), ('title', 'query strings with flask')]) request.args has parsed our query string and conveniently converted it into an ImmutableMultiDict which we can treat just like a Python dictionary, for example, change print(args) for the following: app/app/views.py for k, v in args.items(): print(f"{k}: {v}") You'll see our keys and values printed out to the console: foo: foo bar: bar baz: baz title: query strings with flask Just like a dictionary, we can now pluck out values by their key: @app.route("/query") def query(): args = request.args if "foo" in args: foo = args["foo"] if "bar" in args: bar = args.get("bar") if "baz" in args: baz = args["baz"] if "title" in request.args: title = request.args.get("title") print(foo, bar, baz, title) return "No query string received", 200 However at this point we'll get an error if we don't send a query string with values for foo, bar, baz and title. Let's refactor our code to mitigate any potantial errors and return a formatted query string to the client: @app.route("/query") def query(): if request.args: # We have our query string nicely serialized as a Python dictionary args = request.args # We'll create a string to display the parameters & values serialized = ", ".join(f"{k}: {v}" for k, v in request.args.items()) # Display the query string to the client in a different format return f"(Query) {serialized}", 200 else: return "No query string received", 200 If you re-submit the URL, you'll see: (Query) foo: foo, bar: bar, baz: baz, title: query strings with flask And that pretty much wraps things up for query strings with Flask! Extras Although I've not found much use for them in the past, the request object also provides us with a few more features for working with query strings. request.query_string will return the query string, for example: @app.route("/query") def query(): print(request.query_string) return "Thanks", 200 Will return: b'foo=foo&bar=bar&baz=baz&title=query+strings+with+flask' request.values will return a CombinedMultiDict which comines args with form, for example: @app.route("/query") def query(): print(request.values) return "Thanks", 200 Returns: CombinedMultiDict([ImmutableMultiDict([('foo', 'foo'), ('bar', 'bar'), ('baz', 'baz'), ('title', 'query strings with flask')]), ImmutableMultiDict([])]) Not something I've used in the past but can imagine it would be useful to submit a form with query string parameters in the URL. Wrapping up Query strings are a convenient way to pass arguments to your application and Flask makes light work of quickly parsing them into something we can work with. POST requests don't typically include a query string as they tend to include data that you want to keep within the request body, so you'll mostly be using them with GET requests.
https://pythonise.com/series/learning-flask/flask-query-strings
CC-MAIN-2021-17
refinedweb
943
69.92
Are Web Services the New CORBA? I am updating the “External Services” chapter inCore JSF. There is lots of new and interesting stuff: How to use JPA, stateless session beans, and WebBeans. I ditched the LDAP sections (for which I had received very few queries, even though the examples are notoriously hard to set up). I reimplemented the authentication example with a JDBC realm, which wasno fun. Now I am at the web services section. In the previous edition, I used the Amazon e-commerce service that lets you browse the Amazon catalog. It is pretty simple, really. Inject the service into a managed bean: @WebServiceRef(wsdlLocation= "") private AWSECommerceService service; Then call the service API. Generate the client-side artifacts: wsimport -p com.corejsf.amazon... cvf aws.jar com/corejsf/amazon/* Put the JAR file into WEB-INF/lib. Deploy, and it just works. Except that Amazon has repositioned the API as a “product advertising API”, and you now need to be an “Amazon associate” to use it, which makes it less suitable for a book example. Now what? I found a couple of web services directorieshere andhere. SOAP services seemed pretty pathetic. Mostly vendor and academic demos. Amagic square finder? Please... There were two useful services that seemed to have a chance of being long-lived. The NOAA weather service and Microsoft Bing. Ok, let's make those client-side artifacts: wsimport -p com.corejsf.noaa parsing WSDL... [ERROR] rpc/encoded wsdls are not supported in JAXWS 2.0. line 405 of wsimport -p com.corejsf.bing parsing WSDL... [ERROR] A class/interface with the same name "com.corejsf.bing.SearchRequest" is already in use. Use a class customization to resolve this conflict. line 1 of [ERROR] (Relevant to above error) another "SearchRequest" is generated from here. line 1 of (followed by seven more errors) WT-*? Aren't these supposed to be interoperable? Am I beating a dead dog here?This article describes research on finding web services. In 2008, they found a few thousand services, most of which didn't seem to work. Are WS-* services the new CORBA? I know there are lots of interesting RESTful services out there. The only drawback for me is (1) the data comes back as some ad-hoc XML, RSS, or JSON, and I have to deserialize it by hand and (2) there is no connection to JSF. If you can point me to an interesting WS-* service that is free to use, likely to stay around for a few years, and has a WSDL that wsimport can process, I would very much appreciate if you leave a comment. Or, talk me into dropping the web service section altogether. - Login or register to post comments - Printer-friendly version - cayhorstmann's blog - 4935 reads by stephenconnolly - 2009-07-16 11:09AFAIK, the IETF is kind of opposed to SOAP... (at least off the record, perhaps on the record)... that might have something to do with the demise of the whole WS-* stack... The other issue is that you really need to ensure you are using the 2.1 version of the WS apis from sun by jitu - 2009-07-30 11:05I posted the standard jax-ws customization for bing's wsdl in : by jitu - 2009-07-28 14:26There is a conflict in the generated artifact names for the bing wsdl. Standard way is to pass a JAXB customization using -B switch to resolve the conflicts. There is also an unsupported switch that should allow you to resolve the conflicts. The following works for bing wsdl. % ~/jdk1.6.0_14/bin/wsimport -B-XautoNameResolution rpc/enc WSDLs are not supported by JAX-WS. WS-I BasicProfile doesn't support them either. There may be some old rpc/enc based services, but they should move to doc/lit by m_potociar - 2009-07-28 13:59There are two things in your blog that I am concerned about: First of all, if you can't find it, it does not necessarily mean that it does not exist (or is not being used in our case). As you were not able to find a suitable freely accessible SOAP web service sample for your book, you simply concluded that SOAP services are dead. Well, frankly, I miss some logic behind such conclusion. In my opinion SOAP services are these days mostly used within enterprises or as B2B interfaces. These are typically neither free nor public. Could that be the reason why it is harder to find a public and freely accessible SOAP based WS? Btw. for most simple and public web services, where the service is really just about exposing some resources and not about messaging, REST is a more natural and convenient choice anyway, so why would anyone expose such service as SOAP? And secondly, you confuse web services (WS) with WS-*, which is a set of standardized specification to enable advanced features on SOAP based services, such as message level security, reliability or transactions in an interoperable way. These are enabled via so-called WS-Policy expressions attached to standard WSDL elements. Neither of your WSDLs (Amazon, NOAA Weather, Bing) contain such expressions, so those services are not WS-* enabled, so to say. Also, are you sure that those WSDLs are compliant with WS-I Basic Profile? In case you are not familiar with WS-I BP, it is a profile specification which if followed, should guarantee interoperability among different WS stacks? If not, why do you expect them to be interoperable? SOAP web services are not a cure for everything and certainly not a suitable technology for all situations. No doubt, there's a potential for an improvement in all existing SOAP WS stacks to make the SOAP based services development a smoother process. Yet this technology has its place in the IT world where it does a great job. And you should probably get some deeper insight before making such strong public statements. by graham_king - 2009-07-10 22:30Yes drop it entirely. WS-* went the way of EJB 2. The SOAP vs REST debate has been and gone. Some highlights I bookmarked:... by weberjn - 2009-07-10 04:01You'd be hard pressed to make CORBA as slow as web services ... CORBA is an efficient and mature technology and there are great open source implementations (JacORB, TAO, IIOP.NET) and they are all interoperable. see:... by cayhorstmann - 2009-07-09 19:56Taylor: Those genonames.org services are all very nice. And none of them uses WS-*. BTW, I found this Netbeans tutorial:. It uses a spell checker web service from a company that sells web service hosting, and apparently the price to pay was an infomercial for that company in the tutorial. That service is no longer supported, but they now have a rather amusing "profanity remover": by tcowan - 2009-07-09 18:35I can identify with your sentiments, as do perhaps many others. I think the interop story between Glassfish and MS is good, but probably too little too late for the masses. Although REST is essentially arbitrary XML, Atom is not, and as the protocol layer for Gdata, has some potential. AtomPub adds commonality on how collections are grouped, paged, and updated. Btw, geonames.org has some very well crafted webservice api's of various flavors and does not require special authorization. see geonames.org Taylor by cayhorstmann - 2009-07-09 15:26Nope, that stock quote service isn't compatible with JAX-WS either. It may well be that wsimport is the culprit here, but the point of the section was how easy it is to inject a JAX-WS port into a JSF managed bean. wsimport -p com.corejsf.ws parsing WSDL... [WARNING] src-resolve.4.2: Error resolving component 's:schema'. It was detected that 's:schema' is in namespace '', but components from this namespace are not referenceable from schema document ''. If this is the incorrect namespace, perhaps the prefix of 's:schema' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to ''. line 68 of?... [ERROR] undefined element declaration 's:schema' line 68 of [ERROR] undefined element declaration 's:schema' line 81 of (The workaround at didn't work for me either.) by cayhorstmann - 2009-07-09 12:00@kromagg: Thanks for the tip. I tried processing the WSDL, but it didn't work. Sigh... wsimport -p com.corejsf.ebi parsing WSDL... [WARNING] src-resolve: Cannot resolve the name 'soapenc:Array' to a(n) 'type definition' component. line 10 of [ERROR] undefined simple or complex type 'soapenc:Array' line 10 of [ERROR] undefined attribute 'soapenc:arrayType' line 11 of by kromagg - 2009-07-09 10:19They're generally not very interoperable. Personally I think the heavy focus of the major vendors (Microsoft, Sun, IBM) on automatically generated XML bindings has damaged this supposedly XML based standard beyond repair. You can do it *right* too, but it requires a lot more work, and you're forever following some rules of thumb. Don't think I've ever met a developer who can claim they really know what's in WS-I. In any case, web services are quite popular in the bio-informatics world, check out the ones from EBI maybe: Unfortunately it's a little domain-specific, the dbfetch service might be good for pulling down some gene sequences. by felipegaucho - 2009-07-09 08:15If the book is just about the client technologies (and not in deep about ws-*) I recommend you to include a toy example .. I know it is boring to read a book based on too simplistic demos, but in your case and tricks to consume the service seems more relevant than the service itself. And Metro technologies make it so easy to expose a bean as SOAP web-service that I think a page or two showing how to do that may be enough. Just add a downloadable demo to your book and it will be useful in a long term.. IMO: the most complicated features involving WS-* + JSF are: - HTTPS - security is always a mess from the client-side perspective, specially if you are using tokens and not basic auth.. - Binary data, large volume of data being transferred between the service and the client.. timeouts, etc - Exception handling in the client side. by cayhorstmann - 2009-07-09 07:55Carol: I too can continue to demonstrate the Amazon service, but for you to replicate it, you have to become an Amazon associate. It's just not something that I want to require a reader of our book to do. by caroljmcdonald - 2009-07-09 07:35at JavaOne Harold Carr demonstrated connecting to Amazon's web services with a JAX-WS client by felipegaucho - 2009-07-09 05:16ops, the right URLs should have a ?wsdl at the end: business:... admin:... by felipegaucho - 2009-07-09 05:01if you just want to try, my pet project contracts: business:... admin:... and then you can check the result in the reference implementation JSF client: * This contracts are alive for more than a year now.. and I plan to invest a few more bytes on it .. but, yes, my pet project will probably disappear in a few years range.... * I agree with you that WS-* is kind of being decomissioned in the market...perhaps because the big hypes are going in the opposite direction.. SUN and MS seems to be the only big companies interested in to develop WS-*... google, yahoo and any other browser-centric company is just ignoring the SOAP as a serious option.. and I tought that in few years we can see the RESTful generation to regret or to review their current bliefs, because REST impose other problems that are nor solved neither discussed nowadays.. let's wait the hype to dissipate and check again in onw or two years..... :) by jashatton - 2009-07-08 18:19When I first saw Web services I was working on an internal CORBA app. I was surprised at how similar things were. Web services was a good first few steps but, like most IT problems you have to go through a few solutions before you find the right fit. I think REST feels like the right solution evolved by the people who have felt the pain of web services. It is natural to HTTP and like mentioned already it is easy to either use a parsing library or provide a client library to the user. Heck why not provide the spec and let them choice even better I say. by cayhorstmann - 2009-07-08 11:20David, I can easily do that, and it isn't rocket science to parse a simple XML or JSON file. But there is nothing JSF-specific about that, so I am not sure it has a place in the book. I'll consider your post as a vote for the "dead dog". by dwalend - 2009-07-08 10:50Cay, I think you hit the nail on the head with "Are WS-* services the new CORBA?" Web Services is trying to solve a problem harder than CORBA took on, with better tools, for similar results. Web services works OK for when you control and can change both ends of the wire. That's most of where you'll see it used, the same as CORBA. Designing a protocol for anything but very specific uses is very hard. And, just like CORBA, putting WS-* in the core libraries hasn't paid off. Few people need them. WS-* is a growing standard. The people who do want to use them may be using a different version than the one supported by the standard libraries, so they have to bring in their own .jar files anyway. Same as with CORBA. Most of your readers will be able to get to the internet. Can you pick a restful service, put a parser in a .jar for your readers to download, and make the section of the book just reference that API in a JSF example without showing the details in the parser? Maybe one of them already has a Java parser for you.
https://weblogs.java.net/blog/cayhorstmann/archive/2009/07/are_web_service.html
CC-MAIN-2015-35
refinedweb
2,356
64.71
Tools to add and a verify a cryptographic signature to WARC (or any gzip-chunked) files This package provides complemetary warc-sign tool which signs WARC(s) with an RSA signature and warc-verify which verifies that the WARC(s) have been signed. Install with: python setup.py install Tests can be run with: python setup.py test To sign a warc: warc-sign privatekey.pem my-warc-file.warc.gz To verify that a warc has been signed: warc-verify publickey.pem my-warc-file.warc.gz warcsigner can be used from other scripts. To sign a warc: from warcsigner.warcsigner import RSASigner signer = RSASigner(private_key_file='privatekey.pem') if signer.sign('my-warc-file.warc.gz'): # warc signed successfully or to verify: from warcsigner.warcsigner import RSASigner signer = RSASigner(public_key_file='publickey.pem') if signer.verify('my-warc-file.warc.gz'): # signature verified else: # signature not found/invalid the sign and verify methods can take either a filename string or a file-like stream object (an object with a read method) Additionally, upon verification, the signature can be removed: if signer.verify('my-warc-file.warc.gz', remove=True): # signature verified and removed assert signer.verify('my-warc-file.warc.gz') == False If the first verify succeeds, the signature will be removed and file truncated to its previous pre-signature size. (The file is unaltered if the verification fails). This may be useful if planning to append to the WARC and then resigning it. It is possible to use a file-like object which supports a read() instead of a filename. When a WARC is signed, the signature is appended to the end of the file. When verifying a file, the seek() may be used to determine the file size and the position of the signature. However, if a size= param is added to verify or verify_stream calls, no seek() calls are made during the verification and the file-like object is consumed linearly. This is specially useful when streaming a file from a remote location and seek() is not available. The total file size must be provided, though. Public/Private keys are expected to be in .PEM format See the python-rsa formats doc for more information on supported key formats. In certain situations, it may be useful to return the original, unsigned stream from a signed stream. signer.get_unsigned_stream(stream, size) will return a wrapper for stream which will not include the signature (if present). This is useful if concatenating WARCs without including a signature (and empty record) for each one. The python-rsa library is used to sign and verify the signature. The signature is stored in an extra gzip chunk containing no data but using custom extra field to store the signature. This allows the verify tool to quickly access the signature by checking a fixed offset from the end of the WARC. When decompressing gzip chunks, there should be no detectable difference as most gzip tools ignore the extra gzip header. While this is designed for compressed WARCs, this can be used for any format consisting of concatenated gzip chunks, ARC files, etc… Note: since the signature is a gzip block, it makes less sense for uncompressed / plain text.
https://pypi.org/project/warcsigner/
CC-MAIN-2016-44
refinedweb
534
56.96
Expand | Embed | Plain Text - #include <iostream> - #include <fstream> //this includes the necessary functions for file IO - #include <string> - using namespace std; - - /* Here is another important topic. File input-output. - - In this program we are going to see how to open a text file, write something and then - read this file. - - The file IO operations are done via streams, similarly to the way we did it for input - and output in the console. However I must note that this is the case when writing files - and data in text format. We are going to see binary files later. - - As we said we use streams. Therefore we use the '<<' and '>>' operators. The main logic - is this: - - 1)We create a stream suitable for an input or output file - 2)We open a file and link it to the stream we created. This file must be either - for input or output and it must agree with the stream type - 3)We use the '<<' or '>>' operators to write or read in/from the stream/file - 4)We close the stream/file/ - - See the code below to get how this is done. What we are doing in this program is that - we ask the user whether he wants to create a new file with his name and age inside or - see what has already been stored in the file. According to the user's choice we either - open a new file to write in(if this file exists it is overwritten) and write his name - and age or open an existing file (if it exists) and read his name and age. - */ - - int main() - { - string name;//Variables that hold the users name and age - double age; - int choice;//A control variable for the user's choice - - //We ask the user what he wants to do - cout<<"What do you want to do?n"; - cout<<"(1) Write a file with your name and agen"; - cout<<"(2) Read from a file your name and agen"; - cin >> choice; - - if (choice==1){//The user wants a new file - - cout<<"Please enter your name:n";//we ask the user for this name and age - cin>>name; - cout<<"Please enter your age:n"; - cin>>age; - - //We create a new stream to an output file. Note the type is 'ofstream' meaning - //a stream to a file for output. The name of this variable is the name of the used - //stream and for us it holds the name to the file (but not the filename) - ofstream output_file_stream; - - /* Here we open a new file named 'file1.txt' using the 'open()' function of the - stream. Note that we enclose this function in an 'if' statement. We do that because - if the 'open()' function fails to open the file then it returns a 'false' otherwise - if all goes well it returns a 'true'. So we use this if to inform the user as to how - the opening of the file went. Alternatively we can use the 'is_open()' function which - returns true if a file is open and false if is not. the syntax is 'file_stream.is_open()' - - Note the syntax of the open statement: - - file_stream_name.open(filename,input_or_output_identifier) - - filename: the fact that we are going to write text in the file doesnot mean that - the extension must be txt. It could be .dat or nothing at all or anything - input_or_output_identifier: this lets the compiler know how we are going to use this - file. We want to write in the file so we use ios::out. - These identifiers are members of the 'ios' namespace and - therefore we user the '::' operator. - - There are many identifiers but we use here only 'ios::out' which means we open - a file to write in (output file) and 'ios::in' which means we open a file to read - from (input file) - */ - - if (output_file_stream.open("file1.txt"),ios::out) { - - - /*Note that we use the stream to the file with the '<<' operator to write - * anything we want inside just like we used the 'cout' stream for the console - * - * IMPORTANT: note the usage of 'n' between the variables. This is neccessary to distinguish - * the different variables. BEWARE: The usage of 'endl' instead of 'n' does NOT work - */ - output_file_stream<<name<<"n"<<age; - //output_file_stream<<age; - } - else cout<<"The file could not be openedn"; - - //We close the file to complete the IO operation - output_file_stream.close(); - } - else if (choice==2){ - - ifstream input_file_stream; - /* Here the only difference from above is that we open a file that should already - exist. If it doen't then the 'open' function returns a false and the program stops - with an error. - If it does then we read the data with the same order as when we wrote it and we place - that data in their variables.*/ - if (input_file_stream.open("file1.txt"),ios::in){ - input_file_stream>>name; - input_file_stream>>age; - - //We print the data from the file - cout<<"Your name is '"<<name<<"' and you age is "<<age<<endl; - - //We close the file - input_file_stream.close(); - - - } - - else - cout<<"The file could not be openedn"; - - } - return 0; - } - Report this snippet Tweet
http://snipplr.com/view/29668/
CC-MAIN-2015-11
refinedweb
829
75.13
Suppose you are on Let's Make a Deal and you are playing the Monty Hall Game, with one twist. Before you went on the show you analyzed tapes of previous shows and discovered that Monty has a tell: when the contestant picks the correct door, Monty is more likely to blink. Of the 18 shows you watched, the contestant chose the correct door 5 times, and Monty blinked three of those times. Of the other 13 times, Monty blinked three times. Assume that you choose Door A. Monty opens door B and blinks. What should you do, and what is your chance of winning? To get started, let's review the standard version of the Monty Hall problem (from Wikipedia): "Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say A [but the door is not opened], and the host, who knows what's behind the doors, opens another door, say B, which has a goat. He then says to you, "Do you want to pick door C?" Is it to your advantage to switch your choice?"We can solve this problem using Bayes's Theorem. There are two relevant hypotheses: A: the car is behind door A C: the car is behind door C Before Monty opens door B, the prior probability for both hypotheses is 1/3. Now the evidence is E: Monty opened door B. To compute the posterior probabilities, we need the likelihoods P(E|A) and P(E|C). P(E|A) is the probability of the evidence if the car is behind door A. In this case Monty has a choice; he could have opened door B or C. In the canonical version of the problem, he chooses at random, so P(E|A) = 1/2 P(E|C) is the probability of the evidence if the car is behind door C. In this case Monty has no choice, so P(E|C) = 1 Applying Bayes's Theorem yields: P(A|E) = 1/3 P(C|E) = 2/3 So if you switch to Door C, you increase the chances of winning from 1/3 to 2/3. This is the standard answer to the standard version of the problem. If you are not familiar with the Monty Hall problem and this answer comes as a shock to you, please don't take it out on me. Go read about it, starting here, and come back when you have calmed down. Are you ready to go on? Ok. We can do a similar analysis for the Blinky Monty problem, but now we have more evidence to consider: E: Monty opens Door B and blinks. According to the scouting report, the probability that Monty blinks if the car is behind A is 3/5, so P(E|A) = (1/2)(3/5) = 3/10 If the car is behind C, Monty blinks 3/13 of the time, so P(E|C) = (1)(3/13) = 3/13 Plugging in Bayes' Theorem, we get P(A|E) = 0.51, so in this scenario you are slightly better off sticking with Door A. But is that all there is to it? No! And here's where this blog earns the name "Probably Overthinking It." Remember that the probabilities for Monty's blinking are estimates based on a sample, so we have some uncertainty about them. To take that uncertainty into account, we have to 1) Use the scouting report to estimate the distribution of P(blink|A) and P(blink|C). 2) For each pair of values from those distributions, compute P(A|E). 3) Apply the law of total probability to get the overall P(A|E). That might sound complicated, but it is straightforward to estimate computationally. First, let me take a minute to make fun of frequentists. According to conventional hypothesis testing, the data from the scouting report is not statistically significant. If the null hypothesis is that Monty has the same chance of blinking regardless of the location of the car, the p-value of the sample we saw is 0.27 (I used Fisher's exact test, computed using this online calculator). We can't reject the null hypothesis, so if we play by the rules of conventional hypothesis testing, I guess that means we can't take advantage of Monty's tell. If you are a committed frequentist, you should stop reading now. Good. Now that the riff-raff are gone, let's proceed. Here's how we make the posterior distribution for P(blink|doorA): doorA = MakeUniformSuite(0.0, 1.0, 101, name='Door A') evidence = 3, 2 Update(doorA, evidence) MakeUniformSuite() makes a Pmf of 101 values equally spaced between 0 and 1, with equal probability. Update() does the usual Bayesian update: def Update(suite, evidence): """Updates a suite of hypotheses based on new evidence. Modifies the suite directly; if you want to keep the original, make a copy. Args: suite: Pmf object evidence: whatever kind of object Likelihood expects """ for hypo in suite.Values(): likelihood = Likelihood(evidence, hypo) suite.Mult(hypo, likelihood) suite.Normalize() def Likelihood(evidence, hypo): """Computes the likelihood of the evidence assuming the hypothesis is true. Args: evidence: a tuple of (number of heads, number of tails) hypo: float probability of heads Returns: probability of tossing the given number of heads and tails with a coin that has p probability of heads """ heads, tails = evidence p = hypo return pow(p, heads) * pow(1-p, tails) If you are not familiar with that, you can read Chapter 8 of Think Stats, or see this blog post. To find P(blink|C), it's pretty much the same: doorC = MakeUniformSuite(0.0, 1.0, 101, name='Door C') evidence = 3, 10 Update(doorC, evidence) And to finish it off, we apply the law of total probability: print TotalProbability(doorA, doorC, ProbWinning) TotalProbability() enumerates the values from doorA and doorC, and calls ProbWinning() for each pair: def TotalProbability(pmf1, pmf2, func): """Enumerates pairs from the Pmfs, calls the func, and returns the total probability. func: takes a value from each Pmf and returns a probability. """ total = 0.0 for x, px in pmf1.Items(): for y, py in pmf2.Items(): if px and py: total += px * py * func(x, y) return total Finally, ProbWinning() takes P(blink|A) and P(blink|C) and returns P(A|E): def ProbWinning(pbA, pbC): """Computes the probability that the car is behind door A: pbA: probability that Monty blinks if the car is behind A pbC: probability that Monty blinks if the car is behind C """ pea = 0.5 * pbA pec = 1.0 * pbC pae = pea / (pea + pec) return pae You can download all this code here. If you run it, you'll see the posterior distributions for P(blink|A) and P(blink|C): The most likely values are 0.6 and 0.23, but since we don't have much data, the uncertainty is still large.Taking it all together, the probability that the car is behind Door A, P(A|E), is 0.52. So you are slightly better off sticking with Door A. To summarize: 1) In the canonical version of the game, P(A|E) = 1/3, so you are better off switching. 2) In the Blinky Monty version, if we take P(blink|A) and P(blink|C) as givens, we estimate P(A|E) = 0.51, so you are slightly better off sticking with Door A. 3) If you are a frequentist, you conclude that Monty's tell is not statistically significant, so you ignore it, switch, and lose most of the time. 4) If you are a Bayesian, you can take advantage of the tell and maximize your chance of winning. If Monty blinks and you stick, you win 52% of the time. If he doesn't blink and you switch, you win 87% of the time. Since he blinks 40% of the time, overall you can expect to win 73% of the time. So the tell provides a substantial advantage. Exercise for the reader: download my code and modify it to analyze the case where Monty doesn't blink. Hint: you only have to change two lines. EDIT October 19, 2011: I got a comment on reddit that raises a legitimate concern about data collection. In the scenario I presented, if you review tapes of the show and look for several potential tells (blinking, facial tics, verbal habits, etc.) and you choose one that seems to be correlated with the outcome, you could easily get fooled (see this post on repeated tests). This is a fair warning for both the frequentist and Bayesian analyses. So to be more careful, maybe I should say that you were tipped off to the possibility that Monty's tell is a blink before you reviewed the tape, and that's the only data you collected. EDIT January 26, 2012: In the comments below, Jacob pointed out an error in my calculation. As a result, I went back and changed the scenario to match my calculations, which forced me to make a few other revisions. I think it is all settled now, but let me know if you disagree. I believe that you made a mistake calculating P(A|E). You write that you set: "evidence = 3, 10" when it should be "3, 7". Now, maybe that was just a typo, but in your graph, the "Door C" curve appears to peak, not around 0.3, but somewhere closer to 0.25 or maybe exactly 3/13 which would be the case setting your evidence to be "3, 10" You are correct. I have revised the article accordingly (see the note at the end). Thanks very much! We see P(E|A) = 1, instead it should be P(E|C) = 1 Fixed. Thank you!
https://allendowney.blogspot.com/2011/10/blinky-monty-problem.html
CC-MAIN-2021-39
refinedweb
1,658
71.14
Because All has generated as much disagreement as Some did initially, All is definitely a poor name. None being smaller than all other values was an arbitrary decision, and may not be the case in the future. Relying on it is probably not a good idea - especially considering that most people do not know that it could be used in this way. (Also noted by multiple people) If None should not be relied upon, but the existance of a top and bottom value limit make sense (a few people believe that it does), then really we need two values. Terry Reedy suggested making those objects attributes of the cmp builtin. This has the notable side-benefit of not polluting the builtins namespace (YAY!). Terry also suggested that the attributes be cmp.hi and cmp.lo, which seem to be obvious attribute names for what they are. String representations for them are certainly up for debate, ObjHi/ObjLo, NoneHi/NoneLo, Highest/Lowest, Infinity/NegativeInfinity were offered. My only concern is that eval(repr(cmp.hi)) == cmp.hi and eval(repr(cmp.lo)) == cmp.lo be true, but I am leaning toward Highest/Lowest or hi/lo. The names Infinity and NegativeInfinity seem to suggest numbers. Numbers can have math done on them. Certainly there are a certain set of behaviors that make sense, but then there are others that don't (like Infinity - Infinity). Whatever the top and bottom value limit end up being called, whether or not they should allow math to be done on them is probably up for debate. Independant implementations of the top/bottom idea suffer from the ordering of operands to a comparison function making a difference in the result. This may be a problem when an algorithm is written with one top value in mind, yet another comes in and could gum up the works. I've got another draft of my PEP that addresses the above comments and concerns, and provides examples. I'm going to sleep on it before submitting the changes. - Josiah
https://mail.python.org/pipermail/python-dev/2004-January/041688.html
CC-MAIN-2016-50
refinedweb
340
56.05
Code Conventions Table of Contents These conventions should be followed in all code. NOTE: These coding conventions are mandatory for code to be accepted for the Stable series! Python Code Style - - - Limit line length to 80 characters - Use " " for strings, UNLESS the string contains a ", in which case use ' (see also Quotes) - Global variables should be avoided - use response.s3 to store them. PEP8 Script Use static/scripts/tools/pep8.py to check for PEP8 compliance. Execute the following in your eden directory: python static/scripts/tools/pep8.py yourfile.py Quotes - for string constants in Python use double quotes " " - UNLESS the string contains " - for string constants in JavaScript use single quotes ' ' - UNLESS the string contains a ' - for Inline-JavaScript or JSON inside Python code use - in all other cases of triple-quoted strings (such as docstrings or Inline-XML) use """ """ - for XML/HTML attributes use double quotes " " (inner quotes must be escaped anyway) Naming conventions - Function names for the global namespace should start with an "s3_" prefix (if they are not module-specific) or with the module prefix plus underscore. - Names for Eden-specific methods in subclasses of web2py classes also start with "s3_". - should have the suffix "S3" - Names for Eden-specific subclasses of web2py classes and all classes which over-ride existing classes start with "S3", - All other classes defined in Eden end with "S3" (e.g. AuthS3 vs. S3Resource). - CamelCase is for class names only - Constant names are all-uppercase and with underscores as word separator - everything else (including table names and field names) should be all-lowercase with underscores as word separator - Names should be obvious and explicit, but not overly verbose (i.e. as long as they need to be to not make people think). They shouldn't require someone to look in another file or solve a puzzle to figure out what they mean, but shouldn't take too long to write. Avoid inventing new acronyms. e.g. bad: shn_prm_lkp, method_that_allows_us_to_create_a_gis_layer, good: shn_personnel_search, create_gis_layer - All files, classes and functions should have docstrings which allow to auto-generate API documentation using epydoc Suggested style: """ This function is just an example @param: None """ Exceptions - Do not use naked excepts. Yes there are lots already in the code base. Do not make the situation worse. They are being gradually fixed. - If you do use a naked except, the exception should be re-raised. - database errors are the typical tricky case as we don't want to create dependencies on database modules that aren't used. You can catch BaseException and check the exception class name, or you can provide and reuse standard tuples of exception classes in the configuration that map to the same generic database error. - try blocks should be minimised, so that there is less chance of catching the same exception type from a place that wasn't expected, (and then handling it incorrectly). To do this, move code before the exception raising line before the try block, and code after the exception raising line into an else block. - It's good practice to clean up resources in finally blocks. - avoid raising errors inside exception handlers. - don't ignore exceptions. At the very least, log them, or raise them in debug mode. Instead of this: try: # this could raise an error we aren't prepared for file_path = get_file_path() f = file(file_path, 'w') # this could also raise an exception f.write('Please send the helicopter to %s' % disaster_location) f.flush() except: pass # Argh! by ignoring the exception, now lots of things could be messed # up and the rest of the code could break in strange ways. # We will have a hard time figuring out the reason as the original # exception is now lost. # Worse, maybe the user doesn't notice and people die on a mountain. Do this: # now we see any errors here separately file_path = get_file_path() try: # the try block is minimised f = file(file_path, 'w') except IOError, exception: # e.g. a permissions violation if session.s3.debug: # re-raise in development raise else: # logging is good logging.error("%s: %s" % (file_path, exception)) # email reports are great as the developer doesn't have # to log into the machine to read them. # this mustn't raise exceptions (tricky) send_error_email_to_devs(exception, locals(), globals(), request) if not exception_has_been_totally_handled_and_no_further_consequences(): # let the user know so they can take action if possible. raise HTTPError(500, "Cannot queue your message because: %s" % exception) else: f.write('Please send the helicopter to %s' % disaster_location) f.flush() finally: # finalise resources f.close() When should you raise Exceptions, anyway? If it is not possible to continue with the respective processing because there can not be any plausible result, then the necessary consequences highly depend on the cause: - You should never raise an exception for Validation Errors - any invalid user input must be caught and properly reported back to the client (simply because users can't do anything about an exception, so it would render the functionality unusable - whilst a proper error message may help the user to correct their input). Failure to catch validation errors is always a bug. - Configuration Errors, wherever possible, should at most issue a warning (if the invalid setting is obviously a mistake), and else get ignored and fall back to reasonable defaults. Only if there is no possible fallback action, then Configuration Errors should be treated as Runtime Errors. - Runtime Errors may raise exceptions if unrecoverable (i.e. if there's no reasonable handling possible at the respective level). However, if possible and in production mode, they should be caught at a higher level and properly reported back to the client in order to explain the reason and allow correction. Remember logging! - Programming Errors (=bugs) must lead to exceptions in order to attract immediate attention of the programmer to the bug and help them debugging. They should never be caught unless you intend to implement a plausible fallback action (and even then a warning may be appropriate in most cases). Eden is an unsupervised server system, so you must have very good reasons to let it crash. Remember that any uncaught exception leads to a HTTP 500 status with error ticket - and an HTTP 500 status in Eden is a bug by definition. Users can't do anything about error tickets, so the only legitimate reason to raise an uncaught exception in Eden is that you are 100% sure that the error condition leading to the exception is caused by a bug. Nulls Nulls make code much more complicated by introducing special cases that require special null-checking logic in every client, making code harder to understand and maintain. They often and easily cause hard-to-diagnose errors. - Avoid returning nulls wherever possible. Unfortunately the design of python and web2py make this very difficult. E.g. if creating a data structure from many objects, instead of returning nulls from each object and requiring special checking before adding to the structure, pass the data structure to the objects and let them fill in as necessary. - Check for nulls and handle them properly unless you are sure you aren't going to get them. - Unit tests should check that nulls aren't returned. - if you must return a None at the end of the function, do so explicitly, to make the intention clear, rather than falling off the end. - Database fields should generally be non-nullable. If there is the chance of unknown data in certain fields, it indicates that the table may be too big, and those fields may need splitting out into separate tables. It may seem reasonable to allow unknown data, but it places the burden of null-checking on every client of the table. If any client doesn't don't do it (the default), then there is a risk of undefined behaviour. By making them non-nullable, we get a level of code validation from the database layer. JavaScript HTML ids & classes should be named ina way that they don't conflict & should be semantic (what they are for) rather than presentational: - -
https://eden.sahanafoundation.org/wiki/DeveloperGuidelines/CodeConventions?version=33
CC-MAIN-2022-05
refinedweb
1,336
52.6
This post is for those who include <iostream.h>: The new C++ standard (faster & more flexible) does not have a header file named iostream.h, nor does it have fstream.h, stdio.h, or any of the other ANSI-standard .h files that are out there. after including <iostream> or any of the other new c++ headers you should declare that you are using the std namespace as the following code shows. Code: PHP Code: #include <iostream> //no .h's #include <fstream> using namespace std; //see just one new line int main(int argc, char* argv) { cout << "Hello World!" << endl; return 0; } And the old C headers are also converted to the new format like this: <stdio.h> is now <cstdio> <string.h> is now <cstring> <math.h> is now <cmath> hopefully by now you get the pattern ;) So far the only problem i know is between the string.h (now cstring) and string, #include <string> includes the STL string class (very nice, look into this) #include <string.h> includes c functions to deal with char-arrays This is a little annoyance of mine, someday the .h's may cause more conflicts (as in the case of string.h vs. string) and it's just better to use the updated headers, makes no obvious change. The new headers are on all compilers after 98 i believe. Happy Coding! (and don't forget that "using namespace std;" line)
http://cboard.cprogramming.com/cplusplus-programming/3456-h-please-read-printable-thread.html
CC-MAIN-2016-07
refinedweb
237
84.47
Prevent MD5 Downgrade in TLS 1.2 Signatures RESOLVED FIXED in Firefox 43 Status P1 normal People (Reporter: karthikeyan.bhargavan, Assigned: mt) Tracking ({sec-moderate}) Firefox Tracking Flags (firefox39 wontfix, firefox40- wontfix, firefox41+ wontfix, firefox42+ wontfix, firefox43+ fixed, firefox44+ fixed, firefox45+ fixed, firefox-esr31 affected, firefox-esr3844+ fixed) Details (Whiteboard: [adv-main43+][adv-esr38.6+]) Attachments (6 attachments, 3 obsolete attachments) Since 2011 (Bug 650355), NSS was supposed to "stop accepting MD5 as a hash algorithm in signatures". While this applies to signatures within certificates, NSS still allows MD5 signatures in the server signature in the TLS 1.2 ServerKeyExchange message. This exposes NSS based clients such as Firefox to theoretical collision-based forgery attacks. More pragmatically, we believe it is important to draw attention to this bug before TLS 1.3 is implemented, because a similar bug in the processing of the TLS 1.3 ServerCertificateVerify message would lead to a serious server impersonation attack. To see the bug, connect with Firefox to an openssl 1.0.1m server with a modified ssl/s3_srvr.c (attached) which always signs the ServerKeyExchange with RSA-MD5. When Firefox connects to a server, its signature algorithms extension only advertises the following signature/hash algorithms: SHA256/RSA, SHA384/RSA, SHA1/RSA, SHA256/ECDSA, SHA384/ECDSA, SHA1/ECDSA, SHA256/DSA, SHA1/DSA. Notably, it should not allow any MD5 signature. However, when our server sends it an RSA-MD5 signature, NSS does not check that this algorithm is included in the allowed algorithms and quietly accepts it. The root cause for this bug is that TLS 1.2 allows the signer to choose any combination of signature and hash algorithm (even ECDSA-MD5 if it so wishes) and it is up to the verifier to check that the algorithm is acceptable. This is a change from TLS 1.1 (which only allowed MD5SHA1); notably the current TLS 1.3 draft also allows MD5 signatures. We note that NSS allows any signature/hash algorithm combination in ServerKeyExchange but in the ClientCertificateVerify it forces the client to use the hash algorithm that will be used in the Finished message (SHA-256 for TLS 1.2, MD5SHA1 for TLS 1.1) again ignoring the signature algorithms extension. We anticipate that a future update to NSS would also generalize the client signature (to support SHA-512, for example); and this report warns that any such update should be careful to avoid MD5 downgrades. The impact of the bug depends on whether an adversary can trigger meaningful collisions in TLS client and server signatures. Folklore about TLS has previously suggested that only second preimage attacks "break" TLS signatures, collisions do not. We attach a draft research report that shows that collision resistance is essential for the security of client and server signatures in TLS. We show how chosen-prefix collisions in the hash function can be used to forge client signatures in TLS 1.2 and server signatures in TLS 1.3. We believe this result is of independent interest. Collisions in any of the handshake hashes in TLS can be translated to real man-in-the-middle attacks. We would be happy to provide further tests (such as a test server) and discuss countermeasures. The straightforward fix is to check that the signature/hash algorithm in the ServerKeyExchange message is one of the algorithms sent in the ClientHello. (In reply to Karthikeyan Bhargavan from comment #0) > We would be happy to provide further tests (such as a test server) > and discuss countermeasures. The straightforward fix is to check > that the signature/hash algorithm in the ServerKeyExchange message > is one of the algorithms sent in the ClientHello. The conclusion of your paper is that collision resistance is a requirement for the digest algorithm. We basically don't consider SHA-1 to be collision resistant any more. Consequently, SHA-1 should be treated the same way and all the SHA-1 algorithms should be removed from the supported signature algorithms extension. While there are probably few compatibility concerns regarding removing support for MD5 signatures (especially since they aren't advertised in the extension), there may be more compatibility concerns for removing SHA-1. It would be good to see results of scans indicating (a) How many servers choose a digest weaker than SHA-256 when SHA-1 is advertised in the supported signature algorithms extension, and (b) how many servers break if SHA-1 is removed. But, dropping MD5 support shouldn't be blocked on that. I agree that we should prepare for SHA-1 being deprecated, but as far as I know chosen-prefix attacks for SHA-1 are still not considered practical, although they're in the "coming soon" category. The report focuses on the use of hash functions in signatures, since this is configurable since TLS 1.2. However, the same argument holds for the use of hash functions in the Finished message. In TLS 1.2 we use SHA-256 which is considered safe, but in earlier versions we use MD5+SHA1 and practical chosen-prefix collisions on this combined hash function would break the integrity of TLS handshakes. Disregarding the general discussion above on collision resistance, the MD5 downgrade should be fixed soon. Anything I need to do to get this bug confirmed? Status: UNCONFIRMED → NEW Ever confirmed: true Karthikeyan: thank you very much for reporting the bug. I just gave the "canconfirm" access to your Bugzilla account, so that future bugs you file will start in the NEW state. Martin: I assigned the bug to you. I will be happy to help or review the patches. Assignee: nobody → martin.thomson Status: NEW → ASSIGNED Priority: -- → P1 Target Milestone: --- → 3.19.1 I've identified what I think the most trivial fix for this bug could be: Delete this line: /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the * SECOidTag used internally by NSS. */ static const struct { int tlsHash; SECOidTag oid; } tlsHashOIDMap[] = { - { tls_hash_md5, SEC_OID_MD5 }, { tls_hash_sha1, SEC_OID_SHA1 }, { tls_hash_sha224, SEC_OID_SHA224 }, { tls_hash_sha256, SEC_OID_SHA256 }, { tls_hash_sha384, SEC_OID_SHA384 }, { tls_hash_sha512, SEC_OID_SHA512 } }; I think that works for now, but it has been suggested that perhaps JC might have more time for doing this work. If we are going to fix this properly - which I'm going to recommend happen in a follow-up - a more complete solution would have a global hash configuration. That config could be used in ssl3_ClientSendSigAlgsXtn and it would then also drive ssl3_CheckSignatureAndHashAlgorithmConsistency. That would allow NSS users, like Firefox, to set a policy that disabled SHA-1 at the point in time where that was considered feasible. We'd need good numbers to support a decision to do that though. It might be that this is sooner than we phase out SHA-1 in certificates, but that seems like a reasonable point in time to consider a change in policy. Kai also pointed out that it's possible to detect attempts at hash collisions as described in I don't think that's worth doing if we're going to be ripping SHA-1 out. That might be a good backup plan if it turns out that telemetry tells us that is a bad idea. Flags: needinfo?(jjones) Martin: we probably should go for a direct fix by only allowing the signature algorithms advertised in ClientHello. I agree your trivial fix should solve this problem, but it is an indirect fix and is likely to break in the future. In the immediate term I'm pretty slammed, Martin - racking & configuring ISRG's DR datacenter Sunday-Wednesday. Earliest I can start taking a look would be 7 May. :( Flags: needinfo?(jjones) Could we also fix the handling of signatureAlgorithms in CertificateRequest (and hence in CertificateVerify)? NSS currently ignores the requested signature algos and uses MD5SHA1 in TLS < 1.2 and SHA256 in TLS 1.2. This isn't standards compliant, but I guess not too many people are using client signatures with other hash algorithms. It also means that a client that support SHA-512 signatures cannot take advantage of the stronger hash algorithm. Again, clients using certs with hashAlg > SHA256 are probably rare. Regarding comment 9, I think that we should try to keep the changes contained. We can consider expanding scope in a follow-on. I've done some investigation here and I think that we should add a control surface for selecting what signature algorithms we want to accept. The hack I described might be OK if we need something quickly. It's indirect and horrible, as Wan-Teh noted, but it should work. For the control surface, I've a few API choices that I'd like to run by folks with more familiarity with the code. A.1. Co-dependent settings for signature and hash. e.g., SECStatus SSL_SignaturePrefSet(PRFileDesc *fd, SSLSignType sigAlg, SSLHashType hashAlg, PRBool enabled); Noting that SSLHashType doesn't exist (see C). A.2. Indepedendent settings: SECStatus SSL_SignatureAlgPrefSet(PRFileDesc *fd, SSLSignType sigAlg, PRBool enabled); SECStatus SSL_SignatureHashPrefSet(PRFileDesc *fd, SSLHashType hashAlg, PRBool enabled); A.3. A job lot approach: SECStatus SSL_SetSignatureAlgorithms(PRFileDesc *fd, SSLSignatureAlgorithm *algorithms, size_t count); B.1. Include setters for the global defaults, like SSL_CipherPrefSetDefault does for cipher suites. B.2. Don't. C.1. A new type in sslt.h for SSLHashType. C.2. Assuming A1, define a struct for signature algorithms: typedef struct SSLSignatureAlgorithmStr { SSLSignType sign; SSLHashType hash; } SSLSignatureAlgorithm; C.3. Use the PKCS#11 definitions, such as SEC_OID_MD5. C.4. Move the tls_hash_* definitions in ssl3prot.h into sslt.h I'm leaning toward A.1, B.2, and C.1. Martin, we are trying to assign this a security rating, but don't understand the implications of this bug. Can you advise? How easy is it to exploit? Flags: needinfo?(martin.thomson). Flags: needinfo?(martin.thomson) Groundwork for larger patch. A rework of how we handle signature algorithms. is available on request. Target Milestone: 3.19.1 → 3.19.2 Wan-Teh, can you do the patch review here? This has been sitting around for more than a month and we need to get this fixed. status-firefox39: --- → wontfix status-firefox40: --- → affected status-firefox41: --- → affected status-firefox42: --- → affected status-firefox-esr31: --- → affected status-firefox-esr38: --- → affected tracking-firefox40: --- → + tracking-firefox41: --- → + tracking-firefox42: --- → + tracking-firefox-esr38: --- → ? Flags: needinfo?(wtc) Target Milestone: 3.19.2 → 3.20 (In reply to Martin Thomson [:mt:] from comment #12) >. I think server impersonation, based on this bug, is not really practical yet. It requires either (a) a server which chooses a predictable server random and repeats its (EC)DH key share [10% of servers reuse key shares but very very few seem to use predictable server randoms, but the latter is difficult to test, and may be plausible in virtualized scenarios.] or (b) an adversary capable of performing 2^64 queries, storing their results, and then peforming 2^64 MD5 hashes [the last of these is practical, but the first two seem to be out of reach for most adversaries] or (c) a second preimage attack on MD5 [this is still an open problem] So, although I am all for this bug being fixed as soon as possible, I would in this case recommend a lower security rating than sec-high, even if it means no bounty :) Thanks Kathik, hopefully we can fix this before this becomes sec-high based on any of those criteria :) Keywords: sec-high → sec-moderate Al, can you provide your assessment on whether this bug needs to be fixed in the upcoming ESR 38 release? Thanks! Flags: needinfo?(abillings) (In reply to Ritu Kothari (:ritu) from comment #20) > Al, can you provide your assessment on whether this bug needs to be fixed in > the upcoming ESR 38 release? Thanks! Given that it is a external report affecting TLS, I'd suggest taking this on ESR38. Flags: needinfo?(abillings) If this is going into 40, it pretty much needs to get checked in today. Flags: needinfo?(martin.thomson) Tracking for ESR 38 given comment 21. This is not going in today. See comment 18 regarding severity. Also, the patch needs another round, which it isn't getting on such short notice. Flags: needinfo?(martin.thomson) I noticed that you nominated this bug for esr38 tracking ?, does this mean that you don't want the security team to fix it? In that case we can wontfix and untrack. Let me know! Flags: needinfo?(abillings) No, it means that I'd mark it tracking 41+ in the ESR38 tracking except 41+ doesn't exist yet. Flags: needinfo?(abillings) Release notes draft for this change: Bug 1158489 - NSS libssl incorrectly accepted signatures in TLS 1.2 using algorithms that it did not advertise in its signature_algorithms extension. This resulted in libssl accepting MD5 hashes in signatures. There are several functional changes as a result of this fix: - Support for MD5 hashes in signature algorithms has been removed. - Support for SHA-224 hashes in signature algorithms has been removed (SHA-224 was previously only partially supported). - The set of signature algorithms that libssl advertises and accepts can be configured, where this was previously hard-coded. - libssl now selects a signature algorithm to use based on the configured signature algorithms, rather than having a fixed preference order. - New API calls have been added: + SSL_SignaturePrefSet sets the signature algorithms that libssl will advertise or accept. The order of this set is used to select the signature algorithm that is used; earlier values are preferred. This configuration governs what value is advertised in the signature_algorithms extension or the supported_signature_algorithms field of the CertificateRequest message. libssl rejects signatures in TLS 1.2 that identify a signature and hash algorithm that don't appear in this set. + SSL_SignaturePrefGet retrieves the currently configured signature algorithms. + SSL_SignatureMaxCount gets the maximum number of signature algorithms that can be configured at the same time. Also at Attachment #8606510 - Attachment is obsolete: true Attachment #8606511 - Attachment is obsolete: true Target Milestone: 3.20 → 3.21 Updated based on ekr's comments, still awaiting final review. Attachment #8643316 - Attachment is obsolete: true I just opened Bug 1195434. This provides justification/cover for these changes going in, which will happen soon. It also avoids one concern that ekr raised regarding a mismatch between the configuration in NSS and in mozilla::pkix. Other users of NSS will have to deal with this on their own, I'm afraid. (clearing n-i on wtc) Flags: needinfo?(wtc) Martin, since this is a FF41+ tracked bug. Will there be a fix for this issue in Beta41 time frame (1-2 more weeks left now)? Flags: needinfo?(martin.thomson) I will ask what the NSS release schedule is like. I think that the plan is to get a few more features in before we branch. Group: core-security → crypto-core-security Discussed on today's call. The decision was to delay inclusion to Firefox 44 and to miss the next ESR 38 build. There are a few more related changes to land in NSS. None of the fixes are particularly urgent and we could use the extra time to do some more comprehensive testing. Flags: needinfo?(martin.thomson) Based on comment 34, setting FF41 status to wontfix. Can we push this bug along? This bug will be publicly disclosed at Real World Crypto (Jan 6-8 2016). The disclosure page (still work-in-progress) is here: (user: vulnerability, pass: prosecco) To summarize the impact on NSS, an attacker who can make 2^X connections to and store the server signatures, can subsequently impersonate to NSS clients by performing 2^(128-X) MD5 hashes. If X = 64 is practical, then the effective security of the connection is brought down to 64 bits, even if the server is using a 2048 bit RSA key with TLS 1.2 ECDHE-RSA-AES-GCM-SHA384. This attack is still out of reach for academics, but may well be in reach for a powerful government-scale adversary. Ahh, this is already landed. I am reminded that we should request uplift of NSS 3.21 though. (In reply to Martin Thomson [:mt:] from comment #37) > Ahh, this is already landed. I am reminded that we should request uplift of > NSS 3.21 though. We're about to cut release candidates for Firefox 43 so you may have blown the dates there to make it into that release. Flags: needinfo?(lhenry) Martin, it could happen, but we're about to merge beta to mozilla-release and build the release candidate on Monday. If this is critical for the 43 release, we also have the option to do an RC2 in mid week. It looks like you were planning to release a fix along with 44 and that more testing is needed. I don't think we will have time for that testing over the next week unless this is critical. Since this is rated sec-moderate, I wouldn't normally consider doing a second RC build for it. Do you think the planned disclosure in January changes how we should treat this bug? status-firefox43: --- → affected status-firefox44: --- → affected status-firefox45: --- → affected tracking-firefox43: --- → + tracking-firefox44: --- → + tracking-firefox45: --- → + tracking-firefox-esr38: --- → ? Flags: needinfo?(lhenry) → needinfo?(martin.thomson) As noted, it's sec-moderate, though Comment 36 does make this marginally more serious than the earlier analysis in Comment 18. Either way, I don't think that we need to create a special build for it. My recommendation is that we opportunistically uplift as things become available. That is, take it with the next ESR that goes out, and if there is a second RC, consider including it there. We've been using NSS 3.21 in Nightly for a while now and I've not heard even a whisper about stability or compatibility issues, so I think that it's safe to uplift. The upcoming announcement could come with another media splash and another round of panicking from certain people. If we want to get ahead of it, then it would be wise to at least have a plan in place. I think that this is the plan: ship NSS 3.21 as the opportunity presents itself. Note: when uplifting, we need to uplift the changes in bug 1211568, not this one. Status: ASSIGNED → RESOLVED Last Resolved: 4 years ago Flags: needinfo?(martin.thomson) Resolution: --- → FIXED Since the changes in bug 1211568 are already in 44 I think we should uplift them to beta as well. If you could request uplift there we could get it into Monday's RC build. That doesn't allow for a lot of testing or room for error but it sounds best to give it a try. Thanks Martin. Flags: needinfo?(martin.thomson) I requested uplift for the three relevant bugs. Flags: needinfo?(martin.thomson) If you consider to uplift to the ESR 38.x update scheduled for next week, we need to discuss the best strategy. ESR currently uses NSS 3.19.2.1. There have been a lot of changes between that and 3.21. The root CA list has been updated twice, and in the past, it was usually decided that regular CA updates should be excluded from the ESR branch (except in case of emergency CA updates). OK. After some more discussion (thanks everyone for your advice!) let's not uplift this to 43. We still may need to do that, but if so, more planning and a bit more time would be better. Suggestion for Firefox 43 (or 43.1) and for ESR 38.5 (or 38.5.1): Use Martin's minimal fix from comment 6, which Wan-Teh has reviewed in comment 7. If this minimal fix can be considered sufficiently secure for the next 2-3 months, it seems more appropriate for a last minute hotfix. Red Hat would like to make some more time testing NSS 3.21, and is looking for a minimal fix that can be backported to NSS 3.19.2.1 And, if the minimal fix can be considered sufficient for ESR 38, it might also be sufficient for the limited lifetime of the Firefox 43 branch. If you agree to this approach, my suggestion is: ESR 38 ====== Currently uses NSS 3.19.2.1 Apply the minimal fix from comment 6 on a mini-branch and release NSS 3.19.2.2 Upgrade the ESR branch to 3.19.2.2 Firefox 43 ========== Currently uses NSS 3.20.1 Apply the minimal fix from comment 6 on a mini-branch and release NSS 3.20.2 Upgrade Firefox 43 to 3.20.2 I suggest that we go ahead and create the NSS releases immediately, and you can decide if you want to respin 43/38.5, or if you want to do a followup and do 43.1/38.5.1 Thoughts? Flags: needinfo?(martin.thomson) (In reply to Kai Engert (:kaie) from comment #45) > > I suggest that we go ahead and create the NSS releases immediately, and you > can decide if you want to respin 43/38.5, or if you want to do a followup > and do 43.1/38.5.1 Are we allowed to check in the minimal fix publicly on stable branches, or would that make it all too obvious that we found a security vulnerability? If you're worried that it's too obvious, the alternative suggested timing is: - on January 4, commit minimal hotfix to NSS, create NSS branch releases, and update the 38.x and 43.x branches - publish the updated 38.x and 43.x releases as soon after January 5 as you can. Could you please comment, which suggestion and which timing you like best? Thanks Attachment #8696762 - Attachment description: Martin's minimal fix, suggested for ESR 38.x and 43.x, has r=wtc → Martin's minimal fix, has r=wtc, suggested for ESR 38.x and 43.x Hi, If there's going to be a CVE number for this bug, do let me know so I can include it in our paper. Many thanks, Karthik Comment on attachment 8696762 [details] [diff] [review] Martin's minimal fix, has r=wtc, suggested for ESR 38.x and 43.x Review of attachment 8696762 [details] [diff] [review]: ----------------------------------------------------------------- r=wtc. I inspected the NSS source code in mozilla-esr38. I agree with Karthikeyan's analysis that in all other places NSS doesn't sign with MD5 and doesn't allow MD5 signatures -- partly because NSS properly disallows MD5, and partly because NSS is hardcoded to use SHA-256 or SHA-1 in CertificateVerify. Alias: CVE-2015-7209 (In reply to Karthikeyan Bhargavan from comment #49) > Hi, > > If there's going to be a CVE number for this bug, do let me know so I can > include it in our paper. > > Many thanks, > Karthik Karthik, Red Hat already assigned CVE-2015-7575 to this flaw (i mailed you about this earlier) Al, Can we use the above CVE please if possible to allow duplication. Thanks! reply to Karthikeyan Bhargavan from comment #52) >. > Red Hat issued a "protocol-level" CVE > several previous cases, no implementation level CVEs were issues. Code is implements the protocol. In essence code is not flawed, so i dont think we should issue code level CVEs > Red Hat issued a "protocol-level" CVE Ok, we will cite this CVE in our disclosure (hopefully other vendors will follow suit) > In several previous cases, no implementation level CVEs were issues. Code is > implements the protocol. In essence code is not flawed, so i dont think we > should issue code level CVEs I don't mind having only a protocol-level CVE; it simplifies things for disclosure. Worth adding a word of warning though. Say you're using Firefox/NSS and look at the SSL Labs Browser test, which says that your browser does not support RSA/MD5. Or you're using an old version of GnuTLS and you set your --priority to "NORMAL" which does not include MD5. You may expect that, as a user, you have now addressed the protocol-level CVE-2015-7575 by "disabling MD5". The bugs in these libraries (and in some others) is that disabling MD5 is not as simple as that. It may be worth adding specific wording to the protocol-level CVE to warn users and TLS implementations against this. Of course, we and others will probably have browser and server tests that will test for the vulnerability and provide the right feedback. Alias: CVE-2015-7209 → CVE-2015-7575 By tomorrow, I must publicly commit the minimal fix to NSS backported branches, which might cause the issue to be more obvious, than the previous commit for this bug (which had used the text "Enable signature algorithm configuration"). I suggest we'll use the following text for the minimal fix: "Remove obsolete entry." Regarding release notes, I suggest that we'll be vague in the NSS release notes document for now, and update them around after Karthikeyan has published the issue, with more details and credit. I'd announce the updated NSS releases with vague information at the time Mozilla releases the first of {43.x,38.x} that contains the fix. Clearing needinfo from comment 45, I talked to Liz and Sylvestre on IRC. A Firefox 43.x release shall happen this week, and because of that Liz confirmed I should go ahead and prepare the NSS release for it. ESR hasn't been decided yet, waiting for a decision, but I'll create an appropriate release for it, too. Flags: needinfo?(martin.thomson) Confirmed with Chrome folks that we're treating this as not requiring a chemspill; we'll likely pick this up with Chrome 49 going to NSS 3.21, which means sometime in late Feb/early March to hit stable, based on reading the release calendar tealeaves. The only difference between the suggested NSS 3.20.2 and the 3.20.1 currently being used will be attachment 8696762 [details] [diff] [review] plus NSS version number changes. Attachment #8698647 - Flags: approval-mozilla-release? The only difference between the suggested NSS 3.19.2.2 and the 3.19.2.1 currently being used will be attachment 8696762 [details] [diff] [review] plus NSS version number changes. Attachment #8698648 - Flags: approval-mozilla-esr38? Group: crypto-core-security → core-security-release OK, after some more discussion with Daniel and Kai, we are planning for Kai to land this on m-r tomorrow (which should be after I build 43.0.1). We will aim this NSS update for 43.0.2, which we are planning to build and release early next week. The goal here is to avoid the need for a 43.0.3 in early January. Kai, given that we are doing this for ESR38 and FF43, should we also uplift to Beta44? Thanks! Flags: needinfo?(kaie) Actually I just realized that FF44 was upgraded to NSS 3.21 in Bug 1211568 so we may not need to do anything here for FF44. Should I just mark it as fixed? correct, 44 and 45 are already fixed, because they use NSS 3.21 Flags: needinfo?(kaie) Comment on attachment 8698647 [details] upgrade mozilla-release 43 to NSS 3.20.2 Approved for uplift to mozilla-release. We are set with the 43.0.1 build now, so this work will go into 43.0.2. Attachment #8698647 - Flags: approval-mozilla-release? → approval-mozilla-release+ Comment on attachment 8696762 [details] [diff] [review] Martin's minimal fix, has r=wtc, suggested for ESR 38.x and 43.x BTW, the minimal patch has landed on stable NSS branches: NSS_3_19_2_X_BRANCH for 3.19.2.2 NSS_3_20_BRANCH for 3.20.2 The commit to mozilla-release upgraded to 3.20.2 We are ready to push this with 43.0.2 release today. Al I just realized, does this mean we should have a security advisory in place? Or is there one already as this upgrade is already released in 44 and onward? Flags: needinfo?(abillings) I'll just link to the 43 sec advisory page for now from the release notes. Flags: needinfo?(abillings) **** Was this bug / fix under embargo? Al - can you post the text of what we released today here? We had an advisory live for about an hour today on this bug before I was advised that it might be under embargo. I pulled the advisory down. Text of advisory was:. I mailed karthikeyan.bhargavan@inria.fr to ensure that he sees this. Flags: needinfo?(karthikeyan.bhargavan) What is the procedure for the advisory? Can you add one later? Otherwise, the text above looks more or less ok, since it refers only to server authentication (which is the harder attack, compared to client authentication.) Any mention of the CVE would definitely be premature. The main risk is that (a) someone will start wondering what servers support MD5 signatures, and the thing might leak before RHEL 6 and 7 release patches, and (b) someone will start wondering about client authentication, before Java releases patches. Flags: needinfo?(karthikeyan.bhargavan) Usually, we write them when we release the fix but we can hold them until later as well. The advisory is already public, should we consider this issue public now? Public disclosure of CVE-2015-7575 is in January, and other vendors need the time to fix. Let's please be circumspect about what we consider public till then. Like I said, I do not mind if the short text referred to above has already been leaked, but please do not add any more detail or refer to the CVE at this point. Conversely, please do refer to the CVE once the bug is publicly disclosed. (In reply to Huzaifa Sidhpurwala from comment #74) > The advisory is already public, should we consider this issue public now? The advisory was removed. While the text may have leaked, it is down right now and there are no public references to the CVE at this time. The text I posted above will go back online (with the CVE from here) once the talk has occurred. If you don't want it live then, Karthikeyan, we will need a disclosure date from you. Otherwise, I expect to post it on January 7, based on the presentation being complete. It won't contain any more data than what we posted before then. In the future, we need to have embargo dates explicitly communicated. I should have seen the presentation dates and put it together myself not to talk about it but no one ever clearly communicated to Mozilla not to talk about it until after a specific date. Karthikeyan, at what time and timezone will your talk be given? Thanks. Flags: needinfo?(karthikeyan.bhargavan) I just found the answer myself. Thursday, Jan 7, 16:30 pacific time, which means, early after midnight Jan 8 UTC. Flags: needinfo?(karthikeyan.bhargavan) Hi, we just put sloth-attack.org online. I'll be giving the talk tomorrow, but let's consider this public disclosure. So the advisory with the text given in comment 70 (which has the CVE attached to this bug on it) can go live now? Flags: needinfo?(karthikeyan.bhargavan) Yes. Please cite the CVE number as well. Thanks! Flags: needinfo?(karthikeyan.bhargavan) The sec advisory says that we fixed this in 38.5.2 but I don't think that is the case. (In reply to Liz Henry (:lizzard) (needinfo? me) from comment #83) > The sec advisory says that we fixed this in 38.5.2 but I don't think that is > the case. Al: Liz is right. Could you please fix the advisory from comment 82 and remove the statement about 38.x? Flags: needinfo?(abillings) Comment on attachment 8698648 [details] upgrade mozilla-esr38 to NSS 3.19.2.2 Given that we've announced this fix in ESR (comment 83) and that the sec team thinks we should take this fix (comment 21, comment 40), let's get this into ESR 38.6.0. Attachment #8698648 - Flags: approval-mozilla-esr38? → approval-mozilla-esr38+ Comment on attachment 8698648 [details] upgrade mozilla-esr38 to NSS 3.19.2.2 Flags: needinfo?(abillings) Whiteboard: [adv-main43+] Whiteboard: [adv-main43+] → [adv-main43+][adv-esr38.6+] (In reply to Kai Engert (:kaie) from comment #84) > > Al: Liz is right. Could you please fix the advisory from comment 82 and > remove the statement about 38.x? What the hell? We didn't ship this? (In reply to Al Billings [:abillings] from comment #87) > (In reply to Kai Engert (:kaie) from comment #84) > > Al: Liz is right. Could you please fix the advisory from comment 82 and > > remove the statement about 38.x? > > What the hell? We didn't ship this? We have _now_: comment 84 was 6 weeks ago; 4 weeks ago we shipped Firefox 38.6 ("44+") with NSS 3.19.2.2 containing the fix. Comment on attachment 8646029 [details] [diff] [review] bug1158489.patch Martin, only out of curiousity, was there a special reason why you added sha384/512 entries for rsa and ecdsa, but not for dsa, in this table? Or was it simply the thought they aren't necessary currently? Thanks in advance. +static const SSLSignatureAndHashAlg defaultSignatureAlgorithms[] = { + {ssl_hash_sha256, ssl_sign_rsa}, + {ssl_hash_sha384, ssl_sign_rsa}, + {ssl_hash_sha512, ssl_sign_rsa}, + {ssl_hash_sha1, ssl_sign_rsa}, +#ifndef NSS_DISABLE_ECC + {ssl_hash_sha256, ssl_sign_ecdsa}, + {ssl_hash_sha384, ssl_sign_ecdsa}, + {ssl_hash_sha512, ssl_sign_ecdsa}, + {ssl_hash_sha1, ssl_sign_ecdsa}, +#endif + {ssl_hash_sha256, ssl_sign_dsa}, + {ssl_hash_sha1, ssl_sign_dsa} +}; Flags: needinfo?(martin.thomson) Kai, I think that the SHA-256 version is an error. See this from RFC 5246, Section 7.4 [...] Flags: needinfo?(martin.thomson) Oh, I realize now why it's in there. Otherwise, we can't do DSA with TLS 1.2 because we advertise only SHA-256 paired with the asymmetric signature scheme in signature_algorithms. It's a bit of a mess really. Group: core-security-release Comment on attachment 8696762 [details] [diff] [review] Martin's minimal fix, has r=wtc, suggested for ESR 38.x and 43.x goog Flags: needinfo?(MAWAVANSMOOKEY) Comment on attachment 8696762 [details] [diff] [review] Martin's minimal fix, has r=wtc, suggested for ESR 38.x and 43.x Review of attachment 8696762 [details] [diff] [review]: ----------------------------------------------------------------- http:mtnuganda-cust.opera-mini.net:80/bugzilla/<html >/good Comment on attachment 8696762 [details] [diff] [review] Martin's minimal fix, has r=wtc, suggested for ESR 38.x and 43.x good Flags: needinfo?(MAWAVANSMOOKEY)
https://bugzilla.mozilla.org/show_bug.cgi?id=1158489&amp;GoAheadAndLogIn=1
CC-MAIN-2019-22
refinedweb
5,712
65.42
Hi, So I've got several CMake projects within one 'solution' folder, each with their own namespaces. Adding correct namespace each time i create a new class within any of these projects is a little tedious. Is there a trick to have it done for me? In Qt Creator, I could type 'mynamespace::MyClass' as class name to get an empty class 'MyClass' within 'mynamespace' namespace. As a workaround up until now, I've changed my code template creation to always insert an empty namespace when creating a source or header file. I still have to add the correct namespace name, though. Hi, Hi Halvor. It is not implemented yet, we have related issue in our tracker. Feel free to comment or upvote. Thank you. I placed my vote!
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206606605-Default-namespace-based-on-cmake-project-
CC-MAIN-2020-16
refinedweb
129
75.61
Extern in C Reading time: 30 minutes | Coding time: 5 minutes Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files. Syntax: extern <data_type> <variable_name>; // or extern <return_type> <function_name>(<parameter_list>); Example: extern int opengenus; // or extern int opengenus_fn(int, float ); To understand the significance better, we need to understand three terms: - Declaration Declaration of a variable means that the compiler knows that the variable exists but no memory or data has been assigned to it. To stop at this step, we need extern keyword like: extern int opengenus; opengenus is a valid integer variable but no memory has been allocated to it. - Define Defining a variable means assigning the variable the required memory. At this step, garbage value is placed at the memory location but the variable is ready to be used. Example: int opengenus; - Initializing Initializing a variable means assigning a value in the memory location of the variable. Example: int opengenus = 1; This table summarizes the idea: Using extern The main rule is that extern should be used in header files only. Though there are ways around this but it is not advised for code safety. Let us code a header file named "opengenus_header.h" as: extern int opengenus; extern void get_data(void); opengenus_header.h has both variables and functions but in production, it is advised to keep variables and functions in separate header files. This will be our common C code (og.c) used to declare and define common variables and functions. #include "opengenus_header.h" int opengenus = 1; This is our main code (main.c) which is linked with our common C code (og.c) and uses the same global/ extern variables and functions. #include "opengenus_header.h" #include <stdio.h> int main(void) { printf("%d", opengenus); } Compile it as: gcc main.c og.c Execute it as: ./a.out Output: 1 While compiling, if you do not link og.c with main.c, you will get a compile time error. Erroneous compilation: gcc main.c Error: /tmp/ccrE2C9Q.o: In function `main': main.c:(.text+0x6): undefined reference to `opengenus' collect2: error: ld returned 1 exit status This is because the memory for opengenus variable is being allocated in file og.c and it has not been linked. So, in main.c, in this compilation step, we are using the variable without declaring it which gives an error. If we compile og.c only, we will get an error as it has no main function. gcc og.c Compile time error: /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: error: ld returned 1 exit status Hence, the overall and good coding strategies are: - All variables and functions in header files should be extern - Separate header files should be used for variables and functions - Use a C code file to declare the variables and functions and use this in end user code - Extern must be used instead of using global variables
https://iq.opengenus.org/extern-in-c/
CC-MAIN-2020-29
refinedweb
533
66.03
In this article, we will discuss a sample CLR function that illustrates accessing an external resource such as a file from inside a SQL Server stored procedure or function, . The sample highlights a number of different features and concepts, such as file-access, table-valued functions and impersonation. Let us review first how to implement a table-valued function. If you have been playing with table-valued functions (TVFs) in SQL Server 2005 beta 2, you will notice that the contract is much simplified in the April CTP of SQL Server 2005. The basic requirements are as follows: The TVF should be mapped to a static method in the CLR (let us call it the root method) that returns either an IEnumerator or an IEnumerable interface. The IEnumerable interface is supported mainly to support scenarios where you want to crack collections (such as arrays, lists) into tabular result sets. It is very straightforward to implement such TVFs because the managed classes that implement these collections already implement the IEnumerable interface. The IEnumerable interface has a single method called GetEnumerator that returns an IEnumerator interface. For cases where you’re not cracking such a collection, you can implement the IEnumerator interface itself (instead of the indirect route of implementing IEnumerable that returns an IEnumerator). The IEnumerator interface requires one property and two methods that need to be implemented. Following are the descriptions of these methods along with how SQL Server calls them. - MoveNext: This method moves the current position of the “result-set” to the next row. The initial position of the “result-set” is before the beginning, so the consumer (in this case SQL Server) will always call MoveNext first which positions it on the first row of the result set. - Current property: This property returns the current “row” of the result set as an Object as per the current row position - Reset: This method resets the current position to before the first row. The root method should be annotated with a SqlFunctionAttribute that indicates what the fill-row method is (typically another static method in the same class as the root method). The fill-row method cracks the record represented by the Object returned by IEnumerator.Current into multiple column values using output parameters. Thus, the fill-row method has 1+n arguments where n is the number of columns returned by the TVF. The first argument is an input argument which is the Object that SQL Server got from calling IEnumerator.Current. The next n arguments are output arguments that the method should fill with the column values; the data types of these arguments should be compatible with the column data types as declared by the CREATE FUNCTION statement. Having reviewed the basic elements of building a TVF, let us look at our example scenario. The sample implements a table-valued function called GetFile, that given the path-name for a file, reads the contents of the file and returns it as a varbinary(max) value as a single row with a single column. You might wonder why this is not written as a scalar-valued function since after all it just returns a single scalar. The reason is performance: whenever dealing with large values, it is of course important to try and stream the values to SQL Server instead of buffering the entire contents along the way. This means using the SqlBytes data type as the return type of the function (well, actually the type of the single column returned by the function). SqlBytes allows streamed movement of binary data to SQL Server. In our case, we will construct a SqlBytes object using a managed FileStream object that represents the contents of the specified file. However we need a way to close this FileStream once SQL Server is done reading the contents of the file. Since SqlBytes does not implement the IDisposable interface, there is no way for SQL Server to close the file. So if we implemented this function as a scalar function, there will be no way to close the FileStream and we will have an open file handle even after the query that reads the file contents completes execution. On the other hand, if we model this function as a table-valued function, then the MoveNext method (which is part of the IEnumerator interface that needs to be implemented for the TVF) can close the FileStream once it reaches the end of the result-set (which in this case is just one row). Having established the need for a table-valued function, let us review our implementation. The implementation consists of two classes: FileAccess which implements the root method (GetFile) and the fill-row method (called of course FillRow). The GetFile method returns a SingleFileLoader object that implements the IEnumerator interface. The SingleFileLoader is constructed using the specified file name which it opens stashing away the FileStream in its private state. (It also impersonates the current caller before it opens the file; more on this later). MoveNext is coded such that it always returns only one row. When it reaches past this one row it closes the FileStream (the main reason why we chose the TVF approach). Current simply returns the FileStream that was created when the SingleFileLoader was constructed. Here is the code (which will work only in the April CTP of SQL Server 2005 or later). using System; using System.Collections; using Microsoft.SqlServer.Server; using System.IO; using System.Data.SqlTypes; using System.Security.Principal; // This class implements a table-valued function that returns one row with one // column that retrieves the binary contents of a specified input file name. // Returns NULL on most exception conditions such as inability to impersonate, // file-doesn't exist etc. public partial class SingleFileLoader : IEnumerator { private FileStream fs; private bool IsBegin = true; private String fn; public SingleFileLoader(String FileName) { fn = FileName; SingleFileLoaderHelper(); } private void SingleFileLoaderHelper() { WindowsImpersonationContext OriginalContext = null; try { //Impersonate the current SQL Security context WindowsIdentity CallerIdentity = SqlContext.WindowsIdentity; //WindowsIdentity might be NULL if calling context is a SQL login if (CallerIdentity != null) { OriginalContext = CallerIdentity.Impersonate(); fs = new FileStream(fn, FileMode.Open); } else fs = null; } catch { //If file does not exist or for any problems with opening the file, // set filestream to null fs = null; } finally { //Revert the impersonation context; note that impersonation is needed only //when opening the file. //SQL Server will raise an exception if the impersonation is not undone // before returning from the function. if (OriginalContext != null) OriginalContext.Undo(); } } public Object Current { get { return fs; } } public bool MoveNext() { //Ensure returns only one row if (IsBegin == true) { IsBegin = false; return true; } else { //Close the file after SQL Server is done with it if (fs != null) fs.Close(); return false; } } public void Reset() { IsBegin = true; SingleFileLoaderHelper(); } } public partial class FileAccess { [SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "FileContents varbinary(max)")] public static IEnumerator GetFile(String FileName) { return new SingleFileLoader(FileName); } public static void FillRow(Object obj, out SqlBytes sc) { //If non-existent file, return SQL NULL if (obj != null) sc = new SqlBytes((Stream)obj); else sc = SqlBytes.Null; } } Assuming that this code is compiled into an assembly called TVF.dll, the assembly and the table-valued function can be registered in SQL Server by executing the following DDL: use MyDB go if exists (select * from sys.objects where name = 'GetFile') drop function GetFile if exists (select * from sys.assemblies where name = 'TVF') drop assembly TVF go create assembly TVF from 'c:\Projects\TVF\TVF\TVF.dll' with permission_set = external_access go create function GetFile(@fn nvarchar(300)) returns table(filecontents varbinary(max)) as external name TVF.FileAccess.GetFile go Following are some simple test queries to test the TVF: from GetFile('C:\MyDir\function1.cs') go from GetFile('NonExistentFile.cs') – should return NULL go Impersonation As you might have noticed, there is code to impersonate the current security context in the constructor for SingleFileLoader - actually the bulk of the work is done by SingleFileLoaderHelper. SQL Server does not automatically impersonate the current caller when executing code in an EXTERNAL_ACCESS or UNSAFE assembly (it is not possible to access an external resource in the SAFE assembly, so impersonation is moot for that case). Hence by default, code will run and access resources under the SQL Server service account unless there is explicit code to impersonate. In this example, it is sufficient to impersonate only when the file is opened. Make sure to Undo the impersonation (done in the finally clause) since SQL Server will raise an error if the impersonation has not been reverted before execution returns to SQL Server. The way you retrieve the current calling context is by calling SqlContext.WindowsIdentity. This might return NULL if the calling context is not an NT Authenticated login; in this example, we simply return a NULL value for the function when impersonation fails in this manner. So what about OpenRowset(BULK)? You might wonder why should we write this in the CLR, while SQL Server 2005 natively supports the OpenRowset(BULK ‘filename’, SINGLE_BLOB) syntax that does exactly the same thing. While this specific scenario is available natively, there are other such things that you can write in CLR with more flexibility that you cannot do with OpenRowset(BULK); for e.g. retrieve all files in a directory that have a specific extension (I might post this sample in a future entry). You could also choose not to impersonate or to impersonate a fixed security context in the CLR based implementation while with OpenRowset(BULK) you always get impersonation of the caller. The next question I can imagine someone asking is how this performs compared with the native OpenRowset(BULK). My unscientific measurements on the April CTP (IDW 14) reveal that the CLR TVF is slower than OpenRowset(BULK). However, there has been some recent performance work on improving the transition cost coming back from managed code to SQL Server which should bring the performance of the CLR TVF to be close to that of OpenRowset. This performance improvement will be available in the next CTP of SQL Server 2005. - Balaji Rathakrishnan Microsoft SQL Server This posting is provided "AS IS" with no warranties, and confers no rights. Thanks for the sample. Would it be possible to post the client side code that calls this method and chunks file to the client file? Also, maybe you could post the reverse too. Uploading file to SQL using this method. Thanks much! — William Stacey [MVP] Hi William, Can you give us a detailed description of your scenario? We would be glad to help you with a sample if we understand your needs better. Thanks, Sashi William, Chunking the returned contents of this TVF (or for that matter any LOB value from the server) should be possible by writing an ADO.NET program that sets the CommandBehavior property of the SqlCommand to "SequentialAccess". If you execute such a command, the resultant SqlDataReader will load LOB data as a stream. You can then use the GetBytes or GetChars method to specify a byte location to start the read operation, and a limited buffer size for the data being returned. If you think you still need a sample, let us know. As for the other direction, it is unfortunately not possible to "stream" a LOB value as an input parameter into SQL Server from the client as an argument of a stored procedure. (The client will buffer the entire value before sending it to the server). Balaji Rathakrishnan Microsoft SQL Server Yes please, would still like a client sample. There is something similar in a MSDN article (I think), but would like to see another implementation in the context of your server sample. The sample case could be this: You have a message row in sql db. Message has subject, body, and can have 0 or more attachments. Get message row and all attachments. Attachment reading should be stream based so not to load large files into mem on client. GetAttachments(string[] attachmentIDs) could be a seperate call instead of grabbing attachments with the message. Thanks for the feedback so far. 2005 looks great! Also.. It seems to me like explict support for .Net Streams could be supported and would make this kind of thing natural for the client side consumer. The SQLClient could create and hook-up the stream (i.e. NetworkStream) based on the reply results. Would seem possible to do both read and write streams. This may need to happen outside the normal SP context – not sure, but think it can be done (all most things.) Naturally, I could probably do this kind of thing with DIME and WSE 2.0 (or 3.0 and MTOM) if WSE was supported from SQLCLR (is it or will it?) Thanks again! Is it possible to create similar function with OLAP SQL Server 2005 access. The same way as you loaded a document. is there a way read data from a table and write to a document in filesystem? I was looking for more information on Table-Valued Functions (TVF) in SQL Server in attempting to perform Yesterday I wrote about that the SQLCLR team had started blogging, and today I saw their first "real"
https://blogs.msdn.microsoft.com/sqlclr/2005/05/05/file-access-and-table-valued-functions/
CC-MAIN-2018-17
refinedweb
2,189
52.9
Hello! How to download a file without a browser using Sikuli? For example how to get Google's logo (https:/ Thanks in advance! Question information - Language: - English Edit question - Status: - Solved - For: - Sikuli Edit question - Assignee: - No assignee Edit question - Solved by: - TestMechanic - Solved: - 2017-11-15 - Last query: - 2017-11-15 - Last reply: - 2017-11-15 import urllib urllib. Notes: 1. file location is in windows format - change if needed for mac/linux 2. In IDE you may have problem to run this twice - restart IDE if needed. I guess it will be fine when starting code as script Thanks TestMechanic, that solved my question. There are tools for doing this, e.g. wget available at http://. org/software/ wget/
https://answers.launchpad.net/sikuli/+question/660787
CC-MAIN-2017-51
refinedweb
121
74.29
- Configure your Google account - Create a new project from a template - Create a Kubernetes cluster from within GitLab - Install Ingress - Configure your base domain - Enable Auto DevOps (optional) - Deploy the application - Conclusion Getting started with Auto DevOps This step-by-step guide helps you use Auto DevOps to deploy a project hosted on GitLab.com to Google Kubernetes Engine. You are using the GitLab native Kubernetes integration, so you don’t need to create a Kubernetes cluster manually using the Google Cloud Platform console. You are creating and deploying a simple application that you create from a GitLab template. These instructions also work for a self-managed GitLab instance; ensure your own runners are configured and Google OAuth is enabled. Configure your Google account Before creating and connecting your Kubernetes cluster to your GitLab project, you need a Google Cloud Platform account. Sign in with an existing Google account, such as the one you use to access Gmail or Google Drive, or create a new one. - Follow the steps described in the “Before you begin” section of the Kubernetes Engine documentation to enable the required APIs and related services. - Ensure you’ve created a billing account with Google Cloud Platform. Create a new project from a template We are using a GitLab project template to get started. As the name suggests, those projects provide a bare-bones application built on some well-known frameworks. - In GitLab, click the plus icon () at the top of the navigation bar, and select New project. Go to the Create from template tab, where you can choose among a Ruby on Rails, Spring, or NodeJS Express project. For this tutorial, use the Ruby on Rails template. Give your project a name, optionally a description, and make it public so that you can take advantage of the features available in the GitLab Ultimate plan. - Click Create project. Now that you’ve created a project, create the Kubernetes cluster to deploy this project to. Create a Kubernetes cluster from within GitLab On your project’s landing page, click Add Kubernetes cluster (note that this option is also available when you navigate to Infrastructure > Kubernetes clusters). On the Add a Kubernetes cluster integration page, click the Create new cluster tab, then click Google GKE. Connect with your Google account, and click Allow to allow access to your Google account. (This authorization request is only displayed the first time you connect GitLab with your Google account.) After authorizing access, the Add a Kubernetes cluster integration page is displayed. In the Enter the details for your Kubernetes cluster section, provide details about your cluster: - Kubernetes cluster name - Environment scope - Leave this field unchanged. - Google Cloud Platform project - Select a project. When you configured your Google account, a project should have already been created for you. - Zone - The region/zone to create the cluster in. - Number of nodes - Machine type - For more information about machine types, see Google’s documentation. - Enable Cloud Run for Anthos - Select this checkbox to use the Cloud Run, Istio, and HTTP Load Balancing add-ons for this cluster. - GitLab-managed cluster - Select this checkbox to allow GitLab to manage namespace and service accounts for this cluster. Click Create Kubernetes cluster. After a couple of minutes, the cluster is created. You can also see its status on your GCP dashboard. Install Ingress After your cluster is running, you must install NGINX Ingress Controller as a load balancer, to route traffic from the internet to your application. Because you’ve created a Google GKE cluster in this guide, you can install NGINX Ingress Controller through the GitLab Cluster management project template, or manually with Google Cloud Shell: - Go to your cluster’s details page, and click the Advanced Settings tab. - Click the link to Google Kubernetes Engine to visit the cluster on Google Cloud Console. - On the GKE cluster page, select Connect, then click Run in Cloud Shell. After the Cloud Shell starts, run these commands to install NGINX Ingress Controller: kubectl create ns gitlab-managed-apps helm repo add stable helm repo update helm install ingress stable/nginx-ingress -n gitlab-managed-apps # Check that the ingress controller is installed successfully kubectl get service ingress-nginx-ingress-controller -n gitlab-managed-apps Configure your base domain Follow these steps to configure the Base Domain where your apps will be accessible. A few minutes after you install NGINX, the load balancer obtains an IP address, and you can get the external IP address with the following command: kubectl get service ingress-nginx-ingress-controller -n gitlab-managed-apps -ojson | jq -r '.status.loadBalancer.ingress[].ip' Replace gitlab-managed-appsif you have overwritten your namespace. Copy this IP address, as you need it in the next step. Go back to the cluster page on GitLab, and go to the Details tab. - Add your Base domain. For this guide, use the domain <IP address>.nip.io. - Click Save changes. Enable Auto DevOps (optional) While Auto DevOps is enabled by default, Auto DevOps can be disabled at both the instance level (for self-managed instances) and the group level. Complete these steps to enable Auto DevOps if it’s disabled: - Navigate to Settings > CI/CD > Auto DevOps, and click Expand. - Select Default to Auto DevOps pipeline to display more options. - In Deployment strategy, select your desired continuous deployment strategy to deploy the application to production after the pipeline successfully runs on the masterbranch. Click Save changes. After you save your changes, GitLab creates a new pipeline. To view it, go to CI/CD > Pipelines. In the next section, we explain what each job does in the pipeline. Deploy the application When your pipeline runs, what is it doing? To view the jobs in the pipeline, click the pipeline’s status badge. The icon displays when pipeline jobs are running, and updates without refreshing the page to (for success) or (for failure) when the jobs complete. The jobs are separated into stages: - Build - The application builds a Docker image and uploads it to your project’s Container Registry (Auto Build). Test - GitLab runs various checks on the application, but all jobs except testare allowed to fail in the test stage: - The testjob runs unit and integration tests by detecting the language and framework (Auto Test) - The code_qualityjob checks the code quality and is allowed to fail (Auto Code Quality) - The container_scanningjob checks the Docker container if it has any vulnerabilities and is allowed to fail (Auto Container Scanning) - The dependency_scanningjob checks if the application has any dependencies susceptible to vulnerabilities and is allowed to fail (Auto Dependency Scanning) - Jobs suffixed with -sastrun static analysis on the current code to check for potential security issues, and are allowed to fail (Auto SAST) - The secret-detectionjob checks for leaked secrets and is allowed to fail (Auto Secret Detection) - The license_scanningjob searches the application’s dependencies to determine each of their licenses and is allowed to fail (Auto License Compliance) Review - Pipelines on masterinclude this stage with a dast_environment_deployjob. To learn more, see Dynamic Application Security Testing (DAST). Production - After the tests and checks finish, the application deploys in Kubernetes (Auto Deploy). Performance - Performance tests are run on the deployed application (Auto Browser Performance Testing). - Cleanup - Pipelines on masterinclude this stage with a stop_dast_environmentjob. After running a pipeline, you should view your deployed website and learn how to monitor it. Monitor your project After successfully deploying your application, you can view its website and check on its health on the Environments page by navigating to Deployments > Environments. This page displays details about the deployed applications, and the right-hand column displays icons that link you to common environment tasks: - Open live environment () - Opens the URL of the application deployed in production - Monitoring () - Opens the metrics page where Prometheus collects data about the Kubernetes cluster and how the application affects it in terms of memory usage, CPU usage, and latency - Deploy to ( ) - Displays a list of environments you can deploy to - Terminal () - Opens a web terminal session inside the container where the application is running - Re-deploy to environment () - For more information, see Retrying and rolling back - Stop environment () - For more information, see Stopping an environment GitLab displays the Deploy Board below the environment’s information, with squares representing pods in your Kubernetes cluster, color-coded to show their status. Hovering over a square on the deploy board displays the state of the deployment, and clicking the square takes you to the pod’s logs page. REPLICASCI/CD variable in Settings > CI/CD > Variables. Work with branches Following the GitLab flow, you should next create a feature branch to add content to your application: - In your project’s repository, navigate to the following file: app/views/welcome/index.html.erb. This file should only contain a paragraph: <p>You're on Rails!</p>. - Open the GitLab Web IDE to make the change. Edit the file so it contains: <p>You're on Rails! Powered by GitLab Auto DevOps.</p> Stage the file. Add a commit message, then create a new branch and a merge request by clicking Commit. After submitting the merge request, GitLab runs your pipeline, and all the jobs in it, as described previously, in addition to a few more that run only on branches other than master. After a few minutes a test fails, which means a test was ‘broken’ by your change. Click on the failed test job to see more information about To fix the broken test: - Return to the Overview page for your merge request, and click Open in Web IDE. - In the left-hand directory of files, find the test/controllers/welcome_controller_test.rbfile, and click it to open it. - Change line 7 to say You're on Rails! Powered by GitLab Auto DevOps. - Click Commit. - In the left-hand column, under Unstaged changes, click the checkmark icon () to stage the changes. - Write a commit message, and click Commit. Return to the Overview page of your merge request, and you should not only see the test passing, but also the application deployed as a review application. You can visit it by clicking the View app button to see your changes deployed. After merging the merge request, GitLab runs the pipeline on the master branch, and then deploys the application to production. Conclusion After implementing this project, you should have a solid understanding of the basics of Auto DevOps. You started from building and testing, to deploying and monitoring an application all in GitLab. Despite its automatic nature, Auto DevOps can also be configured and customized to fit your workflow. Here are some helpful resources for further reading:
https://docs.gitlab.com/14.0/ee/topics/autodevops/quick_start_guide.html
CC-MAIN-2021-39
refinedweb
1,767
52.19
Investors eyeing a purchase of ATN International Inc (Symbol: ATNI) stock, but tentative about paying the going market price of $73.29/share, might benefit from considering selling puts among the alternative strategies at their disposal. One interesting put contract in particular, is the March 2019 put at the $70 strike, which has a bid at the time of this writing of $3.80. Collecting that bid as the premium represents a 5.4% return against the $70 commitment, or a 10.9% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Selling a put does not give an investor access to ATNI's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. And the person on the other side of the contract would only benefit from exercising at the $70 strike if doing so produced a better outcome than selling at the going market price. ( Do options carry counterparty risk? This and six other common options myths debunked ). So unless ATN International Inc sees its shares fall 4.4% and the contract is exercised (resulting in a cost basis of $66.20 per share before broker commissions, subtracting the $3.80 from $70), the only upside to the put seller is from collecting that premium for the 10.9% annualized rate of return. Worth considering, is that the annualized 10.9% figure actually exceeds the 0.9% annualized dividend paid by ATN International Inc by 10%, based on the current share price of $73.29. And yet, if an investor was to buy the stock at the going market price in order to collect the dividend, there is greater downside because the stock would have to fall 4.42% to reach the $70 strike price. Always important when discussing dividends is the fact that, in general, dividend amounts are not always predictable and tend to follow the ups and downs of profitability at each company. In the case of ATN International Inc, looking at the dividend history chart for ATNI below can help in judging whether the most recent dividend is likely to continue, and in turn whether it is a reasonable expectation to expect a 0.9% annualized dividend yield. Below is a chart showing the trailing twelve month trading history for ATN International Inc, and highlighting in green where the $70 strike is located relative to that history: The chart above, and the stock's historical volatility, can be a helpful guide in combination with fundamental analysis to judge whether selling the March 2019 put at the $70 strike for the 10.9% annualized rate of return represents good reward for the risks. We calculate the trailing twelve month volatility for ATN International Inc (considering the last 252 trading day closing values as well as today's price of $73.29) to be 38%. For other put options contract ideas at the various different available expirations, visit the ATNI Stock Options page of StockOptionsChannel.com..
https://www.nasdaq.com/articles/commit-buy-atn-international-70-earn-109-annualized-using-options-2018-09-14
CC-MAIN-2021-21
refinedweb
507
53.81
You create and deploy SideShow gadget applications on a Windows Vista personal computer. There is no means to place any active content on the target device over and above the Simple Content Format descriptions of the pages that are to be displayed on it. Simple Content Format descriptions are expressed in Extensible Markup Language (XML). We will consider the content of these descriptions in detail in the section titled "SideShow Content and Endpoints" later in this chapter. A SideShow gadget application can be written in managed or unmanaged code; for the sake of consistency, you will create your SideShow application using managed code and C#. You can create a SideShow gadget application on the personal computer to deliver content to a SideShow device, or you can modify a larger application to send relevant content to a SideShow device. For an example of the former, consider an application that downloads daily weather and tidal updates into a SideShow device for use by river pilots. For an example of the latter, note that the Microsoft Office Outlook 2007 program provides a SideShow gadget application that you can use to send calendar and e-mail notifications to a connected device. If you are creating a personal computer application, it is worth considering how you could add value to it by including some SideShow features-for example, an image editing program could provide a facility that could also download photo album content into a SideShow device. We are going to create our SideShow application using the C# language and Microsoft Visual Studio 2005. To create SideShow applications, you must have downloaded the Microsoft-Windows Software Development Kit for Windows Vista. You can find this on MSDN. It provides a set of libraries and additional components that integrate with your Visual Studio 2005 installation. Next, you need the libraries that let you create the SideShow classes on your personal computer. You can find these in the Windows SideShow .NET Framework Components 1.0, which is also available for download from MSDN. If you have a SideShow device, you can just connect it, and it will become available as a target for SideShow applications configurable in the Control Panel dialog box, which was shown in Figure 8-1. However, you may wish to develop for the platform without having a physical device. Fortunately, an emulator is supplied for this purpose. The emulator runs as a program on your development computer, but it behaves exactly as a real physical device. It communicates to a server that runs on the host machine. The server provides the communications channel between the device and the gadget applications. When the emulator starts, it makes contact with the server process. Before you can use the server, you must register it by issuing this command: WindowsSideShowVirtualDevice.exe /regserver You need to perform the registration only once on a particular machine. This program can be found in the SDK installation directory, for example: C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin An administrator must run the regserver command on the target system. You can do this by starting a command window using "Run as administrator." Once you have registered the server, you should find that you can create an instance of a SideShow device on your personal computer by running this program: VirtualSideShow.exe. You can find the program in the same directory as the server that you started earlier. This command will start an instance of the Virtual SideShow device on your machine. This will register itself with the server and should become visible in the Windows SideShow Control Panel. If you connect gadget applications to the device, these applications will appear on the device menu. You can create multiple SideShow devices if you wish; to do this, follow the VirtualSideShow command with an ID number for the device you are starting. VirtualSideShow.exe 1 This command would start a device with an ID of 1. When you finish using a simulator, you can close it by right-clicking anywhere on the simulator display and selecting Close from the menu that appears. By default, an emulator will retain its state when it closes so that the next time it runs, it will have the same content and configuration as before. If you wish to remove a simulator completely, you can uninstall the SideShow device it is simulating by using the SideShow Control Panel. The sample application we will create is a simple memo system for use by security guards who carry our ultimate flashlight. Our system's customer has asked us to provide a means by which pictures of areas that need special attention, along with text instructions, can be loaded into the flashlight at the start of each shift. The application will be registered on the personal computer as a "Flashlight Memo." On the personal computer, you need to create a program that will allow users to enter pictures and text and create content to send to a SideShow device when the program next connects to the host computer. The device will then allow the user to browse the content after the user disconnects it from the system. The following sections will show you how to create a SideShow gadget application, install it on a host system, and then design the pages to be sent to the SideShow device. A gadget application is a Windows program that includes the SideShow libraries. The program is registered on the host system, and when a SideShow device is connected, the application is started so that it can interact with the device. You can start by creating an application project in Visual Studio 2005. Next, you must add the SideShow library as a reference. Finally, you add a couple of using statements to allow us to refer to the SideShow classes directly. using Microsoft.SideShow; using Microsoft.SideShow.SimpleContentFormat; The first of these allows us to use the SideShow classes to talk to the device. We will use the second when creating Simple Content Format classes, in the section titled "SideShow Content and Endpoints" later in this chapter. For a gadget application to appear on the SideShow Control Panel of a machine, the application must first be registered on it. The list of gadget applications installed on a particular computer is held in registry keys on that computer. There are two key locations, one for gadget applications available to all users, held in the HKEY_LOCAL_MACHINE registry key, and the other that identifies those available to a particular user, held in the HKEY_CURRENT_USER registry key. Figure 8-5 shows a registry entry that we could use for our application. It contains configuration details for the gadget application and also selects some behavior options for the program in the device itself. The registry key itself is the globally unique identifier (GUID) value for that particular gadget. Figure 8-5: Registry entry for our SideShow Flashlight Memo application. You can obtain a unique GUID for any gadget application that you write by using the program uuidgen, which is provided in the SDK directory. The following code is an example of calling it to create the key for the Flashlight Memo gadget: C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin>uuidgen You can then cut the response out of the command prompt window and use it to create a GUID instance in the program. private static readonly Guid gadgetId = new Guid("{}"); Each GUID value is designed to be unique in the world, which will prevent the gadget from being confused with any other. Now that we have an identifier for our gadget, we can create a registry entry for it. The registry entries for the gadget application can be created by hand, but the GadetRegistration class in the SideShow libraries provides a static method called Register that will do this for us. We will call it once during the installation process of the gadget application. The method is shown in Listing 8-1. Listing 8-1: Creating a registry entry for a gadget GadgetRegistration.Register( true, // register for all users gadgetId, // gadget GUID ScfSideShowGadget.ScfEndpointId, // content endpoint - want SCF "Flashlight Memo", // friendly name @"c:\Program Files\FlashlightMemo\FlashlightMemo.exe device", // program parameter @"c:\Program Files\FlashlightMemo\flashlight.ico", // icon location false, // true if online only GadgetCachePolicies.KeepNewest, // cache policy null); // property page GUID The first parameter, "register for all users," determines whether the gadget application is registered for all users. If this parameter is set to true, the entry is made in the HKEY_LOCAL_MACHINE part of the registry, and the application will be available to all users of the machine. If this parameter is set to false, the entry is made in the HKEY_CURRENT_USER area, and the application will work only for the currently authenticated user. The second parameter, "gadget GUID," is the GUID of this gadget application. The operating system uses the GUID to identify the gadget application, giving the key created in the registry this name. The third parameter, "content endpoint," identifies the endpoints that a device must be able to support if our application is to be able to talk to it. At the moment, two endpoints are available: SCF and the ICalendar (ICAL) endpoint. These identify the means by which the gadget application will speak to the SideShow device. If the device does not support the required endpoints, the operating system will not allow the user to connect our application to that device. The fourth parameter, "friendly name," sets the name that the user will see in the operating system gadget Control Panel on the host computer. This is also the name of the gadget displayed on the SideShow device itself. The gadget is going to be called Flashlight Memo, and so that is the text we specify. The fifth parameter identifies the gadget program that will provide content to the SideShow devices when they connect to the computer. The name of the program file can be followed by a parameter which can be used in the application. The next section, "Running the SideShow Gadget Application," shows how this is done. The sixth parameter, "icon location," tells the host computer the location of the file containing the icon for this gadget. The icon appears in the Control Panel and is also downloaded into the gadget itself. The Control Panel uses a 32 × 32 pixel icon and the SideShow device itself uses a 48 × 48 pixel version. If you don't provide an icon location, or the icon is not found, a default icon is used instead. The seventh parameter, "true if online only," tells the system whether the SideShow device should display the content when it is not connected to the host. If this value is set to true, it means that the content will be visible only when the device is connected. The Flashlight Memo items must be visible when the device is disconnected, so this has been set to false. The eighth parameter, "cache policy," selects the way that the SideShow device is to manage message items that it receives. This has been set to KeepNewest, because the newer information is the most important. You can also select KeepOldest, which means that older items will be kept in preference to newer ones. You may combine these with two other settings: KeepFrequentlyAccessed means that the most frequently accessed items are given priority, and KeepRecentlyAccessed selects the most recently accessed content items. The final parameter, "property page GUID," identifies a property page that you can use to modify further settings for this gadget. This can be left null if you don't wish to set properties in this manner. Once you register the gadget, the gadget will appear in the SideShow Control Panel as available for deployment. Figure 8-6 shows our new gadget application in the Windows SideShow Control Panel. The Flashlight Memo gadget has been configured to appear on the Momento SideShow device. Figure 8-6: SideShow Control Panel entry for the Flashlight Memo application. Figure 8-7 shows how our Flashlight Memo gadget appears on a target device. At the moment, no content is being sent, so no information is available. You now need to create the application that will run when the SideShow device connects, and deliver some content to it. Figure 8-7: Flashlight Memo on a SideShow device. When you connect a SideShow device to its host personal computer, the SideShow infrastructure enumerates all the SideShow gadget applications available on it (that is, those gadgets installed on the machine host and selected via the Control Panel). The host computer then starts the gadget application for each gadget, using the program command found in the registry for that gadget. In our case, the command is: c:\Program Files\FlashlightMemo\FlashlightMemo.exe device The application will then run and update the content in the device. You will note the parameter "device" after the application name, which allows us to use the same application to deliver content to the device as is used to prepare the content. The Main method in the application can then detect the parameter and behave appropriately. static void Main(string [] args) { if (args.Length > 0) { if (args[0] == "device") { doUpdateDevice(); } } else { doNormalBehaviour(); } } If the program finds the argument device, it calls the method doUpdateDevice to update the device display; otherwise, the program calls the doNormalBehaviour method. So at this point, we know how to install our gadget application and run it when the device connects. Next, we will consider how to send content to the SideShow device.
https://flylib.com/books/en/3.308.1.70/1/
CC-MAIN-2021-17
refinedweb
2,251
52.7
Python Exit handlers: atexit In this tutorial, you will learn about Exit handlers in Python. Python Exit handlers: atexit module as two functions namely register() and unregister(). These are functions that execute at the time of normal interpreter termination. During abnormal termination, these functions will not be executed. In other words, registered functions not executed during signal losses, internal errors, and usage of os.exit(). Exit handlers : atexit.register() register() takes function and function’s arguments as its arguments. We can pass the same function with different arguments more than once. At the time of termination of an interpreter, all functions registered with atexit are executed. import atexit def ending(n): print('bye %s' %(n)) atexit.register(ending,"Codespeedy") bye Codespeedy Functions are stored in the stack according to their registering order. So, when you give more than two functions they execute in LAST IN FIRST OUT manner. So, assign functions in reverse order to get output in sequence. import atexit def f1(): print(1) def f2(): print(2) atexit.register(f1) atexit.register(f2) 2 1 Using atexit as a decorator import atexit @atexit.register def bye(): print("bye") bye All functions assigned should not return any value. atexit.unregister() When we want some registered function to not execute at the termination unregister() is used. Even though function registered more than once unregister() stops the function from execution at the time of the interpreter termination. import atexit def f1(): print(1) def f2(): print(2) atexit.register(f1) atexit.register(f2) atexit.unregister(f1) 2 Python is a mighty and useful programming language. Because of its open-source nature, we have a vast, number of libraries available for making our work simple and fast. Python Exit handlers: The atexit module is one such module that makes registering and unregistering of methods easier. With the help of this module, you can implement at termination time, and you can also stop methods from executing at termination. To learn how to use NumPy. empty go here: Python numpy.empty() function References:
https://www.codespeedy.com/python-exit-handlers-atexit/
CC-MAIN-2021-17
refinedweb
339
50.84
Export a Flex project or Flex library project as an FXP file Export an ActionScript project in ZIP format (or other archive format) Importing projects Projects requiring special handling Support for Catalyst projects Importing a Flex project or Flex library project Importing a Catalyst FXPL project Resolving font references when importing Catalyst projects Importing a Flex 3 project Comparing changes in a project Importing an ActionScript project Importing projects exported with the Eclipse Export wizard Importing projects into multiple workspaces Importing source files into a new project Exporting Adobe AIR application installer Flash Builder exports Flex projects and Flex library projects in the FXP format. ActionScript projects can only be exported as an archive file, typically in ZIP format. The FXP format is an archive format that includes project folders, files, and metadata about the project. An exported project includes all dependent Flex library projects. When exporting or importing a Flex project, some contents of the project require special handling. Different versions of the Flex SDK You can import a Flex project that references a version of the Flex SDK that is not installed with your Flash Builder installation. See Installed Flex SDKs for information on downloading and installing additional versions of the Flex SDK. If Flash Builder cannot find a specific version of the Flex SDK, a dialog opens allowing you to browse to the SDK. After installing the correct version of the Flex SDK, browse to the location. service files Flex projects that connect to data services contains a services folder that contains links to deployed service files. When exporting the project, Flash Builder exports the links but not the deployed services. Upon import, manually deploy the service files and update the links as necessary. For projects that connect to services using LiveCycle Data Service or BlazeDS, make sure that service destinations are available on the target server. For projects that reference local files, upon import deploy the local files using the same path in the original project. This applies to projects accessing static XML service files or local files for HTTP services or web services. Zend Framework Flex projects that connect to data services using PHP and the Zend Framework contain two configuration files. Upon import, examine these files to make sure that they are configured properly for your system: amf-config.ini gateway.php See Installing Zend Framework for information on installing, configuring, and troubleshooting your Zend Framework installation. Data model files (LiveCycle Data Services) A Flex project that uses LiveCycle Data Services (LCDS) links to a data model file. Upon export and subsequent import, Flash Builder references the actual data model file and not a link to it. If you want to use a linked file, and not the one packaged with the exported project, then change the data model file using project properties. Select Project > Properties > Data Model and make the changes. The menus for this procedure vary slightly between the standalone and plug-in configurations of Flash Builder. Some Flex projects require special handling upon import. See Exporting and importing projects. In Flash Builder, select File > Export Flex Project (FXP). If you have the plug-in version of Flash Builder, select File > Export > Flash Builder > Flash Builder Project. You can also use the context menu for a project in the Package Explorer. Select Export > Flash Builder > Flash Builder Project. In the Export Flex Project wizard, select the project to export. All available projects for export are listed in the Project pop-up menu. (Optional) Enable Validate Project compilation. Use this option to confirm that your project compiles without errors. If there are errors, you can still export the project. Click Finish. For server projects, absolute paths to server resources are saved as path variables. When you later import the project, you specify values for the path variables. In Flash Builder, select File > Export > Other. In the Export wizard, select General > Archive File. Click In the Export wizard select the project and files to export: In the leftmost panel, expand the project to specify project folders to include In the rightmost panel, for each selected folder, specify the files to include. Browse to a location to save the exported project and specify a filename. Specify archive file options and click Finish. Flash Builder can import Flex projects, Flex library projects, and ActionScript projects. Projects can be imported from existing project folders or from files that were previously exported from Flash Builder. You can import multiple versions of the same Flex project or Flex library project. After importing multiple versions, you can compare the versions and copy or merge differences. Some Flex projects require special handling upon import. For example: The project references an earlier version of the Flex SDK The project references service files for access to data The Zend Framework configuration for access to PHP services needs to be updated The project uses LiveCycle Data Services (LCDS) links to a data model file. See Exporting and importing projects for information on projects that require special handling. Flash Builder provides development support to application designers using Adobe® Flash® Catalyst™. Catalyst exports a project as an FXP file. Catalyst exports components in as an FXPL file. An FXPL file is a library package. The FXP and FXPL files can then be imported into Flash Builder for development. For FXP files, the resulting project is a Flex web project that runs in Adobe Flash Player. An FXPL file contains a library file. You can import an FXPL files as a Flex library project or you can import the contents into an existing Flex project. You can create an Adobe AIR project from a Catalyst project. Import the FXP file for the Catalyst project into Flash Builder. Convert the application type for the project from Web (runs in Adobe Flash Player) to Desktop (runs in Adobe AIR). See Changing Flex projects to Adobe AIR projects. You can import a project from an exported FXP file or by navigating to a folder containing the project. The menus available for this procedure vary slightly for the plug-in configuration of Flash Builder. From the Flash Builder menu, select File > Import FXP. If you have the plug-in version of Flash Builder, select File > Import > Flash Builder > Flash Builder Project. You can also use the context menu for the Package Explorer to import a project. (Project folder) If you are importing from an existing project folder, select Project Folder, and navigate to the folder containing the project. (FXP file) If you are importing from an FXP file, select File and navigate to the location of the file. If an FXP file contains more than one project, you can select individual projects to import. (Library project or FXPL project) If you are importing a library project or a Catalyst FXPL project, you have the option to import the contents into an existing project. See Importing a Catalyst FXPL project (FXP file) If a project by the same name exists in the workspace, specify the import method: Import as New. Overwrite existing project: Select the project to overwrite. The previous version of the project is permanently removed. (Path variables) If you are importing a project that defines path variables, update path variables for the project. Projects compiled for ColdFusion, PHP, LiveCycle Data Services, or other server technologies use path variables to access a web server and server resources. Other projects can have user-defined path variables. each path variable and provide a valid value for the variable. (Font references) If you are importing an FXP exported by Catalyst, the project can contain font references. You have the option to resolve references to fonts. See Resolving font references when importing Catalyst projects. (PHP server projects) If you are importing a project of application server type PHP, then install or update your Zend installation. The Zend dialog guides you through the process. (Server projects) Deploy services. Manually place services in the web root of the server. Use the same directory structure that was used in the original project. In the Data/Services view, from the context menu for a service, select Refresh. A Catalyst FXPL project is a library project created by Adobe Catalyst. When you import an FXPL project, you have the option to import the contents into another Flex project or Flex library project. This feature is designed to help developers working with Catalyst application designers. However, you can use this feature to import the contents of any library project into another Flex project or Flex library project. The menus available for this procedure vary slightly for the plug-in configuration of Flash Builder. This procedure assumes that you are importing a library project. Select File and navigate to the location of the file. Specify the import method: Import a new copy of. Import contents into existing project. For Source Folder, browse to a src folder of an existing project. For Package, browse to an existing package or specify a new package name for the contents. Overwrite existing project: If a project by the same name exists in the workspace, you can overwrite the existing project. the project to overwrite. The previous version of the project is permanently removed. When importing FXPL files, Flash Builder attempts to resolve references to fonts in the FXPL file. See Resolving font references when importing Catalyst projects. When importing an FXP project created with Adobe Catalyst, the imported project can contain references to fonts that are not available on your system. The Import wizard provides the option to fix font references using CSS. If you select this option, Flash Builder imports the Catalyst style sheet Main.css. Main.css contains references to the fonts used in the project. If you get compile errors from the fonts referenced in the style sheet, fix the references in the style sheet with fonts available on your system. Catalyst FXPL projects do not contain style sheets. Flash Builder attempts to correct any references to fonts when importing an FXPL file. If Flash Builder cannot find a corresponding font on the target system, the original font references are left intact. For FXPL projects, font references that Flash Builder cannot resolve are discovered at runtime. There is either a font substitution or a runtime error for unresolved font references. You can import a Flex 3 project into Flash Builder using Flex 3 Compatibility Mode. In this case, the namespaces and components are unchanged from Flex 3. However, you can take advantage of the compiler available with Flex 4. New documents created in Flex 3 Compatibility Mode use MX components and the following namespace: mx="" In Flash Builder, select File > Import Flex Project. Navigate to the previously exported Flex 3 project ZIP file, or browse to the Flex 3 Project folder. In the Choose Flex SDK Version dialog, make sure that Flex 4 SDK is specified. Select Use Flex 3 Compatibility Mode. Select OK. If you import multiple versions of a project you can compare, copy, or merge the contents of the versions. You can only compare different versions of the same project. In the Package Explorer, select one of the projects you want to compare. Open the Package Explorer context menu and select Compare Project With Version. The Compare Viewer launches, allowing you to compare the project with other versions of the project. Select the version for comparison, which opens the Eclipse Compare Editor. In the compare editor, navigate to the file you want to compare and from the context menu, select Show Content Comparison. The Compare Editor displays both versions of the file, with differences highlighted. You can use Compare Editor options to copy or merge differences in the file. See the Eclipse documentation on the Compare Editor for details. ActionScript projects are exported in ZIP archive format. Use the Eclipse import wizard to import ActionScript projects. In Flash Builder, select File > Import > Other > General > Archive File. You can also use the context menu for the Package Explorer to import an ActionScript project. In the Import Flex Project dialog box, select the ZIP file you want to import. If you have a project that was exported using Eclipse’s Export wizard, use the Eclipse Import wizard to import the project. Select File > Import > General. Then navigate to the appropriate format for your project. For more information, see the Eclipse documentation for importing projects. This documentation is available as Help in the Eclipse Import and Export wizards. If the project contained services created with Flash Builder tools for accessing data services, then you manually have to add the services. Copy the server files in the services folder to an appropriate server. Use the service properties for a server from the Data/Service view to determine the service location. If you exported a PHP project that uses the Zend Framework, the Zend Framework must be installed on the target server. Modify the amf-config.ini file that configures the Zend Framework. For zend_path, specify the absolute path to the Zend installation directory. See Installing Zend Framework for information on installing, configuring, and troubleshooting your Zend Framework installation. When you import a project, you import it into a Flash Builder workspace. A project can be imported into multiple workspaces. In this scenario, the project files exist on disk in one location, but are referenced by each workspace. Changes you make to a project apply to all workspaces. If you have source files and assets on your file system, but are not in a project, you can create a new project for these files. From the Flash Builder menu, select File > New > Project. Project can be a Flex project, Flex library project, or ActionScript project. In the New Project wizard, specify the source and output folder settings to the appropriate location in your file system. For AIR projects, a production build creates a digitally signed AIR file, which users can install before running the application. This process is similar to creating an installer .exe for a typical native application. You can create an unsigned intermediate package, that you can sign later before release. For information on exporting an AIR production build and installer, see Export a release build (Desktop application, runs in Adobe AIR).
http://help.adobe.com/en_US/Flex/4.0/UsingFlashBuilder/WSbde04e3d3e6474c4ef5411412477fbf920-8000.html
CC-MAIN-2017-26
refinedweb
2,359
65.01
I use Python's xml.dom.minidom to process In fact, it's worse than that. Entities just disappear in the processed Given times.dtd and times.xml <?xml version="1.0"?> <!DOCTYPE times SYSTEM "times.dtd"> <maths> <mn>2</mn> <mo>×</mo> <mn>3</mn> <mo>=</mo> <mn>6</mn> </maths> and then times.py import sys, xml.dom.minidom sys.stdout.write(xml.dom.minidom.parse("times.xml").toxml()) you get > python times.py 2 3 = 6 Belgium! I find the Python documentation for xml.dom quite daunting. From what I can tell you should be able to configure the whole experience—the parser, the entity resolver, one lump or two... Until I work out how to do all that, my intermediate solution is to preprocess using xmllint to expand entities, before calling minidom: here's times2.py import os, subprocess, sys, xml.dom.minidom cmd_fo = open("times_expanded.xml", "w") fail = subprocess.call("xmllint --loaddtd --noent " + "times.xml", shell=True, stdout=cmd_fo, stderr=sys.stderr, close_fds=(os.name=="posix"), universal_newlines=True) cmd_fo.close() sys.stdout.write(xml.dom.minidom.parse("times_expanded.xml").toxml()) which results in > python times2.py 2 × 3 = 6 Not very elegant though, is it? Good news everyone: there's an alternate solution over at Stack Overflow, but it's still not perfect: use lxml instead of xml.dom.minidom. Unfortunately lxml doesn't come with the standard Python distribution, so I had to use my package manager to install python-lxml. This time with a times3.py import sys from lxml import etree parser = etree.XMLParser(load_dtd=True) doc_DOM = etree.parse("times.xml", parser=parser) sys.stdout.write(etree.tostring(doc_DOM) + '\n') we get > python times3.py 2 × 3 = 6 I think for the time being I'll stick with xmllint plus xml.dom.minidom, for greater portability.
https://www.nag.co.uk/blog/loading-dtds-using-dom-python
CC-MAIN-2020-24
refinedweb
304
55.5
Subject: Re: [boost] Interest in simple unformatted binary stream I/O? From: Daniel James (dnljms_at_[hidden]) Date: 2011-04-25 09:08:02 On 24 April 2011 13:12, Beman Dawes <bdawes_at_[hidden]> wrote: > > It seems way too small and simple to be a whole library itself. Are > there any ideas where it should live and what namespace it should be > in? 'boost/io' seem like the right place. says, "This sub-library should contain various items to use with/for the standard I/O library". Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2011/04/180722.php
CC-MAIN-2021-39
refinedweb
108
78.25
55115/how-import-json-file-and-encrypt-using-ase-mode-cbc-encryption Hi @Ahmed. Here's a sample code that reads the data from a json file, converts it into a string and then encrypt: import json from Cryptodome.Cipher import AES with open('path_to_file/filename.json') as f: text=json.dumps(f) key = '0123456789abcdef' IV='0123456789abcdef' mode = AES.MODE_CBC encryptor = AES.new(key.encode('utf8'), mode,IV=IV.encode('utf8')) ciphertext = encryptor.encrypt(text) Hi, @Shubham, Web scraping is the technique to ...READ MORE You can find the explanation and implementation ...READ MORE I am trying to count all the ...READ MORE Hello @kartik, According to pip documentation example 3: pip install --upgrade ...READ MORE You can also use the random library's ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE can you give an example using a ...READ MORE I'm using Ubuntu win. on python I ...READ MORE Here am talking about my example you ...READ MORE The code that I've written below. The ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/55115/how-import-json-file-and-encrypt-using-ase-mode-cbc-encryption
CC-MAIN-2020-40
refinedweb
181
64.07
Okydoky 0.9.6 Automated docs builder using Sphinx/GitHub/Distribute for private use Okydoky is an automated documentation builder using Sphinx, GitHub and Distribute (which was setuptools). It makes your closed Python project to continuously build documentations, with the following assumptions: - Documentation is done using Sphinx. - Project is packaged through setuptools (not pip nor any others). - Source code is managed under GitHub. To say shortly, it’s simply a ReadTheDocs.org for private use. How it works It works in the following instructions: - When new commits are pushed, GitHub triggers Okydoky post-receive hook. - Okydoky downloads tarball archives of pushed commits from GitHub. - Tarball archive gets extracted into a temporary directory. - Sphinx builds the documentation. - When users request the docs using their web browser, Okydoky asks the user to authenticate using GitHub OAuth. - If they has the authorization, Okydoky serves a built docs. How to use It’s an ordinary Python package. You can install it using easy_install: $ easy_install Okydoky This package provides a command line script called okydoky. It’s a web application and also a small web server for itself. It takes a config file <config>. Config files have to contain some required values like GitHub application key and secret key. You have to create a GitHub application to use Okydoky. Its Callback URL is very important. Fill it with: http://<host>/auth/finalize and replaces <host> with the domain name what you’ll use. And then, add a post-receive hook into your GitHub repository: http://<host>/ If you make a config file, then run an Okydoky server using okydoky script: $ okydoky -H 0.0.0.0 -p 8080 yourconfig.py Lastly, you have to make an initial auth to finish installation. Open http://<host>/ in your web browser and login with GitHub from there. Configuration The config file is a normal Python script. It uses Flask’s config system. Read Flask’s docs about config files. - REPOSITORY - The user and repository name e.g. 'crosspop/okydoky'. - CLIENT_ID - The GitHub application’s client key. - CLIENT_SECRET - The GitHub application’s secret key. - SAVE_DIRECTORY - The path of the directory to store data. This directory will store some configured data, tarballs, and built documentations. - SECRET_KEY - The secret key to sign sessions. See Flask’s docs about sessions also. - RECREATE_VIRTUALENV Creates the new virtualenv for every build. It’s a lot slower than not using this, but instead makes free from side effects related site-packages. Set any nonzero value e.g. 1, True if you want to recreate the virtualenv everytime. - COMPLETE_HOOK The callback function (any callable object) which is called when the build has complete. It’s called for each commit, even if it failed. It takes three positional parameters: - (basestring) Commit hash - (basestring) Permalink of the docs. It might be 404 if the build failed. - (tuple) Triple sys.exc_info() function returns if the build failed. None if the build succeeded. You can utilize the last argument for printing the error traceback e.g.: import traceback def COMPLETE_HOOK(commit_id, permalink, exc_info): if exc_info is not None: traceback.print_exception(*exc_info) Special environment variable: OKYDOKY Okydoky sets the special environment variable named OKYDOKY during its build process. You can determine whether it’s built by Okydoky or not. For example, you can add some additional requirements only for Okydoky build in setup.py script: import os from setuptools import setup install_requires = ['Flask', 'SQLAlchemy'] if os.environ.get('OKYDOKY'): install_requires.extend(['Sphinx', 'sphinxcontrib-httpdomain']) setup( name='YourProject', install_requires=install_requires ) Or conf.py for Sphinx: import os if os.environ.get('OKYDOKY'): html_theme = 'nature' else: html_theme = 'default' Open source Okydoky is written by Hong Minhee for Crosspop. It’s distributed under MIT license, and the source code can be found in the GitHub repository. Check out: $ git clone git://github.com/crosspop/okydoky.git Changelog Version 0.9.6 Released on February 12, 2013. - Added RECREATE_VIRTUALENV option which makes it to create the virtualenv for each build. - Added COMPLETE_HOOK option. - Try recreating the virtualenv if the build has failed first. - Added --proxy-fix option for HTTP reverse proxies. - Added --force-https option. - Don’t use github-distutils anymore to prevent several headaches related packaging and distribution. Version 0.9.5 Released on September 16, 2012. - GitHub forced state for OAuth. Follow that. Version 0.9.4 Released on September 3, 2012. - Use --upgrade option for setup.py develop command. This prevents version conflicts of dependencies. - Build logs are left in the build.txt file. Version 0.9.3 Released on July 18, 2012. Version 0.9.2 Released on July 17, 2012. Hotfix of 0.9.1. Version 0.9.1 Released on July 17, 2012. Hotfix of 0.9.0. - Made okydoky package empty and moved things to okydoky.app module. Version 0.9.0 Released on July 17, 2012. - Initial version. - Author: Hong Minhee - License: MIT License - Categories - Development Status :: 4 - Beta - Environment :: Web Environment - Intended Audience :: Developers - Intended Audience :: System Administrators - License :: OSI Approved :: MIT License - Operating System :: OS Independent - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 2 :: Only - Topic :: Documentation - Topic :: Software Development :: Documentation - Package Index Owner: dahlia - DOAP record: Okydoky-0.9.6.xml
https://pypi.python.org/pypi/Okydoky/
CC-MAIN-2017-26
refinedweb
863
53.27
Documentation ¶ Overview ¶. Index ¶ - func New(service, daemon string) (func(http.Handler) http.Handler, error) - func WrapDoer(doer goahttp.Doer) goahttp.Doer - func WrapTransport(rt http.RoundTripper) http.RoundTripper - type HTTPSegment - Constants ¶ This section is empty. Variables ¶ This section is empty. Functions ¶ func New ¶ ¶ WrapDoer wraps a goa HTTP Doer and creates xray subsegments for traced requests. func WrapTransport ¶), } Types ¶ type HTTPSegment ¶ type HTTPSegment struct { *xray.Segment http.ResponseWriter } HTTPSegment represents an AWS X-Ray segment document for HTTP services. It wraps the AWS X-Ray segment with the http response writer. func (*HTTPSegment) Hijack ¶ func (s *HTTPSegment) Hijack() (net.Conn, *bufio.ReadWriter, error) Hijack supports the http.Hijacker interface. func (*HTTPSegment) RecordRequest ¶ func (s *HTTPSegment) RecordRequest(req *http.Request, namespace string) RecordRequest traces a request. It sets Http.Request & Namespace (ex: "remote") func (*HTTPSegment) RecordResponse ¶ func (s *HTTPSegment) RecordResponse(resp *http.Response) RecordResponse traces a response. It sets Throttle, Fault, Error and HTTP.Response func (*HTTPSegment) Write ¶ func (s *HTTPSegment) Write(p []byte) (int, error) Write records the HTTP response content length and error (if any) and calls the corresponding ResponseWriter method. func (*HTTPSegment) WriteHeader ¶ func (s *HTTPSegment) WriteHeader(code int) WriteHeader records the HTTP response code and calls the corresponding ResponseWriter method.
https://pkg.go.dev/goa.design/goa@v2.2.5+incompatible/http/middleware/xray
CC-MAIN-2022-27
refinedweb
203
53.47
The SHW driver is used in two modes: By a user, from the FSL SHW API in user space, which goes through /dev/fsl_shw to make open(), ioctl(), and close() calls; and by other kernel modules/drivers, which use the FSL SHW API, parts of which are supported directly by the SHW driver. Testing is performed by using the apitest and kernel api test routines developed for the Sahara2 driver. Definition in file shw_driver.h. #include <inttypes.h> #include <stdlib.h> #include <sys/ioctl.h> #include <memory.h> #include <stdio.h> #include "../../sahara2/include/fsl_platform.h" Go to the source code of this file.
http://linux-fsl-imx51.sourcearchive.com/documentation/2.6.31-605.9/shw__driver_8h.html
CC-MAIN-2017-30
refinedweb
104
68.26
So it’s not exactly news on the interwebs that React Context will be stable in the upcoming release of React, React 16.3.0. React Context is/was an experimental feature of React that received better implementation thanks to multiple PRs from contributors. But even though it’s not news, it is worth taking a minute to learn when and how to use it. And that’s what we’ll do here. What problem does Context API solve? React Context is a way for a child component to access a value in a parent component. One familiar problem in React is what is popularly known as prop drilling. Prop drilling occurs in situations where you’re looking to get the state from the top of your react tree to the bottom and you end up passing props through components that do not necessarily need them. React Context solves the problem of props drilling. It allows you to share props or state with an indirect child or parent. Ordinarily, you’d use a state management library like Redux or Mobx, but what if you don’t want to? Or the data to be passed is so minute that using a state management library would be overkill. This is where the new React Context API comes in. What happened to the current Context API? Well, the current Context API is considered to be unstable as it an experimental API and is likely to break in future releases of React. Also, the current and soon to be old Context API had issues with shouldComponentUpdate blocking context changes. This happens when an intermediate component updates using shouldComponentUpdate, React will automatically assume there are no changes and reuse the entire subtree. The problem with that is if the subtree contains a context consumer, the consumer will not receive the latest context. What’s new? With the new React Context API, you should be familiar with three things: The Provider component is used higher in the tree and accepts a prop called value.It provides a root upon which any child in that tree can access the values that are provided by that context provider. render() { return ( \<Provider value={this.state.contextValue}\> {this.props.children} \<. render() { return ( \<Consumer\> {contextValue =\> \<Child arbitraryProp={contextValue} /\>} \</Consumer\> ) } Using React Context API Before I demonstrate how React Context can be used, let’s take a look at this example below that uses prop drilling to get some data, so that we can establish a bit of…wait for it…context. Classic Prop Drilling The online code editor tailored for web applications The code block above is just a short example of how prop drilling works. We had to pass the props data from the top to the bottom even though the components don’t necessarily need it. Now let’s see how this can be solved using React Context. To get started, you have to install the alpha version of React 16.3. npm i react@next react-dom@next React Context The online code editor tailored for web applications Let’s go through the code block above. const JediContext = React.createContext(); We first initialise a new Context and set it to a const variable. It can be set as anything. class JediProvider extends Component { state = { name: "Vader", side: "dark" }; render() { return ( \<JediContext.Provider value={{ state: this.state, turnGood: () =\> this.setState({ side: "good" }) }} \> {this.props.children} \</JediContext.Provider\> ); } } Inside the JediProvider Component, we create a Provider Context inside the render() function as JediContext.Provider . JediContext.Provider accepts a prop called value which is set to the state and a function that updates the state. Now that we have a Provider, how do we consume the data, even across parent to child components? class App extends Component { render() { return ( \<JediProvider\> \<Vader /\> \</JediProvider\> ); } } const Vader = props =\> { return \<Luke /\>; }; const Luke = props =\> { return \<KyloRen /\>; }; const KyloRen = props =\> { return ( \<JediContext.Consumer\> {context =\> ( \<React.Fragment\> \<p\>My grandfather is {context.state.name} \</p\> \<p\>He belonged to the {context.state.side} side\</p\> \<button onClick={context.turnGood}\>Turn\</button\> \</React.Fragment\> )} \</JediContext.Consumer\> ); }; render(\<App /\>, document.getElementById("root")); The first thing to do would be to wrap all the children of the top level App component with the provider we created, which is, JediProvider . That means all of its children will have access to the value in the Context. Almost like the prop drilling method above, the components are passed into each other albeit with no props, no drilling. The difference is in the bottom child which is KyloRen . The KyloRen component uses JediContext.Consumer to pass context as a render prop. Since context holds the state , you can easily use it to display the data that is required. As seen with context.turnGood , we can also use Context to change and update the state. Whenever the button is clicked, it calls the turnGood function that was added as a value in the Provider. Overall, this is a better solution than the prop drilling methods, you don’t have to pass props unnecessarily to component who don’t need them. React Context The online code editor tailored for web applications Is it a Redux killer? No. The new Context API has its. When should you use React Context? You can use it when all you want is simple state management, or in cases where you want to pass some props deeply without the overkill that comes with Redux or MobX. The Context API should be updated and included in the next couple of updates for React. It will definitely be interesting to see the updates and feature changes for the Context API going forward..
https://blog.logrocket.com/how-and-when-to-use-reacts-new-context-api-b584e41b2704/
CC-MAIN-2019-43
refinedweb
939
65.01
Developing for Windows Phone is easy if you have been doing any XAML at all. That’s because you use Silverlight for Windows Phone development. This is a great thing because everything you already know can be applied immediately. This is not to say that there are no new things that you will have to learn. In fact, with the reduced screen size, the ability to change the orientation of the phone and some of the new types of pages, there are actually quite a few things you will need to learn. This article and the next one is your introduction to some of these new UI techniques. This article assumes that you have Visual Studio 2010 and the Windows Phone tools installed along with it. The Windows Phone tools must be downloaded separately and installed with VS 2010. You may also download the free Visual Studio 2010 Express for Windows Phone developer environment. Working with the List Box Control To start out, you will first build a list box that displays a list of products as shown in Figure 1. This is just a standard Windows Phone Page onto which you drag a ListBox control and bind the ItemsSource property of the list box to a collection class of Product objects. You then create a DataTemplate for each ListBoxItem to display the product name and price. Build the Product Class In order to get the list box populated with products, you will need two classes: a Product class with three properties, and a collection class of Product objects. The Product class contains the ProductName, Price and ImageUri properties. For this first sample you will not use the ImageUri, but that property will be used in the next sample. Create; } } The Products class contains an ObservableCollection of Product objects in a property named DataCollection. The constructor of the Products class calls a method named BuildCollection to populate the DataCollection with some sample data as shown in Listing 1. Value Converter As you can see in Figure 1, Price is shown in a currency format. Unfortunately, in the current version of Silverlight for Windows Phone, the StringFormat attribute on the Binding class is absent. Therefore, you need to create a value converter for displaying a value in currency format. Create the PriceConverter class shown in Listing 2 that implements the IValueConverter interface. In the Convert method, you take the “value” parameter passed in and convert it to a decimal value. You then return that value as a string formatted with the “c” option in the ToString() method. Create Classes in XAML Now that you have the Product class, the Products class and the PriceConverter classes created, you" Next, you create an instance of the Products and PriceConverter class in XAML. The constructor for the Products class will create the initial collection of product objects and load the DataCollection property. <phone:PhoneApplicationPage.Resources> <data:Products x: <data:PriceConverter x: </phone:PhoneApplicationPage.Resources> These two classes may now be used within the rest of your XAML by referencing them by their x:Key name. Create List Box Now it is time to create the List Box and connect it to the static resource you created in the XAML above. Listing 3 shows the XAML you use to build the list box for this sample. Let’s break down each of the areas of the ListBox XAML shown in Listing 3. The ItemsSource property references the static resource you created named “productCollection”. This is an instance of the Products class. The Path attribute refers to the DataCollection property that was populated by the BuildCollection method that is called in the constructor of the Products class. Next, you have the definition for each row in the list box defined in the ItemsTemplate. The ItemsTemplate should not be too foreign to anyone that has done XAML. Each row of the ListBox is defined within the <DataTemplate> area of the ItemsTemplate. The DataTemplate contains a <StackPanel> control with two TextBlock controls within it. This allows the two TextBlock controls to be displayed one on top of the other. Notice in the text block that displays the Price the use of the value converter class you created earlier. You bind to the Price property using the Path attribute of the Binding class. However, before the Binding class displays the Price, it passes the value to the converter. The Convert() method of the PriceConverter class formats the price and returns it as a string to be displayed in the TextBlock. Change the Template when the Orientation Changes When you have a phone in your hands you can turn the phone on its side. This gives you a wide view of the screen. If the user switches from the normal portrait orientation of the phone (Figure 1) to a landscape orientation (Figure 2) you end up with more room to display your data horizontally. You can take advantage of this extra room by switching between two different XAML templates when the phone orientation changes. When you have a phone in your hands you can turn the phone on its side. You can take advantage of this extra room by switching between two different XAML templates when the phone orientation changes. Create the Portrait Template The list box that you first built in this article contained a DataTemplate that worked for a portrait mode of the phone. You will now remove that DataTemplate from the ListBox and put it into the Resources section of your page. You will also need to assign a Key to this DataTemplate. Name it “listPortrait” as shown in Listing 4. Now you can modify your list box to set this template as the default ItemTemplate. You will remove all other XAML from your list box except what is shown in the code below: <ListBox x: Create the Landscape Template Create another DataTemplate in the Resources section of your page to display the landscape view as shown in Figure 3. Copy the existing DataTemplate you created for the portrait mode and paste it back in below the listPortrait DataTemplate. Change the x:Key to be listLandscape. Add a StackPanel control around the existing StackPanel and set the new StackPanel’s orientation property to Horizontal. Immediately after this new StackPanel’s opening tag, add an Image control. Modify the Width property of the TextBlock that displays the ProductName property to 400. Since you have more room in landscape mode, most product names will not have to wrap as they might when in portrait mode. Listing 5 shows the complete landscape DataTemplate. Responding to the OrientationChanged Event Now that you have created two different templates, all you need to do is write code to switch between the two templates when the orientation of the phone changes. To accomplish this, first set an attribute in the PhoneApplicationPage called SupportedOrientation to the value PortraitOrLandscape. This attribute will allow the OrientationChanged event to fire. <phone:PhoneApplicationPage x:Class="WPListBox.MainPage" ... SupportedOrientations="PortraitOrLandscape" ... ... > Also, within the PhoneApplicationPage attributes you add an OrientationChanged event and have Visual Studio create the event procedure in the code behind for this page. <phone:PhoneApplicationPage x:Class="WPListBox.MainPage" ... OrientationChanged= "PhoneApplicationPage_OrientationChanged" SupportedOrientations="PortraitOrLandscape" ... ... > In the OrientationChanged event procedure, fires, the new orientation is passed in the “e” argument as the Orientation property. This property can be one of seven control’s ItemTemplate property. This causes the list box to redraw itself using the defined data template. Panorama Control The Windows Phone Panorama control makes creating a wrap-around list of items very quick and easy to accomplish. In this example, I’ll show you how to create a nice panorama out of a collection of photos. You will be able to take a set of your photos, drop them into this project and try out this sample right away. In Figure 3 you can see an example of an application that you can create. I named my panorama page “My Life in Panorama” to show a list of pictures from my life. In Figure 3 I am showing one page of my panorama that shows me at the top of Kilimanjaro in 2004 with some of my fellow climbers, including Richard Campbell and Stephen Forte. The Windows Phone Panorama control makes creating a wrap-around list of items very quick and easy to accomplish. Create the Panorama Page To get started creating your own Panorama application, open Visual Studio 2010 and choose New Project. Click on the Silverlight for Windows Phone tab, then click on Windows Phone Application and set the name to WPPanoramaSample. For this particular sample, do NOT choose the “Windows Phone Panorama Application.” You will want to start with just creating a simple panorama page and not worry about all the data stuff that this project template adds. Once VS has your new project created, click on MainPage.xaml and delete it. Right-mouse click on the project and select Add | Add New Item… from the context menu. Select Windows Phone Panorama Page from the item list and set the Name to MainPage.xaml.> You can find the Panorama control in the Microsoft.Phone.Controls.dll, so Visual Studio added an assembly reference to your project. Visual Studio added an xml namespace with an alias of “controls” to the MainPage.xaml. This is why there is a “controls:” prefix on the Panorama control you see in the XAML. Each Panorama control allows you to create a title that will be displayed across all items that make up your Panorama page. Change the Title property of the Panorama control to “My Life in Panorama.” Add Pictures and PanoramaItem Controls You are now ready to start adding your own pictures to your project and to the panorama. The Panorama control is made up of one or many PanoramaItem controls. Into the “content” of each of these PanoramaItem controls you may put any XAML you want. For our purposes here you will replace the <Grid /> control with an <Image> control. Create a \Images folder in your VS project. Gather any amount of pictures from your life that you wish to display and copy them into the \Images folder in the VS project. Now you are ready to take each picture and create one PanoramaItem control for each picture. Modify the XAML in the MainPage.xaml to look like the following: > Replace my image file names with your image file names and modify the Header of each PanoramaItem control with appropriate headers. Keep the headers short so they are not chopped off. I find that less than 12 characters works best for the Header attribute. After putting in your images go ahead and run your application and you will be able to pan through all your images both forward and backward. When you get to the beginning (or the end) you will see that the control simply scrolls around in a continuous loop. Pivot Control Another cool UI feature of the Windows Phone is the Pivot control. You can think of a Pivot as similar to a Tab control in Windows Forms, WPF or Silverlight. Each “Tab” or PivotItem you create is like a separate little page where you can create any XAML you need. I will now show you how to create a set of PivotItem controls where each control (tab) will display a list box of photos. You will be able to take a set of your photos, drop them into this project and try out this sample right away. In Figure 4 you can see the sample application that you will create. I named it “My Life in Categories” and it has a list of “tabs” across the top. Each tab is a different year and in each year is a list box with a list of pictures from your life. Create the Pivot Page Create this by opening a new instance of VS 2010 and choose New Project. Click on the Silverlight for Windows Phone tab, then click on Windows Phone Application and set the name to WPPivotSample. Do NOT choose the Windows Phone Pivot Application as this will add some extra data stuff that you don’t want to mess with right now. Once Visual Studio has your new project created, click on MainPage.xaml and delete this page. Right-mouse click on the project and select Add | Add New Item… from the context menu. Select Windows Phone Pivot Page from the item list and set the Name to MainPage.xaml. Click the OK button and your new main page will be ready for you to start creating the different Pivot Item controls in your Pivot page. Locate the XAML for the Pivot control within this page; it will look like the following: <!--Pivot Control--> <controls:Pivot <!--Pivot item one--> <controls:PivotItem <Grid /> </controls:PivotItem> <!--Pivot item two--> <controls:PivotItem <Grid /> </controls:PivotItem> </controls:Pivot> Just like the Panorama control, a Pivot control is located in the Microsoft.Phone.Controls.dll, so VS added an assembly reference to your project. VS also added an xml namespace with an alias of “controls” to the MainPage.xaml. This is why there is a “controls:” prefix on the Pivot control you see in the XAML. Each Pivot control allows you to create a title to display at the top of your Pivot control. Modify the Title property to “My Life in Categories.” Add Pictures and PivotItem Controls The Pivot control is made up of one or many PivotItem controls. In each PivotItem control you can put any XAML that you want. In this sample you will replace the Grid control with a ListBox control into which you will place one or more images. Once again, create an \Images folder and add your own pictures to this folder. Next, create a ListBox control within one of your PivotItem controls and add as many ListBoxItem controls as you want, one for each picture. <ListBox> <ListBoxItem> <Image Source="Images/1965-1.jpg" /> </ListBoxItem> ... ... </ListBox> Modify the Header of each PivotItem control with your appropriate headers. Keep the headers short so they are not chopped off. I find less than 12 characters works best for the Header attribute, just like for the Panorama control. Listing 6 shows an example of a couple of PivotItem controls where you group your pictures into a ListBox control within each PivotItem control. Summary This article introduced you to a few of the different UI features you have on a Windows Phone. While you are using Silverlight for your development, there are some unique features that you need to learn how to handle in your code. One of the features is working with orientation changes. When the user changes from a portrait to a landscape mode, you end up with more width, so you can take advantage of this room by switching a DataTemplate for your list box. Panorama pages and Pivot pages make it very easy to create “virtual” scrolling pages of data. In Part 2 of this article you will learn about Launchers, Choosers and using the Application Bar on the Windows Phone. So, download the Windows Phone tools for Visual Studio 2010 and start developing phone apps!
https://www.codemag.com/Article/1201051/Working-with-Windows-Phone-User-Interfaces-Part-1
CC-MAIN-2020-10
refinedweb
2,524
71.14
In this project, we will work with a data set of submissions to popular technology site Hacker News. Hacker News is a site, where user submitted stories ("posts") are voted and commented upon. Hacker News is extremely popular in technology and startup circles, and posts that make it to the top of Hacker News's listings can get hundreds of thousands of visitors as a result. we will work with the file 'hackers_news.csv' which has been reduced from almost 300,000 rows to approximately 20,000 rows by removing all posts that did not receive any comments, and then randomly sampling from the remaining posts. Below are descriptions of the columns: id :The unique identification from the Hacker News for the post title : The title of the post url : The URL that the post links to, if any num_points : The number of points the post acquired, calculated as the total number of upvotes minus the total number of ownvotes num_comments : The number of comments that were made on the post author : The username of the person who submitted the post created_at : The date and time at which the post was submitted we are specifically interested in posts whose title begin with either Ask HN or Show HN. Users submit Ask HN posts to ask the Hacker News community a specific question and Show HN posts are submitted to show the Hacker News community a project, product, or just generally something interesting. we will compare these two types of posts to determine the following: . Average number of comments received on Ask HN and Show HN . Time connection of average comments on any post Now, we will start by importing the libraries we need. step 1 : Data file 'hacker_news.csv' is read as a list of lists and the result is assigned to a variable hn. First five rows of hn are printed. from csv import reader opened_file = open('hacker_news.csv') read_file = reader(opened_file) hn=list(read_file)']] step 2 : In the second steps we have extracted the first row of data, and assigned it to varaible headers. Now, the headers and remaining data is separated as shown below. headers= hn[0] print(headers) hn= hn[1:]']] Now that we have removed the headers from 'hn', we will filter the data and since we are concerned with post titles begining with 'Ask HN' or 'Show HN', we'll create new list of lists containing just the data for those titles. Below we have created empty lists called 'ask_posts', 'show_posts' and 'other_posts' and looped through each row in 'hn' for the title at row[1] and append the rows to respective empty lists. if 'title' starts with : 'Ask HN' : append it to 'ask_posts' 'Show HN' :append it to 'show_posts' all remaing posts will append to 'other_posts' finally, compare the length of all lists with the length of 'hn. ask_posts = [] show_posts = [] other_posts = [] for row in hn : title = row[1] if title.startswith('Ask HN'): ask_posts.append(row) elif title.startswith('Show HN'): show_posts.append(row) else: other_posts.append(row) print(len(ask_posts)) print(len(show_posts)) print(len(other_posts)) print(len(hn)) total = len(ask_posts) + len(show_posts) + len(other_posts) print(total) 1742 1161 17197 20100 20100 Now, when we have created separate list of all type of comments, we will calculate the average of both ask comments and show comments. To calculate the average of comments of a particular category, we need total number of comments and length of 'ask_posts' and 'show_posts' in following steps: total_ask_comments = 0 for row in ask_posts: num_comments = int(row[4]) total_ask_comments += num_comments avg_ask_comments = total_ask_comments/len(ask_posts) avg_ask_comments = "{:.2f}".format(avg_ask_comments) print(avg_ask_comments) total_show_comments = 0 for row in show_posts: num_comments = int(row[4]) total_show_comments += num_comments avg_show_comments = total_show_comments/len(show_posts) avg_show_comments = "{:.2f}".format(avg_show_comments) print(avg_show_comments) 14.04 10.32 Here we saw that on average, ask posts receive more comments than show posts. Since ask posts are more likely to receive comments, we'll focus our remaining analysis just on these posts. Next, we'll determine if ask posts created at a certain time are more likely to attract comments. We'll use the following steps to perform this analysis: we will process following steps: Now, we have a list of lists consisting datetime and number of comments received, we have to extract the 'hour' from the datetime in result_list and number of comments in that hour in following steps: import datetime as dt result_list = [] for row in ask_posts: created_at = row[6] nu_comments = int(row[4]) value = [] value.append(created_at) value.append(nu_comments) result_list.append(value) counts_by_hour = {} comments_by_hour = {} for row in result_list: c_date = row[0] date= dt.datetime.strptime(c_date, "%m/%d/%Y %H:%M") hour = dt.datetime.strftime(date, "%H") if hour not in counts_by_hour: counts_by_hour[hour] = 1 comments_by_hour[hour] = row[1] else: counts_by_hour[hour] += 1 comments_by_hour[hour] += row[1] print(counts_by_hour) print(comments_by_hour) {'08': 48, '06': 44, '14': 107, '18': 108, '00': 54, '19': 110, '07': 34, '20': 80, '21': 109, '16': 108, '12': 73, '09': 45, '03': 54, '22': 71, '15': 116, '01': 60, '13': 85, '05': 46, '11': 58, '10': 59, '04': 47, '23': 68, '17': 100, '02': 58} {'08': 492, '06': 397, '14': 1416, '18': 1430, '00': 439, '19': 1188, '07': 267, '20': 1722, '21': 1745, '16': 1814, '12': 687, '09': 251, '03': 421, '22': 479, '15': 4477, '01': 683, '13': 1253, '05': 464, '11': 641, '10': 793, '04': 337, '23': 543, '17': 1146, '02': 1381} Now, when we have extracted the 'counts_by_hour' and 'comments_by_hour', we'll calculate the average number of the comments for posts created during each hour of the day. avg_by_hour = [] for hr in counts_by_hour: cmt_hour= comments_by_hour[hr] count_hour= counts_by_hour[hr] avg_by_hour.append([hr, cmt_hour/count_hour]) print(avg_by_hour) [['08', 10.25], ['06', 9.022727272727273], ['14', 13.233644859813085], ['18', 13.24074074074074], ['00', 8.12962962962963], ['19', 10.8], ['07', 7.852941176470588], ['20', 21.525], ['21', 16.009174311926607], ['16', 16.796296296296298], ['12', 9.41095890410959], ['09', 5.5777777777777775], ['03', 7.796296296296297], ['22', 6.746478873239437], ['15', 38.5948275862069], ['01', 11.383333333333333], ['13', 14.741176470588234], ['05', 10.08695652173913], ['11', 11.051724137931034], ['10', 13.440677966101696], ['04', 7.170212765957447], ['23', 7.985294117647059], ['17', 11.46], ['02', 23.810344827586206]] we have extracted the list of lists which has elements as ['hour' , 'average number of comments'] but this format makes it hard to identify the hours with the highest values. so, we'll finish by sorting the lists of lists and printing the values in descending order in a format which is easier to read in the following steps: swap_avg_by_hour = [] for row in avg_by_hour: swap_avg_by_hour.append([row[1], row[0]]) sorted_swap = sorted(swap_avg_by_hour, reverse= True) print("Top 5 Hours for Ask Posts Comments.") for row in sorted_swap: hour= row[1] hour_strip= dt.datetime.strptime(hour, "%H") hour_format= dt.datetime.strftime(hour_strip, "%H:%M") final_list= "{hour}:{avg_value:.2f} average comments per post".format(hour=hour_format, avg_value= row[0]) print(final_list) Top 5 Hours for Ask Posts Comments. 15:00:38.59 average comments per post 02:00:23.81 average comments per post 20:00:21.52 average comments per post 16:00:16.80 average comments per post 21:00:16.01 average comments per post 13:00:14.74 average comments per post 10:00:13.44 average comments per post 18:00:13.24 average comments per post 14:00:13.23 average comments per post 17:00:11.46 average comments per post 01:00:11.38 average comments per post 11:00:11.05 average comments per post 19:00:10.80 average comments per post 08:00:10.25 average comments per post 05:00:10.09 average comments per post 12:00:9.41 average comments per post 06:00:9.02 average comments per post 00:00:8.13 average comments per post 23:00:7.99 average comments per post 07:00:7.85 average comments per post 03:00:7.80 average comments per post 04:00:7.17 average comments per post 22:00:6.75 average comments per post 09:00:5.58 average comments per post
https://nbviewer.org/urls/community.dataquest.io/uploads/short-url/5Umthazl3PeP2otRw6CMAYKsPIo.ipynb
CC-MAIN-2022-40
refinedweb
1,335
67.55
This is a discussion on Re: New-bus unit wiring via hints.. - FreeBSD ; On Tuesday 30 October 2007 04:00:28 pm Marcel Moolenaar wrote: > On Oct 30, 2007, at 10:48 AM, John Baldwin wrote: > > >>> That isn't what is happening though. The port marked "1" is at > >>> 0x3f8 > ... On Tuesday 30 October 2007 04:00:28 pm Marcel Moolenaar wrote: >. It would be interesting to see what Windows does since it still maintains 'COM1:' and 'COM2:' device aliases (if those are the correct DOS device names). > >>>" :-) So you are missing that 1) our users really want this feature, and 2) by making hints do the reservation instead of _hard-coding_ it into the driver we know let users dictate how it should work since they can adjust the hints to suit their needs but still satisfy what users expect on off-the-shelf hardware with the default hints that. ? For the vast majority of x86 boxes (including all the varied boxes we have at work) the default hints will work just fine OOTB. Users are free to edit this, so it remains under user control and doesn't require a recompile. > >>>>... So. I misread how uart's stuff works the first time, but I think I understand now, but I think it has its own confusion. So uart_cpu_{i386,amd64} expect there to be uart hints (wait, I thought hints were the great satan?) that are identical to sio hints. Thus: hint.uart.0.at="isa" hint.uart.0.flags="0x10" hint.uart.0.port="0x3f8" hint.uart.0.baud="9600" However, if you have a system with a PCI serial device or where ACPI lists the darn things backwards then uart0 might be the PCI device, and, say, uart2 might be the device corresponding to these hints. The uart(4) driver then goes and scans the hints on its own to find a set of hints that matches the resources for uart2 and migrates the flag (and thus the serial console setting) over to uart2, so uart2 (device at 0x3f8) does get set to the serial console. But /dev/ttyu0 in userland doesn't match hint.uart.0. Instead, the user has to know (how??) that it's /dev/ttyu2 when they setup /etc/ttys to have a getty listening on COM1. That seems very non-intuitive. At least remove the unit numbers or something and do: uart.console.port=0x3f8 uart.console.baud=9600 or some such. It seems very POLA-violating to have uart0 hints match some other unit number. Of course, that solves the console problem but what if someone wants to apply a different property to a device, like hint.foo.0.disable? or hint.foo.0.bar? ("baud" above corresponds to a "bar"). > >>>... Umm, the user can adjust /boot/device.hints (I do) and can even adjust it at boot time in the loader. > > :-) The snag is you want the user to explicitly set it all up whereas I require it to be automated and reliable (_UID and ACPI namespace node names are not reliable as per previous e-mails). > >>... So where do you hang non-ISA devices on "dumb" busses like IIC that ACPI enumerates? Off acpi0 or the relevant parent such as iic0 or smbus0? > >>>! I can appreciate that, though I consider that I'm binding "sio0" to a piece of hardware so that the other settings for sio0 are bound to the hardware and not to the first device that the sio(4) driver decides to attach to. I actually would like the ability to do something akin to 'hint.pci0.18.0.0.disabled=1' to disable a PCI device. (Granted, that's still in MIB form rather than a flat file, but conceptually similar. I still prefer using the kernel env primed via a file in /boot because you can adjust the kernel env easily in the loader.) Another thing to consider is that if you are going to "wire" a device to a specific driver/unit number (so I can make COM1 always be sio0/uart0 and thus always /dev/ttyd0|/dev/ttyu0) you need to make sure you reserve that driver/unit combo so it can't be probed or attached by something else. > >)? No. Having to guess which device to start the getty on rather then being able to always use /dev/ttyd0 is annoying for one, and just always using hints works fine since COM1/COM2 is an effective de facto standard on all the hardware we buy at work. -- John Baldwin _______________________________________________ freebsd-current@freebsd.org mailing list To unsubscribe, send any mail to "freebsd-current-unsubscribe@freebsd.org"
http://fixunix.com/freebsd/287904-re-new-bus-unit-wiring-via-hints.html
CC-MAIN-2016-18
refinedweb
777
68.81
KOL-CE English (en) | Français (fr) | 한국어 (ko) | Русский (ru) | 中文(中国大陆) (zh_CN) | 中文(台灣) (zh_TW) Introduction KOL-CE is Free Pascal/Lazarus port of KOL&MCK devloped by Vladimir Kladov (). KOL-CE is developed by Yury Sidorov and distributed under wxWindows Library Licence. KOL-CE allows to create very compact Win32/WinCE GUI applications (starting from ~40KB executable for project with empty form). MCK is Lazarus package wich allows VISUAL development of KOL-CE projects in Lazarus IDE. Initially KOL-CE was planned as KOL port for WinCE only. But later it was decided to keep Win32 functionality and made it work with FPC smoothly. Original KOL is targeted for Delphi and does not work with FPC very well. Original MCK can not be used with Lazarus at all. Requirements - Free Pascal compiler 2.2.0 or later for Win32. - arm-wince cross compiler 2.2.0 or later for Win32 (for WinCE development). - Lazarus 0.9.26 or later for Win32. Supported targets - All 32-bit Windows: from Windows 95 to Windows 8.1. - Windows CE based PocketPC and Smartphones. Download Download the latest release of KOL-CE here. Also you can check out the freshest KOL-CE sources from svn using this link: Installation Important: Since KOL-CE 2.80.2 DisableFakeMethods define is not needed anymore. If you previously used KOL-CE 2.80.1 or older, you need to rebuild Lazarus without DisableFakeMethods define before installing MCK package. Otherwise event handlers will not work! To do that: - Run Lazarus. - Choose Tools > Configure "Build Lazarus"... menu item. - Choose Clean Up + Build all on Quick Build Options page. - Open Advanced Build Options page and remove -dDisableFakeMethods from Options input field. - Click Build button to rebuild Lazarus. - Download KOL-CE sources and put them on some folder on your filesystem. - Run Lazarus and choose Components > Load package file menu item. Then navigate to MCK folder and choose MirrorKOLPackage.lpk file. - Package window will appear. Press Install button. - Lazarus will compile MCK package and IDE will be restarted. - After restart KOL tab will appear on components palette. NOTE: If you can't see all KOL components on the palette, resize window with components palette vertically. You will see the second row of components on KOL tab (as on screenshot above). MCK package upgrade is very simple as well. Just overwrite KOL-CE sources with new version, open MCK package and press Install button to recompile the package. Using MCK Creating MCK project - Start Lazarus and select File > New... menu item. - Choose KOL Application under Project section and press OK button. - New project for KOL application will be created. - Save this project with desired name. - Play with your new KOL/MCK Project (adjust parameters, drop TKOL... components, compile, run, debug, etc.) Enjoy! Adding a form - Select File > New... menu item. - Choose KOL Form under File section and press OK button. - Save new form with desired name. Writing code Do not use names from RTL/FCL/LCL, especially from SysUtils, Classes, Forms, etc. All what you need, you should find in KOL, Windows, Messages units. And may be, write by yourself (or copy from another sources). When you write code in mirror project - usually place it in event handlers. You also can add any code where you wish but avoid changing first section of your mirror LCL form class declaration. And do not change auto-generated inc-files. Always remember, that code, that you write in mirror project, must be accepted both by LCL and KOL. By LCL - at the stage of compiling mirror project (and this is necessary, because otherwise converting mirror project to reflected KOL project will not be possible). And by KOL - at the stage of compiling written code in KOL namespace. IMPORTANT To resolve conflict between words LCL.Self and KOL.@Self, which are interpreted differently in KOL and LCL, special field is introduced - Form. In LCL, Form property of TKOLForm component "returns" Self, i.e. form object itself. And in KOL, Form: PControl is a field of object, containing resulting form object. Since this, it is correctly to change form's properties in following way: Form.Caption := 'Hello!'; (Though old-style operator Caption := 'Hello!'; is compiled normally while converting mirror project to KOL, it will be wrong in KOL environment). But discussed above word Form is only to access form's properties - not its child controls. You access child controls and form event handlers by usual way. e.g.: Button1.Caption := 'OK'; Button1Click(Form); Run-time form creation It is possible to create several instances of the same form at run-time. And at least, it is possible to make form not AutoCreate, and create it programmatically when needed. Use global function NewForm1 (replacing Form1 with your mirror form name), for instance: NewForm1( TempForm1, Applet ); To make this possible, NEVER access global variable created in the unit during conversation, unless You know why You are doing so. Refer to Form variable instead. WinCE Setup You need to install arm-wince cross compiler for Win32 to compile WinCE executables. Get it here. To compile for arm-wince target open compiler options of your project using Project > Compiler options... menu item. Open Code tab and change target platform to arm-wince. NOTE: You can receive the following error while compiling your KOL-CE project for WinCE: Compiling resource KOL-CE.rc arm-wince-windres.exe: no resources KOL.PAS(57901) Error: Error while linking KOL.PAS(57901) Fatal: There were 1 errors compiling module, stopping In such case you need to edit Windows PATH environment variable and add path to folder where win32 fpc binaries are located. To find out which path to add, go to Environment options in Lazarus and see compiler path. Quit Lazarus before editing PATH. To edit PATH variable right click on My Computer icon go to Advanced tab and click Environment Variables button. Hints and notes - To make form fullscreen as most Pocket PC applications have, don't change the form position and size. If form size and/or position was changed the form will look like dialog with caption and close button. In MCK set defaultSize and defaultPosition of TKOLForm to True to make form fullscreen. Known issues - The following components are not supported: RichEdit. - Transparency and double buffering are not supported. - Only gsVertical, gsHorizontal gradient panel styles are supported. - Horizontal text alignment does not work in single line edit control. Use memo if you need text alignment. - Vertical text alignment does not work for panel and label. Documentation - Visit official KOL&MCK website for documentation and information: - Read MCK documentation in KOLmirrorReadme.txt file inside MCK folder. KOL-CE in real-world applications See also - The KOL main page - Official KOL&MCK website - KOL-CE page at SourceForge - WinCE port of Free Pascal - Windows CE Interface - Windows CE Development Notes Contacts Report bugs, submit patches and ask questions at project's page at SourceForge:
http://wiki.freepascal.org/KOL-CE
CC-MAIN-2014-41
refinedweb
1,153
68.16
mongod (1) - Linux Man Pages mongod: MongoDB Server NAM runtime configuration of mongod. The options are equivalent to the command-line configuration options. See for more information. Ensure the configuration file uses ASCII encoding. mongod does not support configuration files with non-ASCII encoding, including: - • - output from database commands - • - replication activity - • - connection accepted events - • - connection closed events - --port <port> - Specifies the port number when the MongoDB instance is not running on the standard port of 27017. You may also specify the port number using the --host option. - --bind_ip <ip address> - Specifies the IP address that the mongod process binds to and listens for connections on. By default mongod listens for connections for all interfaces. You may attach mongod to any interface. When attaching mongod to a publicly accessible interface, ensure that you have implemented proper authentication and firewalllog. The default is user. The value you specify must be supportedappend,. Specify one of the following values: - --diaglog <value> - Deprecated since version 2.6. --diaglog is for internal use and not intended for most users. Creates a very verbose, diagnostic log for troubleshooting and recording various errors. MongoDB writes these log files in the dbpath directory in a series of files that begin with the string diaglog and end with the initiation time of the logging as a hex string. The specified value. - --traceExceptions - For internal diagnostic use only. - --pidfilepath <path> - Specifies a file location to hold the "PID" or process ID of the mongod process. Useful for tracking the mongod process in combination with the --fork option. Without a specified --pidfilepath option, mongod creates no PID file. - --keyFile <file> - Specifies the path to a key file to store authentication information.eter supports the following options: - • - enableLocalhostAuthBypass - • - enableTestCommands - • - journalCommitInterval - • - logLevel - • - logUserIds - • - notablescan - • - quiet - • - replApplyBatchSize - • - replIndexPrefetch - • - supportCompatibilityFormPrivilegeDocuments - • - syncdelay - • - textSearchEnabled - • - traceExceptions - • - saslauthdPath - • - authenticationMechanisms - • - sslMode - • -beros Authentication. - --nohttpinterface - Deprecated since version 2.6: MongoDB disables the HTTP interface by default. Disables the HTTP interface. Do not use in conjunction with --rest or --jsonp. NOTE: In MongoDB Enterprise, the HTTP Console does not support Kerberos Authentication. - --clusterAuthMode <option> - New in version 2.6. Enables internal x.509 authentication for membership to the cluster or replica set. The --clusterAuthMode option can have one of the following values: MongoDB instance using an IPv6 network. All MongoDB programs and processes, including mongod, disable IPv6 support by default. - --jsonp - Permits JSONP access via an HTTP interface. Consider the security database logs all slow queries to the log, even when the profiler is not turned on. When the database profiler is on, mongod the profiler writes to the system.profile collection. See the profile command for more information on the database profiler. - --profile <level> - Changes the level of database profiling, which inserts information about operation performance into output of mongod or the log file. The following levels are available: Profiling is off by default. Database profiling can impact database performance. Enable this option only after careful consideration. - - information provides the page size, the number of physical pages, and the number of available physical pages. - --dbpath <path> - Specifies the directory where the mongod instance stores. - --directoryperdb - Alters - - performance penalties during normal operations. - --nssize <value> - Specifies the default size for namespace files (i.e .ns). This option has no impact on the size of existing namespace files. The maximum size is 2047 megabytes. The default value is 16 megabytes, which provides for approximately performance of mongod if the data files are in an old format. In most cases you should not set this value, so you can exercise the most control over your upgrade process. See the MongoDB release notes (on the download page) for more information about the upgrade process. - --repair - Runs a repair routine on all databases. This is equivalent to shutting down and running the repairDatabase database command on all databases. restore the data files to a pristine state automatically. - runtime. Changed in version 2.4: MongoDB enables --objcheck by default, to prevent any client from inserting malformed or invalid BSON into a MongoDB database. - --noobjcheck - New in version 2.4. Disables the default document validation that MongoDB performs on all incoming BSON documents. - - journalCommitInterval to a third of the set value. - --shutdown - Used in control scripts, the --shutdown cleanly and safely termin argument operation: - • - none - • - all - • - _id_only.ures a "delay" in seconds, for this slave to wait to apply operations from the master node. - --autoresync - For use with the --slave option. When set, --autoresync option allows this slave to automatically resync if it is more than 10 seconds behind the master. This setting may be problematic if the --oplogSize specifies a too small oplog.. - - permanently out of sync with the primary, which may cause significant MongoDB. SSL Options See for full documentation of MongoDB's support. - -Mode <mode> - New in version 2.6. Enables SSL or mixed SSL on a port. The argument to the --sslMode option can be one of the following: The default distribution of MongoDB does not contain support for SSL. For more information on MongoDB and SSL, see. - - sslCAFile enabled without sslWeakCertificateValidation. --sslPEMKeyPassword only if the certificate-key file is encrypted. In all cases, mongod. sslAllowInvalid certificate when establishing the connection. If the client presents a certificate and mongod has --sslWeakCertificateValidation enabled, mong. The default distribution of MongoDB does not contain support for SSL. For more information on MongoDB and SSL, see. - --sslFIPSMode - New in version 2.6. Directs mongod to use the FIPS mode of the installed OpenSSL library. Your system must have a FIPS compliant OpenSSL library to use --sslFIPSMode. The default distribution of MongoDB does not contain support for SSL. For more information on MongoDB and SSL, see. Audit Options - --auditDestination - Enables auditing. The --auditDestination option can have one of the following values: NOTE: The audit system is available only in MongoDB Enterprise. - --auditFormat - Specifies the format of the output file if --auditDestination is file. The --auditFormat can have one of the following values: document of the form: { atype: <expression>, "param.db": <database> } NOTE: The audit system is available only in MongoDB Enterprise. AUTHORMongoDB Documentation Project
https://www.systutorials.com/docs/linux/man/1-mongod/
CC-MAIN-2021-21
refinedweb
1,004
51.55
NAME Test::PureASCII - Test that only ASCII characteres are used in your code SYNOPSIS(); DESCRIPTION This module allows to create tests to ensure that only 7-bit ASCII characters are used on Perl source files. EXPORT The functions available from this module are described next. All of them accept as first argument a reference to a hash containing optional parameters. The usage of those parameters is explained on the Options subchapter. - file_is_pure_ascii([\%opts,] $filename [, $test_name]) checks that $filenamecontains only ASCII characters. The optional argument $test_namewill be included on the output when reporting errors. - all_perl_files_are_pure_ascii([\%opts,] @dirs) find all the Perl source files contained in directories @dirsrecursively and check that they only contain ASCII characters. blibis used as the default directory if none is given. - all_files_are_pure_ascii([\%opts,] @dirs) find all the files (Perl and non-Perl) contained in directories @dirsrecursively and check that they only contain ASCII characters. The current directory is used as the default directory if none is given. Options All the functions from this module accept the following options: - skip => \@list_of_files @list_of_files can contain any combination of string and references to regular expressions. Files matching any of the entries will be skipped. For instance: all_files_are_pure_ascii({ skip => [qr/\.dat$/] }); - skip_data => 1 On Perl files, skip any __DATA__section found at the end. - forbid_control => 1 Tests fail when any control character that is not tab, CR neither LF is found. - forbid_tab => 1 Tests fail when tab characters are found. - forbid_cr => 1 Tests fail when carriage return (CR) characters are found. That can be useful when you want to force people working on your project to use the Unix conventions for line endings. - require_crlf => 1 Test fail when any CR or LF not being part of a CRLF sequence is found. That can be useful when you want to stick to Windows line ending conventions. HINTS The module recognizes some sequences or hints on the tested files that allow to skip specific exceptions. Usually you would include them as Perl comments. - pa_test_ignore the line where this token is found is not checked for pure-ascii - pa_test_skip_lines($n) the line where this token is found and the following $n are skipped - pa_test_end the test for this file ends when this token is found SEE ALSO A nice table containing Unicode and Latin1 codes for common (at least in Europe) non-ASCII characters is available from. AUTHOR.
https://metacpan.org/pod/Test::PureASCII
CC-MAIN-2018-22
refinedweb
393
62.98
Capital Budgeting Concepts Primary Task Response: Within the Discussion Board area, write 500–600 words that respond to the following questions with your thoughts, ideas, and comments. This will be the foundation for future discussions by your classmates. Be substantive and clear, and use examples to reinforce your ideas. Part 1 Summative Discussion Board Review and reflect on the knowledge that. Part 2: - What is the capital budgeting, and what role does it play in long-term investment decisions? - What are the basic capital budgeting models, and which ones are considered the most reliable and why? - What is net present value (NPV), how is it calculated, and what is the basic premise of its decision rule? - What is the internal rate of return (IRR), how is it calculated, and what is the basic premise of its decision rule? - What is the modified internal rate of return (MIRR), how is it calculated, and what is the basic premise of its decision rule? - How is the weighted average cost of capital (WACC) employed in capital budgeting decisions, and should it be used for all project regardless of the riskiness of a project? Be sure to document your posts with in-text citations, credible sources, and properly listed
https://www.studypool.com/discuss/204157/capital-budgeting-concepts
CC-MAIN-2017-26
refinedweb
205
61.26
Distributed Computing with Workers For distributed computing, such as cross-validating a model or tuning some hyper parameters, Cloudera Data Science Workbench provides basic support for leveraging multiple engine instances from a single run. Any R or Python engine can spawn other engines, known as workers, and give them code to execute when they start up. Worker output is displayed in the main console to allow you to debug your code. These workers are terminated when the session exits. For more significant distributed computing needs, using CDS 2.x Powered by Apache Spark from within Cloudera Data Science Workbench is strongly recommended. Spawning Workers Select a language from the code samples below to launch workers: R library("cdsw") workers <- launch.workers(n=2, cpu=0.2, memory=0.5, env="", code="print('Hello from a CDSW Worker')") Python import cdsw workers = cdsw.launch_workers(n=2, cpu=0.2, memory=0.5, code="print('Hello from a CDSW Worker')") Worker Network Communication Workers are a low-level feature to help use higher level libraries that can operate across multiple hosts. As such, you will generally want to use workers only to launch the backends for these libraries. To help you get your workers or distributed computing framework components talking to one another, every worker engine run includes an environmental variable CDSW_MASTER_IP with the fully addressable IP of the master engine. Every engine has a dedicated IP access with no possibility of port conflicts. For instance, the following are trivial examples of two worker engines talking to the master engine. R From the master engine, the following master.r script will launch two workers and accept incoming connections from them. # master.r library("cdsw") # Launch two CDSW workers. These are engines that will run in # the same project, execute a given code or script, and exit. workers <- launch.workers(n=2, cpu=0.2, memory=0.5, env="", script="worker.r") # Accept two connections, one from each worker. Workers will # execute worker.r. for(i in c(1,2)) { # Receive a message from each worker and return a response. con <- socketConnection(host="0.0.0.0", port = 6000, blocking=TRUE, server=TRUE, open="r+") data <- readLines(con, 1) print(paste("Server received:", data)) writeLines("Hello from master!", con) close(con) } The workers will execute the following worker.r script and respond to the master. # worker.r print(Sys.getenv("CDSW_MASTER_IP")) con <- socketConnection(host=Sys.getenv("CDSW_MASTER_IP"), port = 6000, blocking=TRUE, server=FALSE, open="r+") write_resp <- writeLines("Hello from Worker", con) server_resp <- readLines(con, 1) print(paste("Worker received: ", server_resp)) close(con) Python From the master engine, the following master.py script will launch two workers and accept incoming connections from them. # master.py import cdsw, socket # Launch two CDSW workers. These are engines that will run in # the same project, execute a given code or script, and exit. workers = cdsw.launch_workers(n=2, cpu=0.2, memory=0.5, script="worker.py") # Listen on TCP port 6000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("0.0.0.0", 6000)) s.listen(1) # Accept two connections, one from each worker. Workers will # execute worker.py. conn, addr = s.accept() for i in range(2): # Receive a message from each worker and return a response. data = conn.recv(20) if not data: break print("Master received:", data) conn.send("Hello From Server!".encode()) conn.close() The workers will execute the following worker.py script and respond to the master. # worker.py import os, socket # Open a TCP connection to the master. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((os.environ["CDSW_MASTER_IP"], 6000)) # Send some data and receive a response. s.send("Hello From Worker!".encode()) data = s.recv(1024) s.close() print("Worker received:", data)
https://docs.cloudera.com/documentation/data-science-workbench/1-5-x/topics/cdsw_parallel_computing.html
CC-MAIN-2022-21
refinedweb
625
51.34
Announcements Content count92 Joined Last visited Community Reputation713 Good About Tesshu - RankMember Android - Passing errors to a user when opengl context fails to be created Tesshu replied to Nanoha's topic in General and Gameplay ProgrammingIf you're using the NDK then I would strongly recommend you learn the JNI stuff. Some stuff is WAY easier to do in Java. Using JNI you get the best of both worlds. The original glue code Google code included was really just a sample IIRC. I made my own glue code using theirs as a guide. The code starts a native thread and puts an exception handler around it. When a C++ exception is caught, I re-throw it using JNI to the JVM. So it gets logged as a normal Java exception and I get a crash report on the Google Play Developer Console. I even log Java exceptions that happened when my C++ code called some Java code. The other thing I have is a custom build I give out if I have a user that is willing to work with me. The app logs everything to a file and makes sure it's flushed after each entry. Next time the app starts, if it sees a file it blocks while it sends it to my website. Then it deletes the file. Sony C#/.NET Component Set Analysis Tesshu commented on PVS-studio team's article in Engines and MiddlewareI thought ferrous was suggesting that the tool shouldn't have flagged it as an issue when clearly the tool got it right. As to what the code wants to do is hard to say for sure without seeing it all. It's likely not up to the tool to know what the coder wants... Sony C#/.NET Component Set Analysis Tesshu. Oh and it's great to see another full page Ad for PVS-Studio! Sony C#/.NET Component Set Analysis Tesshu reviewed PVS-studio team's article in Engines and Middleware Using GLES2/3 depending on hardware (Android) Tesshu replied to Nanoha's topic in General and Gameplay ProgrammingThere is also GL_OES_element_index_uint extension that allows u32 indices. I still think you're making more work for yourself than needed. I would get it to run on ES 2.0 and then add and extensions or ES 3.0 as a bonus if time permits. It's pretty trivial to write and index buffer class that handles the breaking up for you as long as you're drawing the whole thing instead of ranges. If you're drawing ranges then you have already broken the index buffer up somehow. Your development workflow Tesshu replied to 00Kevin's topic in General and Gameplay ProgrammingThat one is awesome but I have to say it's not thread safe. Are you telling me you only get tasks from one place! Using GLES2/3 depending on hardware (Android) Tesshu replied to Nanoha's topic in General and Gameplay ProgrammingIf you have managed to write support using ES 2.0 then why bother with 3.0? I'm still at ES 2.0 and won't change until I have no other choice or becomes the dominant version. Why limited your target audience? What I do for this sort of thing is have abstract classes and then check extensions and make run-time choices. This is basically how I do my platform independence also. The indices problem I solved off line by breaking the assets up as part of the asset pipeline. This rarely happens and I would somewhat question why you need that many indices on a mobile device. VertexArrayObject* OpenGLGraphicsDevice::createVertexArrayObject( VertexBuffer& vb, const VertexFormat& vf ) { if ( isOpenGlES3() == true ) return new OpenGLVertexArrayObject( vb, vf, vb.getTag() ); if ( hasOES_vertex_array_object() == true ) return new OpenGLVertexArrayObjectOES( vb, vf, vb.getTag() ); return new OpenGLVertexArrayObjectEmulated( vb, vf, vb.getTag() ); } Making Your C++ Namespace Solid and Future-Proof Tesshu commented on DemonDar's article in General and Gameplay ProgrammingMaybe I exposed that bad, it is not a shorthand at all. Differently from the "typical use" of creating short-hands, I'm here proposing a good(at least according to my opinion:P) use of "using directive". There are no problems of include order etc. and there is no stuff like 2 different versions. Semantically is exactly equivalent to declaring a class with no side-included headers (go back and read sentence again). I know it is a subtle difference and hard to notice at a first and at a second read. I took a better look at what you are doing (waiting for a build to finish). While my initial comments are true they don't fit the scenario you are talking about, as you pointed out. Sorry. I made a poor assumption that you were trying to solve a different problem. Your solution is actually still looking for a problem and it pains me that someone would spend time on this. I would strongly suggest reading what the master has to say about it in Large Scale C++ Software Design by Lakos. A dry piece of text but the guy knows exactly what he is talking about and I got a lot out of this book. The issue is that your header should include everything it needs to compile itself and nothing more. Forward references whenever possible. If it doesn't I would pretty much say it's an error in waiting. Also the cpp that includes it should include it's header first to enforce this principle. The insanity of having two header files with the same name makes me cringe. Anyone trying to read your code or yourself in 6 months is in for a world of hurt... My Year as a Mobile Gamedev Tesshu commented on TadeuszSynZygmunta's article in General and Gameplay ProgrammingWell done! IMHO you have hit a home run. I often counsel people to drop their 3D MMORPG and do a 2D pac man game. Why? Well it's because they don't know what they don't know. They don't realize that their 3D game isn't even a really small tech demo. It maybe 5% done at most and go no where. Small games like yours get finished and have allowed you to experience the WHOLE process. You have gained skills in all areas and are far more equipped to know what goes into a project and get it shipped. Again well done! Maintenance-free Enum to String in Pure C++ with "Better Enums" Tesshu reviewed antron's article in Engines and Middleware Making Your C++ Namespace Solid and Future-Proof Tesshu commented on DemonDar's article in General and Gameplay ProgrammingOuch, that's not the same at all. Something like "using namespace std" is really a mess and is potentially able to pollute namespace and causing very much problems, in my case I'm just exporting 1 name for header (or if it makes sense, just a bunch of names) wich is very different from importing a whole namespace. namespace myPublic{ using K = myPrivate::K; // results in myPublic::K name => same as declaring K inside "myPublic" } Yes you're correct. I noticed this after I posted and thought it might make it under the radar :) I used to do this sort of thing to make short hands for stuff like the following but I stopped this practice. using dmath = dwarf::math; Still there is some truth here and it's really nitpicking but I still wouldn't do it. Headers get included in different orders all the time and having code that compiles two different ways based on include order can be hard to find. Namespaces are designed to prevent this sort of thing and making shorthand versions is really just circumventing the system. Sure the compiler should point out ambiguity for you if there is a problem but it doesn't protect you from old C headers with macros. I would also say the code is harder to read now. Don't spend time on stuff like this as it only takes away from finishing a project. Making Your C++ Namespace Solid and Future-Proof Tesshu commented on DemonDar's article in General and Gameplay ProgrammingThe problem is that you should never have a using declaration in a header. These should only be in cpp files. Use fully qualified namespace names in your headers. Looks bad at first but eventually it will be normal. java.lang.NoClassDefFoundError: Tesshu replied to grumpyOldDude's topic in General and Gameplay ProgrammingWhat about NDK these days? Is it well supported? Mobile games with big file size Tesshu replied to Lionel Pixel's topic in General and Gameplay ProgrammingI would work VERY hard to get this game to be much smaller. Yes there are bigger games but to think your game is so good that people will dump 250MB isn't realistic. It's not an insult or meant to pull you down, it's just reality. There is a reason apps can be sorted by size on your phone and you don't want to be in the top ten in that list. It is SO hard to get people to even try your game and that file size is a deterrent. Have you looked into doing an expansion file on android? It does require work and is one more point of failure you have to deal with. Perhaps I am wrong but I get the feeling this is a small 1-2 person team. If so realistically, I doubt you could have generated that much content. Spend sometime looking how you could reduce the size. Can you tell me what kind of resources are using the most space and perhaps I could offer some advice? Textures, geometry, audio etc Problems Found in Appleseed Source Code Tesshu commented on PVS-studio team's article in General and Gameplay ProgrammingWell I still think it's code shaming as it's a one sided unsolicited code review. If they have in fact asked the authors if they could do this then I am very sorry but there is no mention of it in the article. With that said, what is to say they are errors or issues in the first place? So many time people have come running with 'The Bug' that isn't a bug actually (myself included) because they didn't know the big picture or understand the code. V670: this error could actually be fine if the constructor just wants a reference or address of the variable. V668: if the project doesn't use exceptions and/or has a custom allocator then the test makes sense. Still not even an issue really. V719: is there a compiler known to man that won't report this? Half if not all of these so called issues could be caught with full warnings on and warnings set to errors, which you should do anyway. These aren't articles by the way. These are full screen ads that use the assets of reputable projects. Ads that they run for free...
https://www.gamedev.net/profile/111382-lonedwarf/
CC-MAIN-2017-34
refinedweb
1,844
71.44
On 09/07/10 6:05 -0700, Eric W. Biederman wrote:> Louis Rilling <Louis.Rilling@kerlabs.com> writes:> > > On 08/07/10 21:39 -0700, Eric W. Biederman wrote:> >> > >> Currently it is possible to put proc_mnt before we have flushed the> >> last process that will use the proc_mnt to flush it's proc entries.> >> > >> This race is fixed by not flushing proc entries for dead pid> >> namespaces, and calling pid_ns_release_proc unconditionally from> >> zap_pid_ns_processes after the pid namespace has been declared dead.> >> > One comment below.> >> >> > >> To ensure we don't unnecessarily leak any dcache entries with skipped> >> flushes pid_ns_release_proc flushes the entire proc_mnt when it is> >> called.> >> > >> Signed-off-by: Eric W. Biederman <ebiederm@xmission.com>> >> ---> >> fs/proc/base.c | 9 +++++----> >> fs/proc/root.c | 3 +++> >> kernel/pid_namespace.c | 1 +> >> 3 files changed, 9 insertions(+), 4 deletions(-)> >> > >> diff --git a/fs/proc/base.c b/fs/proc/base.c> >> index acb7ef8..e9d84e1 100644> >> --- a/fs/proc/base.c> >> +++ b/fs/proc/base.c> >> @@ -2742,13 +2742,14 @@ void proc_flush_task(struct task_struct *task)> >> > >> for (i = 0; i <= pid->level; i++) {> >> upid = &pid->numbers[i];> >> +> >> + /* Don't bother flushing dead pid namespaces */> >> + if (test_bit(PIDNS_DEAD, &upid->ns->flags))> >> + continue;> >> +> >> > IMHO, nothing prevents zap_pid_ns_processes() from setting PIDNS_DEAD and> > calling pid_ns_release_proc() right now. zap_pid_ns_processes() does not wait> > for EXIT_DEAD (self-reaping) children to be released.> > Good point we need something probably a lock to prevent proc_mnt from> going away here. We might do a little better if we were starting with> a specific dentry, those at least have some rcu properties but that isn't> a big help.> > Hmm. Perhaps there is a way to completely restructure this flushing> of dentries. It is just an optimization after all so we don't get too many> stale dentries building up.> > It might just be worth it simply kill proc_flush_mnt altogether. I know> it is measurable when we don't do the flushing but perhaps there can> be a work struct that periodically wakes up and smacks stale proc dentries.> > Right now I really don't think proc_flush_task is worth the hassle it> causes.Indeed, proc_flush_task() seems to be the only bad guy trying to accesspid_ns->proc_mnt after the death of the init process.But I don't know enough about the performance impact of removing it.Louis> > Grumble, Grumble more thinking to do.> > Eric> _______________________________________________> Containers mailing list> Containers@lists.linux-foundation.org>-- Dr Louis Rilling KerlabsSkype: louis.rilling Batiment GermaniumPhone: (+33|0) 6 80 89 08 23 80 avenue des Buttes de Coesmes 35700 Rennes[unhandled content-type:application/pgp-signature]
http://lkml.org/lkml/2010/7/9/142
CC-MAIN-2014-52
refinedweb
426
58.58
The QSqlDriver class is an abstract base class for accessing specific SQL databases. More... #include <QSqlDriver> Inherits QObject. The QSqlDriver class is an abstract base class for accessing specific SQL databases.. This enum contains a list of features a driver might support. Use hasFeature() to query whether a feature is supported or not. More information about supported features can be found in the Qt SQL driver documentation. See also hasFeature(). This enum contains a list of SQL identifier types. This enum contains a list of SQL statement (or clause) types the driver can create. See also sqlStatement(). Constructs a new driver with the given parent. Destroys the object and frees any allocated resources. This function is called to begin a transaction. If successful, return true, otherwise return false. The default implementation does nothing and returns false. See also commitTransaction() and rollbackTransaction(). Derived classes must reimplement this pure virtual function in order to close the database connection. Return true on success, false on failure. See also open() and setOpen(). This function is called to commit a transaction. If successful, return true, otherwise return false. The default implementation does nothing and returns false. See also beginTransaction() and rollbackTransaction(). Creates an empty SQL result on the database. Derived classes must reimplement this function and return a QSqlResult object appropriate for their database to the caller. Returns the identifier escaped according to the database rules. identifier can either be a table name or field name, dependent on type. The default implementation does nothing. This is an overloaded member function, provided for convenience. It behaves essentially like the above function. Returns a string representation of the field value for the database. This is used, for example, when constructing INSERT and UPDATE statements. The default implementation returns the value formatted as a string according to the following rules: See also QVariant::toString().Variant v = db.driver()->handle(); if (v.isValid() && v.typeName() == "sqlite3*") { // v.data() returns a pointer to the handle sqlite3 *handle = *static_cast<sqlite3 **>(v.data()); if (handle != 0) { // check that it is not NULL ... } } This snippet returns the handle for PostgreSQL or MySQL: if (v.typeName() == "PGconn*") { PGconn *handle = *static_cast<PGconn **>(v.data()); if (handle != 0) ... } if (v.typeName() == "MYSQL*") { MYSQL *handle = *static_cast<MYSQL **>(v.data()); if (handle != 0) ... } See also QSqlResult::handle(). Returns true if the driver supports feature feature; otherwise returns false. Note that some databases need to be open() before this can be determined. See also DriverFeature. Returns true if the database connection is open; otherwise returns false. Returns true if the there was an error opening the database connection; otherwise returns false. Returns a QSqlError object which contains information about the last error that occurred on the database. See also setLastError(). Derived classes must reimplement this pure virtual function to open a database connection on database db, using user name user, password password, host host, port port and connection options options. The function must return true on success and false on failure. See also setOpen(). Returns the primary index for table tableName. Returns an empty QSqlIndex if the table doesn't have a primary index. The default implementation returns an empty index. Returns a QSqlRecord populated with the names of the fields in table tableName. If no such table exists, an empty record is returned. The default implementation returns an empty record. This function is called to rollback a transaction. If successful, return true, otherwise return false. The default implementation does nothing and returns false. See also beginTransaction() and commitTransaction(). This function is used to set the value of the last error, error, that occurred on the database. See also lastError(). This function sets the open state of the database to open. Derived classes can use this function to report the status of open(). See also open() and setOpenError().(). Returns a SQL statement of type type for the table tableName with the values from rec. If preparedStatement is true, the string will contain placeholders instead of values. This method can be used to manipulate tables without having to worry about database-dependend SQL dialects. For non-prepared statements, the values will be properly escaped..
http://doc.trolltech.com/4.0/qsqldriver.html
crawl-001
refinedweb
684
53.88
Hello guys, I'm new here and hoping to get some kind of help with my code. This code is to calculate sales tax for specific store. I've got the most part of the code working, but I have to modify it so that it continues to loop until the user decides to exit the program. I would appreciate any help and thanks in advance! #include <stdio.h> #include <stdlib.h> main() { //Define the Variables and their Values float fltDelMar = .0725f; //Defines Del Mar's tax percentage float fltEncinitas = .075f; //Defines Encinitas' tax percentage float fltLaJolla = .0775f; //Defines La Jolla's tax percentage float fltAmount; //Defines the sale amount char chrPercent = '\45'; //Defines a % sign for usage in the program int ui; //Defines an integer to hold the scanf amount function from user input to be verfied char storelocation; //Defines the storelocatoin character //Displays information about the tax calculator program printf("Kudler Fine Foods Tax Calculator\n"); printf("\nThis program will calculate the taxable amount based \non the inputed amount for the selected Kudler stores.\n"); printf("\nTax breakdown below:"); printf("\nDel Mar - 7.25%c tax rate", chrPercent); printf("\nEncinitas - 7.5%c tax rate", chrPercent); printf("\nLa Jolla - 7.75%c tax rate\n", chrPercent); { //Allows the user to enter an amount to be taxed printf("\nPlease enter the purchase amount in dollars & cents, then press [ENTER]:$"); ui = scanf("%f",&fltAmount); fflush(stdin); if (ui <= 0) { printf("That is not a valid purchase amount.\n"); } else { //Allows the user to select the store printf("\nPlease select the store to compute tax:\n"); printf("1) DelMar \n2) Encinitas \n3) La Jolla \n"); printf("Select 1, 2, 3: "); //Calculates the tax rates as well as totals the transaction scanf("%c",&storelocation); fgetc(stdin); printf("%c",&storelocation); if (storelocation == '1') { printf("\nDel Mar: Tax= $%.2f, Total= $%.2f\n", fltDelMar * fltAmount, (fltDelMar * fltAmount) + fltAmount); } else if (storelocation == '2') { printf("\nEncinitas: Tax= $%.2f, Total= $%.2f\n", fltEncinitas * fltAmount, (fltEncinitas * fltAmount) + fltAmount); } else if (storelocation == '3') { printf("\nLa Jolla: Tax= $%.2f, Total= $%.2f\n", fltLaJolla * fltAmount, (fltLaJolla * fltAmount) + fltAmount); } else { printf("Entry not acceptable, please choose another selection."); } } //Requires the user to press [ENTER] to exit the program printf("\nThank you for using the tax calculator!\nHave a nice day!!!\n"); printf("\nPress [ENTER] to exit the program..."); getchar(); } }
https://www.daniweb.com/programming/software-development/threads/174767/need-help-with-loop
CC-MAIN-2017-17
refinedweb
386
54.22
Hello, I can’t get rid of Excel, if I have ever called it, even with such a simple script: ---------- code starts -------------- require ‘win32ole’ def puts_win32ole_objects res = [] ObjectSpace.each_object do |o| res << o if o.is_a? WIN32OLE end puts res.inspect end puts_win32ole_objects # --> empty xl = WIN32OLE.new(‘Excel.Application’) puts_win32ole_objects # --> one object xl.Quit xl = nil GC.start # anything else I could do??? puts_win32ole_objects # --> the object is still there sleep 5 And also the Excel process remains running in Windows. Btw, even after the xl.Quit, the object remains fully functional, so I could call o.Visible, o.Workbooks.Open(…) etc., it o were the object (retrieved from ObjectSpace). When the Ruby process is terminated (after sleep), the Excel process will also terminate. So, what’s the proper way to handle this? I’ve found the WIN32OLE.ole_free method, but they say that it is for debugging only. Thanks for your help Sven
https://www.ruby-forum.com/t/how-to-completely-terminate-a-win32ole-excel-object/105162
CC-MAIN-2018-47
refinedweb
153
79.67
Repeater QML Type Instantiates a number of Item-based components using a provided model More... Properties Signals - itemAdded(int index, Item item) - itemRemoved(int index, Item item). The following Repeater creates three instances of a Rectangle item within a Row: import QtQuick 2.0 Row { Repeater { model: 3 Rectangle { width: 100; height: 40 border.width: 1 color: "yellow" } } } " } } Note: A Repeater item owns all items it instantiates. Removing or dynamically destroying an item created by a Repeater results in unpredictable behavior. This property holds the number of items in the model. Note: The number of items in the model as reported by count may differ from the number of created delegates if the Repeater is in the process of instantiating delegates or is incorrectly set up.. See also Data Models. Signal Documentation This signal is emitted signal is handled. The corresponding handler is onItemRemoved..
https://doc.qt.io/archives/qt-5.10/qml-qtquick-repeater.html
CC-MAIN-2021-04
refinedweb
144
50.23
Nov 23, 2012 03:56 AM|Nandip Makwana|LINK geetasksI am working in MVC3. It is not recognizing System.Web.Optimization & System.Web.Http namespace. This require to be installed... is it installed? Nov 23, 2012 04:18 AM|Nandip Makwana|LINK geetasksI am working in MVC3. Ohh.. I am sorry for incomplete answer earlier. Web optimization framework is introduced with MVC 4. Try with MVC 4 project it is included in default MVC 4 project template. Nov 23, 2012 04:48 AM|Nandip Makwana|LINK I am able to use and define Bundle with MVC 3. there might be some other issue with respect to System.Web.Http. System.Web.Optimization was introduced with MVC 4 but I am able to use it with MVC 3 as well. I followed below step. protected void Application_Start() { Bundle myBundle = new ScriptBundle("~/bundles/CommonJs").Include("~/Scripts/Common.js"); BundleTable.Bundles.Add(myBundle); } Now I am able to browse with ~/bundles/CommonJs with minified JavaScript response same as in MVC 4. 5 replies Last post Nov 23, 2012 04:48 AM by Nandip Makwana
http://forums.asp.net/t/1860759.aspx?Error+System+Web+Http+namespace+not+defined
CC-MAIN-2014-15
refinedweb
181
61.12
FAQs Search Recent Topics Flagged Topics Hot Topics Best Topics Register / Login Win a copy of JDBC Workbook this week in the JDBC and Relational Databases forum or A Day in Code in the A Day in Code forum! Monmohan Singh Ranch Hand 82 34 Threads 0 Cows since Aug 02, (82/100) Number Threads Started (34 (82/10) Number Threads Started (34/10) Number Likes Received (0/3) Number Likes Granted (0/3) Set bumper stickers in profile (0/1) Set signature in profile Set a watch on a thread Save thread as a bookmark Create a post with an image (0/1) Recent posts by Monmohan Singh Hi, All i have a doubt Deadlocks have to be managed by application programmer and can be prevented by techniques like resource ordering (acquiring and releasing locks in the same order) etc show more 14 years ago Threads and Synchronization Thread Join vs isAlive() and wait() oops ..sorry show more 14 years ago Threads and Synchronization Thread Join vs isAlive() and wait() Hi , Please look at this code --------------------- public class TestThreadJoin { //private MyThread t=new MyThread(); final Thread main=Thread.currentThread(); public static void main(String args[]) throws Exception{ Thread t =new Thread(){ public void run(){ System.out.println("Run for some time"); int i=0; while(i<10){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); System.out.println("Join"); while(t.isAlive()){ System.out.println("Checking if the thread is live"); t.wait(0); } System.out.println("Main thread Over>>>>"); } } It throws an IllegalMonitor exception j.t.wait(0); I can't understand the reason esp when replacing the same code with join(0) works show more 14 years ago Threads and Synchronization InterruptedException thread.join throws an interrupted exception? I can't think of a way to handle it. Now the reason a join is called is because i don't want the parent thread to start execution till the child has finished execution. so what do i do in case the join method throws exception show more 15 years ago Threads and Synchronization HTTPunit and java script I am writing a test which has following steps Get a page - this is successful Simulate click of an image on the page.- when i look at the source code of the page it basically means executing a javscript function javascript:listControl_VignConsoleForm.toolBar.actions[10].actionHandler("commonimagestoolbaraddgifSite_VignConsoleForm") How do I simulate this? appreciate any help show more 15 years ago Testing different jdk versions for build and run in case of deprecation, the compiler would warn.. so that is fine .. the assert keyword was introduced in 1.4? and in case of methods which are removed , if the code compiles on 1.3 and run on 1.4, shouldn't it give an error? show more 15 years ago Java in General different jdk versions for build and run i think i messed up.. here is what happens The code is build on 1.3.09 .. but run on 1.4.02 If performance of reflection is the reason, why should the code not be build on 1.4.02.. what can be other reasons? show more 15 years ago Java in General different jdk versions for build and run Many frameworks, I have seen document the fact that their source code should be build on say jdk1.4.2 , but once compiled and jared, it runs on jdk1.3.x I am not able to understand the logic .. can anyone help? show more 15 years ago Java in General Reverse Engineering well that's what I am faced with.. Rose and even TogetherJ give way too much detail.. show more 15 years ago OO, Patterns, UML and Refactoring Reverse Engineering Hi, I just joined a team of developers working on a product which has a huge code base. However the documentation of the design related to the components in pretty negligble. I need to create high level design documents for each of the subsystem/components in the product wanted to hear from the people here as to their experience and what are the ways to approach this problem show more 15 years ago OO, Patterns, UML and Refactoring server socket and accept call "But the receptionist needs to continue answering calls on the original port, so the caller is forwarded to a new port, leaving the original free to receive more calls." I don't think that this forwarding to new port happens.. because in this case when you look at the Socket created by accept call this should show a different value for the destination port which is not the case. Also, what if firewall doesn't allow opening new ports on the machine? show more 15 years ago Sockets and Internet Protocols server socket and accept call Sun's tutorial says that the accept call returns a socket with new port so that the server can still accept connections on the port to which it was bound ( eg port 80 for HTTP Server). I went thru some material and a brief glance at Stevens book and could not find this thing elaborated. an IP packet is represented by {protocol, source IP address, source port, destination IP address, destination port} and as long as one of this is different the packet can be differentiated . also the packets will be in queue on the port where the server is listening.. Also in case of new port there can be issues with firewall? show more 15 years ago Sockets and Internet Protocols configuration Looks like the question was hazy whatI meant was - Any decently sized J2EE application has need to read configuration. People do it in property files/XML data base etc,.but I wanted to know if there is a standard way and the benefits/drawbacks of these approaches show more 15 years ago EJB and other Jakarta /Java EE Technologies configuration Is there a standard way to manage configurations in a J2EE application. The configuration I am talking about is the properties which drive an application show more 15 years ago EJB and other Jakarta /Java EE Technologies MOM products vs JMS service given by Application Servers If the communication is java to java then Using MDB's etc should take care of scalability in terms of processing the messages , since the conatainer pools them. Do the MOM products have lot of othe features which makes them worth the money? show more 16 years ago EJB and other Jakarta /Java EE Technologies
https://www.coderanch.com/u/34234/Monmohan-Singh
CC-MAIN-2020-29
refinedweb
1,087
58.92
An easy way to create a matrix: > (2><3)[1..6] (2><3) [ 1.0, 2.0, 3.0 , 4.0, 5.0, 6.0 ] This is the format produced by the instances of Show (Matrix a), which can also be used for input. Creates a matrix from a vector by grouping the elements in rows with the desired number of columns. (GNU-Octave groups by columns. To do it you can define reshapeF r = trans . reshape r where r is the desired number of rows.) > reshape 4 (fromList [1..12]) (3><4) [ 1.0, 2.0, 3.0, 4.0 , 5.0, 6.0, 7.0, 8.0 , 9.0, 10.0, 11.0, 12.0 ] Creates a vector by concatenation of rows > flatten (ident 3) 9 |> [1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0] Creates a Matrix from a list of lists (considered as rows). > fromLists [[1,2],[3,4],[5,6]] (3><2) [ 1.0, 2.0 , 3.0, 4.0 , 5.0, 6.0 ] Creates a matrix from blocks given as a list of lists of matrices: > let a = diag $ fromList [5,7,2] > let b = reshape 4 $ constant (-1) 12 > fromBlocks [[a,b],[b,a]] (6><7) [ 5.0, 0.0, 0.0, -1.0, -1.0, -1.0, -1.0 , 0.0, 7.0, 0.0, -1.0, -1.0, -1.0, -1.0 , 0.0, 0.0, 2.0, -1.0, -1.0, -1.0, -1.0 , -1.0, -1.0, -1.0, -1.0, 5.0, 0.0, 0.0 , -1.0, -1.0, -1.0, -1.0, 0.0, 7.0, 0.0 , -1.0, -1.0, -1.0, -1.0, 0.0, 0.0, 2.0 ] creates matrix by repetition of a matrix a given number of rows and columns > repmat (ident 2) 2 3 :: Matrix Double (4><6) [ 1.0, 0.0, 1.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 , 1.0, 0.0, 1.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 ] creates a rectangular diagonal matrix > diagRect (constant 5 3) 3 4 (3><4) [ 5.0, 0.0, 0.0, 0.0 , 0.0, 5.0, 0.0, 0.0 , 0.0, 0.0, 5.0, 0.0 ] Creates a string from a matrix given a separator and a function to show each entry. Using this function the user can easily define any desired display function: import Text.Printf(printf) disp = putStrLn . format " " (printf "%.2f")
http://hackage.haskell.org/package/hmatrix-0.2.1.0/docs/Data-Packed-Matrix.html
CC-MAIN-2014-52
refinedweb
441
80.01
? Advertising. It makes me wonder if we should cache shortcuts so that after the first going through 5 layers, the second can jump directly to the tree entries. > > > > I'll try to have a look at your patches in more details soon. > > Shameful fixup (though it does not seem to impact the timing) And here's another one -- 8< -- diff --git a/list-objects.c b/list-objects.c index 39ad3e6..85dc14e 100644 --- a/list-objects.c +++ b/list-objects.c @@ -82,8 +82,10 @@ static void process_tree(struct rev_info *revs, die("bad tree object"); if (obj->flags & (UNINTERESTING | SEEN)) return; +#if 0 if (parse_tree(tree) < 0) die("bad tree object %s", sha1_to_hex(obj->sha1)); +#endif obj->flags |= SEEN; show(obj, path, name, cb_data); me.up = path; -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
https://www.mail-archive.com/git@vger.kernel.org/msg37599.html
CC-MAIN-2017-51
refinedweb
152
55.95
RAND(3P) POSIX Programmer's Manual RAND(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. rand, rand_r, srand — pseudo-random number generator #include <stdlib.h> int rand(void); int rand_r(unsigned *seed); void srand(unsigned seed); For rand() and srand(): The 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 rand() function shall compute a sequence of pseudo-random integers in the range [0,{RAND_MAX}] with a period of at least 232. The rand() function need not be thread-safe.‐2017 calls rand() or srand(). The rand() function shall return the next pseudo-random number in the sequence. The rand_r() function shall return a pseudo-random integer. The srand() function shall not return a value. No errors are defined. The following sections are informative.() and random() functions provide much more elaborate pseudo-random number generators. The limitations on the amount of state that can be carried between one function call and another mean the rand_r() function can never be implemented in a way which satisfies all of the requirements on a pseudo-random number generator. These functions: 1. A single per-process sequence of pseudo-random numbers that is shared by all threads that call rand() 2.(3p), initstate RAND(3P) Pages that refer to this page: stdlib.h(0p), drand48(3p), initstate(3p), srand(3p)
https://man7.org/linux/man-pages/man3/rand.3p.html
CC-MAIN-2021-25
refinedweb
279
59.3
Hello, could someone please help me? I'm pretty new at this. I tried to make a simple watchdog that resets my server when it freezes. I have made a windows program which sets one bit of the parallel port every minute for a second. The Attiny 2313 is programmed that is resets the server when this doesn't happen for more than ten minutes. I have connected the attiny 2313 to the following pins: +5V --- to +5V on the mainboard connector GND --- to one of the GNDs from the parallel port PB0 --- (as input) to the pin on the parallel port which is set by the windows program; and a 10k resistor which is connected to GND on the other end PB7 --- (as output) to the reset pin on the mainboard connector Behavior: when the windows program isn't running, the server resets after 11 minutes (as it should) When the windows program is running, the server runs for about 20 minutes and then resets (it shows that i use the correct pin of the parallel port, at least). Maybe someone has an idea what i did wrong? Here is the c-code: #include <avr/io.h> #include <util/delay.h> #include <avr/pgmspace.h> #include <inttypes.h> int main(void) { int timer; int value; int oldvalue; const int TIMERMAX = 6000; DDRB = 0xFE; // 11111110 - PB0 is input PORTB = 0; oldvalue = 0; timer = 0; while (1) { if (bit_is_set(PINB,0)) { value = 1; } else { value = 0; } if (oldvalue != value) { oldvalue = value; timer = 0; } timer++; _delay_ms(100); if (timer > TIMERMAX) { // no change on PB0 for more than 10 min. PORTB = 0x80; // set PB7 to 1 _delay_ms(100); PORTB = 0; timer = 0; } } // while } Thank You very much for Your help, Peter Sorry ... I don't use AVRs currently, but as nobody else replies .. here are my 2 cents: I'd simply use the good old LED-debugger to watch what the AVR thinks it sees on the parallel port. Did you check the LPT with a scope? I remember that there are different LPT-interface modes you can choose in the BIOS setup. Maybe there's a problem with the mode you use? Good luck! Hi, thank You for Your answer! I've tried the LEDs. A LED connected to the concerning pin of the LPT does go on and off, just as the windows program dictates (on for 1 second, off for a minute). To test the avr, I put a led to the output port (PB7) and decreased the inactivity interval to a few seconds. As long as I touched a wire with +5V to the input port (PB0) often enough, nothing happened, when I didn't the LED would be on for about 1/10 of a second, just like it should. Of course, I didn't try it for 20 minutes... Does it have to be exactly +5V on the input port? I think the LPT of my servers delivers something between 3V and 4V. Do I have a problem with the 10k resistor? Should I activate the internal pullup of the input instead? Thank You, Peter I'd make sure that the parallel port is running in SPP mode, not EPP or ECP. Whether the 10k resistor is a problem or not can be checked with LED debugger as well. Use another port pin and set it similar to your value variable. Then you see what the AVR sees on the input-pin. I don't see a problem in the program. Thank You! I will try changing the lpt settings. Great idea with the value variable! Maybe that will help me! Thank You, Peter
https://embdev.net/topic/169313
CC-MAIN-2019-35
refinedweb
607
81.43
#include "avcodec.h" #include "dsputil.h" #include "bytestream.h" #include "libavutil/colorspace.h" #include "libavutil/imgutils.h" Go to the source code of this file. Definition in file pgssubdec.c. Definition at line 33 of file pgssubdec.c. Definition at line 35 of file pgssubdec.c. Definition at line 71 of file pgssubdec.c. Definition at line 395 of file pgssubdec.c. Decode the RLE data. The subtitle is stored as an Run Length Encoded image. Definition at line 91 of file pgssubdec.c. Parse the display segment packet. The display segment controls the updating of the display. segment, which is currently ignored as it clears the subtitle too early. Definition at line 346 of file pgssubdec.c. Definition at line 64 of file pgssubdec.c. Parse the palette segment packet. The palette segment contains details of the palette, a maximum of 256 colors can be defined. Definition at line 230 of file pgssubdec.c. Initial value: { .name = "pgssub", .type = AVMEDIA_TYPE_SUBTITLE, .id = CODEC_ID_HDMV_PGS_SUBTITLE, .priv_data_size = sizeof(PGSSubContext), .init = init_decoder, .close = close_decoder, .decode = decode, .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"), } Definition at line 470 of file pgssubdec.c.
http://ffmpeg.org/doxygen/0.9/pgssubdec_8c.html
CC-MAIN-2014-35
refinedweb
187
55.3
👋 You can see this in action on Ember Twiddle, or look at the code on Github Pagination is a very basic building block in many web applications. It’s also a great illustration of how you can leverage Ember’s components to make reusable, flexible and DRY pieces of functionality. To demonstrate, in this post we’ll make a simple {{list-pagination}} component that can paginate a simple <ul> of the teams that played in this years Euro 2016 tournament: Setup the un-paginated list of teams To get started, we’ll create the list of teams. To make life easy, we’ll hard-code them in our application route: import Ember from 'ember'; let teams = [{ id: 1, name: "Albania" }, { id: 2, name: "Austria" }, // ... you can get the rest here: { id: 24, name: "Wales" } ]; export default Ember.Route.extend({ model() { return teams; } }); and display them in our application template: <h1>Euro 2016 teams:</h1> <ul> {{#each model as |team|}} <li>{{team.name}}</li> {{/each}} </ul> so that we now have a basic un-paginated <ul> of all the teams: Create a pagination component Now we’ll create a component that will paginate the above list and provide controls to move between the pages (as seen in the GIF above). > ember g component list-pagination To get an idea of how this component will work, let’s first show how it will eventually work in our application template: <h1>Euro 2016 teams:</h1> {{#list-pagination paginateBy=5 items=model as |teams|}} <ul> {{#each teams as |team|}} <li>{{team.name}}</li> {{/each}} </ul> {{/list-pagination}} We are using the component in its block form to entirely wrap the existing list.. This allows us to reuse the pagination component with any sort of list. The styling and implementation of the internal list can be left to the user to declare in the component’s block template (the content between {{#list-pagination ...}} and {{/list-pagination}}). The pagination component and template Lets’ first looks at list-pagination.js: import Ember from 'ember'; export default Ember.Component.extend({ tagName: "section", // The page we are currently on page: 1, // The number of items to show per page paginateBy: 10, // Returns the list of items for the current page only paginatedItems: Ember.computed('items', 'page', function(){ var i = (parseInt(this.get('page')) - 1) * parseInt(this.get('paginateBy')); var j = i + parseInt(this.get('paginateBy')); return this.get('items').slice(i, j); }), // The total number of pages that our items span numberOfPages: Ember.computed('page', function(){ var n = this.get('items.length'); var c = parseInt(this.get('paginateBy')); var r = Math.floor(n/c); if(n % c > 0) { r += 1; } return r; }), // An array containing the number of each page: [1, 2, 3, 4, 5, ...] pageNumbers: Ember.computed('numberOfPages', function(){ var n = Array(this.get('numberOfPages')); for(var i = 0;i < n.length;i++) { n[i] = i + 1; } return n; }), // Whether or not to show the "next" button showNext: Ember.computed('page', function(){ return (this.get('page') < this.get('numberOfPages')); }), // Whether or not to show the "previous" button showPrevious: Ember.computed('page', function(){ return (this.get('page') > 1); }), // The text to display on the "next" button nextText: 'Next page', // The text to display on the "previous" button previousText: 'Previous page', actions: { // Show the next page of items nextClicked() { if(this.get('page') + 1 <= this.get('numberOfPages')) { this.set('page', this.get('page') + 1); } }, // Show the previous page of items previousClicked() { if(this.get('page') > 0) { this.set('page', this.get('page') - 1); } }, // Go to the clicked page of items pageClicked(pageNumber){ this.set('page', pageNumber); } } }); The code is commented, but the important part to note is the computed property paginatedItems. Instead of returning all of the items passed into our component, it figures out what page we are on and returns only those items that are within the current page. Now let’s see the component’s template: {{yield paginatedItems}} <ul> {{#if showPrevious}} <li><button {{action "previousClicked"}}>{{previousText}}</button></li> {{else}} <li style="text-decoration: line-through;">{{previousText}}</li> {{/if}} {{#each pageNumbers as |pageNumber|}} <li><button {{action "pageClicked" pageNumber}}>Page {{pageNumber}}</button></li> {{/each}} {{#if showNext}} <li><button {{action "nextClicked"}}>{{nextText}}</button></li> {{else}} <li style="text-decoration: line-through;">{{nextText}}</li> {{/if}} </ul> The Trick The trick here is our {{yield ...}} helper. Firstly, remember that the yield helper is replaced with the component’s block template (again, the content between {{#list-pagination ...}} and {{/list-pagination}} in our application template). In other words, we are rendering our <ul> of teams in place of {{yield ...}}. Now note that we have passed paginatedItems as a parameter to the {{yield}} helper. These are called block parameters. Doing this makes the parameter available to us back in our component’s block template if we use the as |myVariable| syntax: {{#list-pagination items=model as |teams|}}. In other words, the teams variable in our block template is actually equal to paginatedItems. This means that when we list the teams with {{#each teams as |team|}}, only those teams from the current page are being displayed. Below the yielded template we place the controls for the rest of the component. This is the easy part. We simply show/hide the appropriate buttons using computed properties and provide actions to change the page when a button is clicked. These actions will cause the paginatedItems to change, in turn changing the listed teams. Hopefully it should be clear how this works but to see it in action you can check out this Ember Twiddle as well as browse the entire code on Github Gist
https://timmyomahony.com/blog/simple-pagination-component-ember
CC-MAIN-2021-17
refinedweb
926
55.34
sc_MsgStateBufRecv - Man Page The MsgStateBufRecv is an abstract base class that buffers objects sent through a MessageGrp. Synopsis #include <mstate.h> Inherits sc::StateIn. Inherited by sc::BcastStateInBin, and sc::MsgStateRecv. Public Member Functions MsgStateBufRecv (const Ref< MessageGrp > &) MsgStateBufRecv can be initialized with a MessageGrp. MsgStateBufRecv () Use the default MessageGrp. void set_buffer_size (int) The buffer size of statein and stateout objects that communicate with each other must match. Protected Member Functions int get_array_void (void *, int) virtual void next_buffer ()=0 Specializations must implement next_buffer(). Protected Attributes Ref< MessageGrp > grp int nbuf int ibuf int bufsize char * buffer char * send_buffer int nheader int * nbuf_buffer Detailed Description The MsgStateBufRecv is an abstract base class that buffers objects sent through a MessageGrp. Author Generated automatically by Doxygen for MPQC from the source code.
https://www.mankier.com/3/sc_MsgStateBufRecv
CC-MAIN-2022-21
refinedweb
129
50.33
24 February 2012 07:10 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> MEK prices were assessed at $1,350-1,380/tonne CFR (cost & freight) SE (southeast) Sellers firmed their offers supported by high naphtha costs and the expected seasonal improvement in March or April; hence, buyers had to give higher bids to secure cargoes. “Crude and naphtha prices are too high, so we could not lower prices,” a northeast Sporadic offers were said to be at $1,380-1,400/tonne CFR Korea against buying ideas were at around $1,350/tonne CFR Korea. Some bulk deals were said to be done at $1,350-1,380/tonne CFR Korea this week, a producer said. In southeast Asia market, prices also rose by $20-30/tonne to $1,350-1,400/tonne CFR SE Asia to reflect deals heard in the market, according to ICIS. However, consumer demand has yet to show significant improvement
http://www.icis.com/Articles/2012/02/24/9535476/asia-mek-prices-rise-by-30tonne-amid-higher-feedstock.html
CC-MAIN-2014-52
refinedweb
155
66.07
Today can only be summarized by this: While I’m having my fun in the dark side of development doing XAML I hit something really whacky today, using the WebView control. Here be dragons The WebView control seems to be a little bit special, and not really special in a good way and it seems others have also found it limiting. But I hit an interesting problem with the WebView control rendering, in particular rendering it in a settings panel. Long story short it didn’t display. Here’s the XAML: <UserControl> <Grid> <WebView Source="" /> </Grid> </UserControl> (I omitted the namespace guff for you) Sure I might not be a XAML wiz but I’m pretty sure that that should work, and according to the limited knowledge of how layout works this would be fine right? My WebView doesn’t have sizes specified so it should fill out to the whole area. Well you’re wrong. It would seem that when you use a WebView control that doesn’t have a size set on it, nor on its parents it just goes 0x0. This coupled with the WebView’s inability to animate with the rest of the controls in its container makes leaves me just bemused. Conclusion Avoid the WebView control. Avoid it at all costs.
https://www.aaron-powell.com/posts/2012-08-28-webview-oh-you/
CC-MAIN-2019-18
refinedweb
216
69.21
There was an light-hearted discussion of this last year. It seems there might be a more serious purpose - debunking the kind of myths that undermine new programming languages. "The aim of this book has been to demonstrate that functional languages, in particular SML, can be used to build the kind of real-world projects that you might ordinarily only think of using C or C++ for... Unfortunately programmers are prone to myths about programming languages and seldom revisit them... Here are some common ones Lisp is slow. Optimising compilers have been available for years. Ada is huge and bloated. What, C++ isn't? C must be efficient because you can program down to the bare metal. Nope, its 1970s-vintage machine model no longer fits well with modern computers." Unix System Programming with Standard ML Is The Truth out there? I think the discussion you mentioned I said that if someone created a nice page (with links to LtU message, for instance), I'd be glad to host it here, and link to it from the navigation bar on the left. (I'm quite open to some of the Myths turning out to be true) Predictably, I'd suggest the "C/C++ is so much more efficient" myth. Just because I hear it over and over... maybe it's true! Oh, and another one: "Java was inovative for introducing the concept of a VM." For example, I'd love to see this optimization technique (or something similar) implemented in any safe language (ocaml, perl, java, smalltalk, etc). For the work I do, this every-byte-counts stuff actually adds up -- we routinely store hundreds of millions of objects in memory, and going 64-bit is not yet an option. It's for this reason that when I daydream about language features that I'd like to have, I usually end up thinking about efficient, custom data structures generated from a high-level specification. From a recent LtU discussion: "Generics are new" Maybe we should hangout in slashdot for a while to pick up some mythic themes... I can think of these. Statements that can be proven wrong, using the theoretical framework of the field. These are the easy ones. Next we have things that require empirical evidence. "C is always faster than Scheme" can be deubnked, simply by showing *one* counter example. This sort of thing is often the result of over generalizing from personal experience. Next we have vague terms, that result in meaningless statements (e.g., "OOP is the best methodology". Niether 'OOP' nor 'methodology' have an exact meaning, but 'best' is really meaningless in this context). The last type I want to mentiopn shouldn't really be considered a myth. I am thinking about experssions of opinion. We shouldn't let opinions be disguised as facts, but controversial and even wrong opinions are not myths. They are sometimes the result of mass dellusion, but that's beside the point. In this category I'd list things like "ten years from now everyone will be programming in Lisp". Statements in this category often also use vague terms: "imperative languages are easier for beginners". Opinion & Meaningless Generalization (maybe some of them can be restated): Myths that are actually true. ;-) Are all those items really in the correct category? What repeated, unsubstantiated claims are missing? I've looked at your "Efficient Representation of Shared Data" page, and have some remarks. Here is the way I understand it. There is an object S : Shared which is shared between N objects O1, O2, .. ON : Unique. You want a type T such that there exist functions: mkT : (Shared, Unique) -> T getShared : T -> Shared getUnique : T -> Unique that make T into a product of Shared and Unique. Technique #1: Basically T = Shared * Unique. Technique #2: This is really a non-technique, since it doesn't satisfy your requirements. You basically take T = Unique and require that a computation accessing the O's go through a type X = Shared * UnboxedArray T at some point in its history. Obviously there is no function get_shared definable on T. But since all access to the O's must initially go through X, one can arrange that S is always in scope (there is always a free variable denoting S). This suggests that, if we can force S to always be in scope for every computation on the O's, we can implement the wanted functions above. So define a Shared-computation (M a) to be value a with a value of type Shared in scope: type M a = M (Shared -> a) This forms a reader monad: return :: a -> M a return x = M (\s -> x) (>>=) :: M a -> (a -> M b) -> M b (M m) >>= k = k m fetch :: M Shared fetch = M (\s -> s) runM :: Shared -> M a -> a runM s (M m) = m s (>>=) :: M a -> (a -> M b) -> M b (M m) >>= k = k m fetch :: M Shared fetch = M (\s -> s) runM :: Shared -> M a -> a runM s (M m) = m s Now suppose we have a function which processes T's (producing Int's, say) and requires access shared data. It should have type: f :: Unique -> M Int This type is isomorphic to: Unique -> (Shared -> Int) which is iso to: Unique * Shared -> Int which, taking T = Unique * Shared, is iso to: T -> Int So we can implement something like the wanted functions: mkT' :: Unique -> M T mkT' o = do { s <- fetch; return (o,s) } getShared' :: Unique -> M Shared getShared' _ = fetch getUnique' :: Unique -> M Unique getUnique' = return getShared' :: Unique -> M Shared getShared' _ = fetch getUnique' :: Unique -> M Unique getUnique' = return I think this satisfies your requirements, though. Every Unique object is stored by itself, as is the object S, and no pointer arithmetic required. Instead of changing the data representation, we changed the representation of computations on the data. The monad M ensures that every computation on a Unique gets passed the value S. I think in OO circles this is known as the Flyweight pattern. But it seems you missed one important point: there can be more than one shared object, and each unshared object should be associated with a particular shared object. Judging from runM, it looks like you're assuming that there is only one shared object in the entire system. In that case, sure, you can just structure computations so that the shared object is supplied at some point in the future. But that's basically begging the question. By the way, thanks for the exhibition of monadic transforms. They're still a bit new to me, so seeing them in a familiar context was useful. I don't think there is a problem there. You have one object s associated with a set of objects. When you write: runM s m you're effectively creating that association: it associates s with all the objects mentioned in the computation m. If you have more than one shared object `in the system', then you can use a reader monad transformer and standard techniques for combining monads. It is true in that case that there is no information about which objects are associated with which shared object but that should not pose a problem since you can almost certainly assume that if the set O is associated with s and the set O' with s', then O and O' are disjoint. (Why can you assume this? Because in your `efficient representation' the objects are stored by value in a contiguous array, so if they are part of two shared structures, then they have to either all be in common---O=O'---or not, and if they are all in common, then you can just merged their shared bits...) Assuming I haven't exhausted your patience already, I'd be interested to see how your technique solves a problem like this (trying to keep it simple, yet still illustrate my point): You have a list of unique objects, each of which has a shared object associated with it. Suppose, for simplicity, that the shared object is simply an integer. I want the sum of all the integers associated with the unique objects, disregarding the sharing. In haskell: sum uniques = foldl (+) 0 (map getShared uniques) Feel free to lift the computation into a monad and do whatever other transformations you'd like. Right! I'll try to get in touch next week (you can also email me), and we should get together some time. If you have two shared objects, then the combined monad looks like: Shared -> Shared -> a or equivalently (Shared, Shared) -> a So there is really no overhead on the uniques. However, it is not really meaningful, I think, to talk about data representation overhead here, since there is no object stored in memory corresponding to a Shared plus all its associated uniques. Rather, I think you need to start talking about the space complexity of a computation in the monad. You have a list of unique objects, each of which has a shared object associated with it. Suppose, for simplicity, that the shared object is simply an integer. I want the sum of all the integers associated with the unique objects, disregarding the sharing. I'm afraid, if I understand you correctly, that this is not so straightforward. Since you have one `Shared' appearing in the type of the monad for each shared object, such a function needs to be polymorphic recursive and operate at a range of types: () Shared -> a Shared -> Shared -> a ... So at the least you need to do induction on types, which is possible, but not something I want to get into here. Also, I think you were right earlier and some more information needs to be added to this type in order to tell which unique is associated with which Shared; undoubtedly that extra information would exceed your minimum overhead. Actually, a more serious problem occurred to me yesterday after I wrote my message. I said that if you have two Shared objects then it is almost certain that their associated uniques will be disjoint. The reason I wrote almost certain is that your efficient C representation stores the uniques by value in an array, and so if some were associated with two distinct Shared objects, then the intersection has to correspond to a suffix of the array for one Shared and a prefix of the array for the other Shared, which seemed pretty unlikely. But I thought of an example where exactly that situation occurs, namely when the uniques are characters in a text editor buffer and the Shared object gives some styling or text properties which are associated with a contiguous range of characters. (This is, I think, the motivating example for the Flyweight pattern in the GOF book.) Anyway, I think you could apply the reader monad approach in this case but it would certainly take more work, and I'm not sure about the space complexity off the top of my head. First, the solution on your page has the space complexity of N + sizeof (int) + sizeof (pointer) bytes per shared object, provided there are at most 256 unique objects per shared objects and objects cannot be allocated or freed individually (without an expensive reorganization). It seems the gist of the problem is one-to-many correspondence. The solution follows from the relational database approach in a straightforward manner. We demonstrate two solutions here: 1. Consider a set of shared objects one relations, and the set of unique objects another relation. We also need a relation between shared and unique objects. Suppose we have at most 256 shared objects. We can allocate them in a vector. The index of a shared object in the vector would be that shared object's primary key. Unique objects can be allocated as you please. The handle (reference) to that object is its primary key. To relate a unique object and its shared part, we need a foreign key: shared object's index. By assumption, there can be no more than 256 shared objects -- so one byte per foreign key should suffice. struct SharedData { /* shared data */ }; SharedData shared_data_table [] = { ....}; struct MyObject { /* non-shared data */ ... uint8 shared_data_key; }; SharedData *get_shared_data(MyObject *object) { return & shared_data_table[object->shared_data_key]; } SharedData shared_data_table [] = { ....}; struct MyObject { /* non-shared data */ ... uint8 shared_data_key; }; SharedData *get_shared_data(MyObject *object) { return & shared_data_table[object->shared_data_key]; } 2. What if we want to find all unique objects that share a given shared object? We should turn to a more general solution. We should ask ourselves, what should be a primary key of a unique object? It could be its handle -- or it could be a pair (shared_obj_key, unique_obj_key). Thus, a unique object is identified by a shared object and some additional key. We can assume that there can be no more than 65536 shared objects and no more than 65536 unique objects per one shared object. struct SharedData { /* shared data */ int UniqueDataCount; UniqueData * unique_obs; // vector of unique objs };]); } Overhead (per shared object): sizeof(int) + sizeof(ptr). The overhead does not depend on the number of unique objects. No address arithmetics is required. We only need array access. Furthermore, because UniqueObjRef does not depend on actual memory addresses, UniqueObjRef can refer to objects on disk as well objects in memory, can be persistent, and can be reliably stored in persistent and distributed data structures. It must be noted that a virtual address is likewise a complex structure of various indices (into a segment and page tables). Unfortunately, the first version won't work in practice. Every compiler I know of will pad that last byte up to the nearest word size, which on current machines is four bytes. If it didn't, then you would pay a heavy penalty for using any of the unique objects, since they would not be word-aligned and would therefore need to be copied out bytewise before being used. It also restricts you to 256 shared objects total, with no real way to increase that number. However, the second version is good enough to prove me wrong. This version has two drawbacks and one advantage. The first drawback is that you have to know up-front how many shared objects you're going to have (although this can be offset by using a table that grows on demand, at a trivial cost). The second drawback is that it restricts the total number of shared objects, depending on how many bits you allocate for the shared and unique offsets, and this allocation is static and must be tailored to the problem at hand. On the other hand, it has the advantage that on a 64-bit cpu it will remain only 32 bits, while a pointer would double in size. In nearly every situation, your second version would be sufficient to solve the problem. However, in the situation I was working in when I developed my technique, I had about 40 million shared objects (26 bits), and if I limited them to only 32 unique objects each (the remaining 6 bits), they would have doubled to 80 million, and so on and so on. So it wouldn't have worked for me, but I was in a very specific and odd situation. I'll link to this thread from my page. struct MyObject { /* non-shared data */ ... uint8 shared_data_key; }; struct MyObject { uint8 shared_data_key; char my_str[0]; }; Your comment highlights the often neglected fact that allocating memory for strings via malloc() is quite wasteful: the overhead is 4 bytes (50% of the 1-7 padding bytes) plus (on many systems) 8 bytes for memory block header. For short strings, the overhead can be quite large. Alas, in C all non-static strings that are to survive the return from the creating function must be allocated on heap. Memory allocation is really a very difficult subject and should therefore be left to specialists such as Hans-J. Boehm.
http://lambda-the-ultimate.org/classic/message6804.html
crawl-002
refinedweb
2,647
60.75
When printf (stdio.h) is used, "Start both threads\n" and "Enter a number\n" mixed together (something like "StEanterrt b a oth thnureaber\nads\n"), but this does not happen in std::cout (iostream). I suspect this has something to do with std::thread, but I am still new with multi-threading programming. I really don't want to use iostream because it makes the program super large! I am using mingw32 g++ 4.9.2, compile with g++ -o foreback foreback.cpp -O2 -std=c++11 //#define IOS #ifdef IOS #include <iostream> #endif #include <stdio.h> #include <thread> #include <atomic> #include <windows.h> // for Sleep() std::atomic<int> atom(1); void foreground() { int c = 1; while (c) { #ifdef IOS std::cout << "Enter a number: "; std::cin >> c; #else printf("Enter a number: "); scanf("%d", &c); #endif atom.store(c, std::memory_order_relaxed); } } void background() { FILE *out = fopen("foreback.txt", "w"); int c = 1; while (c) { fprintf(out, "%d", c); c = atom.load(std::memory_order_relaxed); Sleep(500); } fclose(out); } int main() { std::thread f(foreground), b(background); #ifdef IOS std::cout << "Start both threads.\n"; #else printf("Start both threads.\n"); #endif f.join(); b.join(); #ifdef IOS std::cout << "End of both threads.\n"; #else printf("End of both threads.\n"); #endif return 0; } std::cout provides no guarantees on interleaving either; it's not mentioned in C++03, and C++11's FDIS says the following in §27.4.1 [iostream.objects.overview]: Concurrent access to a synchronized (§27.5.3.4) standard iostream object’s formatted and unformatted input (§27.7.2.1) and output (§27.7.3.1) functions or a standard C stream by multiple threads shall not result in a data race (§1.10). [ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ] That note at the end basically means " std::cout is allowed to interleave characters too". It's possible it isn't doing so due to the compiler/runtime library specific implementation in general, or due to the attempts to synchronize itself with stdio.h (turning off sync_with_stdio might cause it to begin interleaving again). But it's not a language guarantee; you're just lucking out. If you want output to not interleave, you need to either perform all I/O from a single thread (have your workers take arguments and compute values, and the main thread is responsible for performing the I/O to output the computed values), or explicitly lock around all I/O functions that are used from different threads that target the same stream/ FILE*. You could easily use stdio.h, you'd just need to have a std::mutex that you lock (e.g. with std::lock_guard) around your uses of stdio.h functions; as long as it's done consistently, you're guaranteed no interleaving.
https://codedump.io/share/TY2Y8RqP1FK0/1/printf-calls-messed-up-with-stdthread-but-stdcout-are-fine
CC-MAIN-2018-09
refinedweb
485
66.84
Descripción Ultimate Blogroll is a plugin which enables your visitors to submit a linktrade. Your visitors can add their own website and you can keep track of the in- and outlinks. * Let your visitors add a linktrade * Give an overview of the linktrades including the stats * Order by different parameters * Easily approve or discard a new linktrade * Check for a reciprocal link * Prevent spam with Recaptcha * Import/export links into/from WordPress * Handy Wizard/Installation process to get you started * ... Now available in: English, Dutch, Spanish, Hungarian, Russian, Norwegian Credits: Spanish translation: Dennis Vera () Hungarian translation: Nora Erdelyi () Russian translation: Nickolay Avdeev Norwegian translation: Rune Kristoffersen ( ) Instalación There is a wizard available which will guide you thought the installation process. - Can I import my wordpress linkpartners Sure, you can import your linkpartners. If you don’t like Ultimate Blogroll you can even export them back to wordpress. - Are the statics in realtime? No, they are calculated once every hour. This plugin is designed for large sites with a huge amount of visitors. Reseñas Colaboradores y desarrolladores «Ultimate Blogroll» es un software de código abierto. Las siguientes personas han colaborado con este plugin.Colaboradores Traduce «Ultimate Blog.5.2 - Fixed a name collision (admin_menu) - Added ‘Errors:’ to the po localization file 2.5.1 - Turned off error reporting 2.5 - Fixed bugs, credits to: syndrael for reporting 2.4.5 - Fixed blank page 2.4.4 - Improved importing old settings to determine which page is the Ultimate Blogroll page 2.4.3 - Removed namespaces, since this is php 5.3 and apparently a lot of people don’t update their php and are using an unsecured server - Fixed a bug for editing linkpartners inside admin panel 2.4.2 - Fixed addlink in widget - Added namespaces to prevent name conflicts 2.4.1.1 - Restyled button in wizard 2.4 - Fixed Bugs: addlink, reCAPTCHA, Missing argument 2 for wpdb::prepare() - Fixed styling issues: buttons look fine in the new WordPress style 2.3 - Fixed «Fatal error: Call to undefined method Page::sendMail()» problem - Added the Norwegian language 2.2.4 - Fixed stylesheet problem 2.2 - Fixed problems since 2.1 caused due to SVN not playing nice with GIT 2.1 - Added Italian and Bahasa Indonesia - Fixed The function «Target: _blank» does not open a new window. - Fixed Hiding website logo - Fixed Sorting - Moved assets into gui/assets 2.0 - has been replaced by another system - code has been redesigned and refactored - gui rebuild - bugs fixed 1.8.2 - Added curl support, thanks to Rob of abcblogcast - Fixed bug checking for external links, there is no need in receiving a warning (ports not open) if you don’t need the feature - Curl support should fix the «Could not check for reciprocal website. Check if ports are open.» warning 1.8.1 - Updated magic methods to be compatible with php 5.3 - Fixed some minor bugs 1.8 - Added russia - Performance boost - Added options for website image(logo) - Fixed some minor bugs 1.7.6 - Added the hungarian language - Fixed recaptcha bug - Fixed error in admin panel, when you add a linkpartner manually - Fixed some minor bugs 1.7.5 - Fixed some display issues (<?= <?php echo) - Added the Spanish language - Fixed linktrades did not save although successful message was shown - Fixed some minor bugs 1.7.2 - Fixed No such file gui/recaptchalib.php 1.7.1 - Fixed widget title - Enabled choice to require reciprocal link 1.7 - Fixed some conflicts with other plugins - Relative paths changed into absolute path - New way of saving settings 1.6.5 - Fixed Call to a member function UpdatePermalink() issue 1.6.4 - Fixed Recaptcha library issue 1.6.3 - Added the possibility to add images - Fixed a bug in the wordpress import function 1.6.2 - Fixed some annoying minor bugs 1.6.1 - Minor bugfix in url (email) 1.6 - Import/export linktrades from/into WordPress 1.5 - Multi-language - Added a wizard/installation process - Fixed some minor bugs - Changed internal structure 1.0 - First version build, I am currently awaiting feedback
https://es.wordpress.org/plugins/ultimate-blogroll/
CC-MAIN-2022-33
refinedweb
677
58.69
Abstract:. Welcome to the 134th edition of The Java(tm) Specialists' Newsletter. This week, I have the honour of welcoming Kirk Pepperdine as a contributing author to our newsletter. It is the first newsletter that Kirk is writing for us, and hopefully not the last. Kirk is a well known authority on the topic of Java Performance. I have listened to his talks at TSSJS and JavaZone, and have even shared the stage with Kirk in Johannesburg earlier this year. Kirk Pepperdine is presenting his incredible Java Performance Tuning course in Greece in the week of the 23rd. On one of the evenings, I will join you for a wonderful meal at "Irene's", a little restaurant in the village of Xorafakia. Run by Irene herself, this tiny taverna cooks typical Cretan dishes and is frequented by the locals (always a good sign) and of course tourists. Come join us for an evening of good food and good company :) And with that, I hand you over to Kirk Pepperdine. javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge. Just recently I had a conversation with a colleague who had determined that String was at the root of his performance woes. Normally I am sceptical when someone tells me that String utilization is the problem. It isn't that String utilization couldn't be a problem; it is just that String is used so ubiquitously that fixing it not only time consuming, there is no guarantee that "fixing" it will improve performance. However the application in question was performing a lot of String concatenations. The resulting String was then used to perform a lookup in a HashMap. What should have been a quick performance win was going to take a lot of effort because the original developer failed to adhere to the Don't Repeat Yourself (DRY) design principle. One of the goals in this exercise was to dispel the myth that you need to sacrifice good design or write overly complex code in order to achieve good performance. That there is wide spread belief in this myth is unfortunate because I have found that violating design principles or writing overly complex code is often the stumbling block to achieving good performance. In this case, not following DRY left the String concatenation operation and subsequent HashMap lookup scattered all throughout the application. This has two knock-on effects. The first being that any operation that is a bottleneck will be difficult to find as the scattering dilutes or hides the effect. The second is that if you are lucky enough to find that an operation is a bottleneck, you will be obliged to trawl through the code looking for every instance of that operation. Lastly what happens is that teams blindly change String operations without any evidence to say that a change would make a difference. Fortunately my colleague had identified a single use case and that allowed me to write a focused benchmark. A benchmark in which we could explore the benefits of one strategy over another. In addition, I wanted to demonstrate how DRY would help and without hurting performance. Thus I structured the benchmark to follow that design principle. public class Person { private int id; private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public int getId() { return id; } public void setId(int id) { this.id = id; } } import java.util.HashMap; public class AllPersons { private HashMap personsById = new HashMap(); private HashMap personsByName = new HashMap(); public Person addPerson(String firstName, String lastName) { Person person = new Person(firstName, lastName); personsById.put(new Integer(person.getId()), person); personsByName.put(firstName + lastName, person); return person; } public Person findPersonsById(int id) { return (Person) personsById.get(new Integer(id)); } public Person findPersonsByName(String firstName, String lastName) { return (Person) personsByName.get(firstName + lastName); } } As you can see, the AllPersons class provides a nice neat home for all of the needed CRUD operations. Note that the class contains two HashMaps. The second is not necessary for this benchmark but demonstrates one of the benefits of following DRY. As the queries build up you may find that you need alternative indexing schemes. Just as adding an extra index in a database, the personsByIndex Map provides that functionality. Other benefits will become apparent when we move to the second part of the benchmark. The next step was to setup a benchmark harness. The code for this is just below. import java.util.*; public class TestHarness implements Runnable { private static String[] FIRST_NAMES = {"Ted", "Fred", "Andy", "Gromit", "Wallace"}; private static String[] LAST_NAMES = {"Mouse", "Duck", "Pascal", "Kabutz", "Monster", "Dread", "Crocket"}; private StringArray firstNames = new StringArray(FIRST_NAMES); private StringArray lastNames = new StringArray(LAST_NAMES); private AllPersons allPersons; private int numberOfIterations; public TestHarness(int numberOfIterations) { this.numberOfIterations = numberOfIterations; } public void init() { allPersons = new AllPersons(); for (int i = 0; i < 250000; i++) { allPersons.addPerson( firstNames.nextAsDeepCopy(), lastNames.nextAsDeepCopy()); } } public void run() { for (int i = 0; i < numberOfIterations; i++) { allPersons.findPersonsByName( firstNames.next(), lastNames.next()); } } public static void main(String[] args) throws InterruptedException { ArrayList processes = new ArrayList(); ArrayList threads = new ArrayList(); long setup = System.currentTimeMillis(); for (int i = 0; i < Integer.parseInt(args[0]); i++) { TestHarness harness = new TestHarness( Integer.parseInt(args[1])); harness.init(); processes.add(harness); } setup = System.currentTimeMillis() - setup; System.gc(); Thread.sleep(1000); System.gc(); Thread.sleep(1000); long processing = System.currentTimeMillis(); for (Iterator it = processes.iterator(); it.hasNext();) { TestHarness harness = (TestHarness) it.next(); Thread thread = new Thread(harness); thread.start(); threads.add(thread); } System.out.println("waiting"); for (Iterator it = threads.iterator(); it.hasNext();) { Thread thread = (Thread) it.next(); thread.join(); } processing = System.currentTimeMillis() - processing; System.out.println("Setup time : " + setup); System.out.println("Processing time : " + processing); } public static class StringArray { private int nextString = 0; private String[] array; public StringArray(String[] strings) { this.array = strings.clone(); } public String next() { String result = array[nextString++]; nextString %= array.length; return result; } public String nextAsDeepCopy() { return new String(next()); } } } The harness is pretty straight forward. After doing some initialization I clear the deck to prepare for the run. The clearing consists of a pair of calls to System.gc() followed by a sleep. The reason why gc is called twice is that the second call takes care of collecting any residual objects that may have required finalization. The call to sleep removes any interference from the concurrent portion of the call to gc. With the cleanup complete, we have more assurance that we are only measuring what we believe we are measuring. What I wanted a measure of was the effect of memory management on the time to complete a fixed unit of work. The results of the runs are listed in table below. There i some variation in the numbers but what is important to note is that the magnitude remains stable. During the run I made the observation that CPU utilization bounced about in the range of 77 to 89%. My guesstimate was that overall CPU utilization averaged 83%. This was a bit surprising given that the benchmark runs un-throttled but more on this later on. The next step was to implement the alternative solution. Since the key in the lookup was a composite of two String objects, what I proposed was to introduce a new class. In the source for CompositeKey we can see that the concatenation has been replaced two instance variables. public class CompositeKey { private String key1, key2; public CompositeKey(String key1, String key2) { this.key1 = key1; this.key2 = key2; } public final boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CompositeKey)) return false; CompositeKey that = (CompositeKey) o; if (key1 != null ? !key1.equals(that.key1) : that.key1 != null) return false; if (key2 != null ? !key2.equals(that.key2) : that.key2 != null) return false; return true; } public final int hashCode() { int result; result = (key1 != null ? key1.hashCode() : 0); result = 31 * result + (key2 != null ? key2.hashCode() : 0); return result; } public String getKey1() { return key1; } public String getKey2() { return key2; } } Since we followed DRY, altering the benchmark to use the new class is simple. All of our changes have been isolated to our domain specific collection class. Note that changes to the harness are missing from the code (listed below) that has been changed. This implies that we are presenting the benchmark the same unit of work offered under the same conditions. This is an important property that allows us to directly compare results. public Person addPerson(String firstName, String lastName) { Person person = new Person(firstName, lastName); personsById.put(new Integer(person.getId()), person); personsByName.put(new CompositeKey(firstName, lastName), person); return person; } public Person findPersonsByName(String firstName, String lastName) { return (Person)personsByName.get(new CompositeKey(firstName, lastName)); } With these changes in place I was quickly able to re-run the benchmark. The results of these runs are listed in the next table. As we can see there is a dramatic improvement in performance of the benchmark. As for my previous observation regarding CPU utilization, I guesstimated that the new improved version was averaging of about 95%. From this evidence we can start to draw conclusions. The first conclusion was that abandoning String in favour of the (more suitable) CompositeKey class provided us with a stunning improvement in performance. The second conclusion was that following DRY made it extremely easy for us to alter the performance of the application. If this were all that could be said than it would be more than enough, however, since the focus of this benchmark was on the effects of memory management, garbage collection activity was monitored. To monitor GC, the -verbose:gc JVM flag was set and the subsequent output was processed by HP JMeter. The resulting graphical display is shown in figure 1. What we are looking at is a comparison of object creation rates of both the original benchmark in red and the "improved" version in yellow. From this view we can see that String version created 79,354.22 Mbytes of data where as the improved version created 14,661.595 Mbytes. I am not sure if there are any words that I can use that could add to the visual impact. There remains yet one unexplained point in this benchmark, the differences in CPU utilization between the two. I ran the benchmark on a multi-core 3.2 GHz Pentium IV processor running Windows XP Pro. As is standard with all my machines, I have swap memory turned off. This effectively pins the JVM into memory, as there is no room for it to swap. I mention this because the inability to fully utilize a CPU is almost always attributed to disk or network I/O or some form of contention such as locking. And with that note I will provide one other clue before I leave the mystery to you to solve. Since the second benchmark also was not able to reach 100% sustained utilization there is likely more than one source of contention. As is the case with most benchmarking exercises I find that I am once again pleasantly surprised by the results. Also both Heinz and I often talk of the benefits of DRY with a lot of hand waving. We do this in a world where it is widely believed that you must violate best practices in order to achieve good performance. Thus it is satisfying to demonstrate how helpful DRY is with a concrete example. Kind regards, Kirk Pepperd...
https://www.javaspecialists.eu/archive/Issue134.html
CC-MAIN-2020-05
refinedweb
1,907
56.45
SERVICE INFORMATION AUDIO TELEX DCM120 POWER AMPLIFIER CONTENTS: OPERATION MANUAL CIRCUIT DESCRIPTION SET-UP / TEST PROCEDURE SCHEMATIC DIAGRAMS PCB OVERLAYS COMPONENT LISTS Australian Monitor 1 Clyde Street, Silverwater NSW 2128 Australia +61 2 9647 1411 g o AUlilrDililt@ co M M u N I CATI ff{lTl O N SPrar LrD I .fr, O DCMl 20 l- 120w Power Amplifier a g 3 = Ouditv EndorseA "ffiiH c .frl - G l- o Aud io Tel"1$pJnn"y,3j":"?ljons Pty Ltd NSW & ACT 149 Beaconsfield Street Private Bag 149 Silverwater NSW 2128 Australia Ph 02 96/.7'141'l 42 Commercial Road PO Box 871 221277 Middleborough Road Fortitude Valley QLD 4006 Ph 07 38521312 Fax 07 32521237 PO Box 151 FaxO29648 3698 299 Fitzgerald Street West Perth WA 6005 PO Box 404 North Perth WA 6906 Ph 08 92284222 Fax 08 9228 4233 Box HillVlC 3128 Blackburn South VIC 3130 Ph 03 98907477 Fax 03 9890 7977 Electronic Concepts Pty Ltd 76 George Street Thebarton SA 5031 PO Box 7034 Hutt Street Adelaide SA 5000 Ph 08 82349444 Fax 08 8234941 New Zeafand Unit B, 11 Piermark Drive PO Box 512 Albany NZ 1331 Ph 09 4159426 Fax 09 415 9864 K W McOulloch Pty Ltd 54a Albert Road MoonahTAS 7009 Ph 03 62286373 Fax 03 6278 1063 DCM120,12O Watt Power Amplifier Product Description The DCM120 is a 120 watt power amplifier in a two rack unit (2RI) chassis suitable for table or direct 19" rack mounting. The DCM120 has outputs for 100 & 70 volts, 4 & 8 ohms. It has a balanced input of 10K ohms. The DCMI2O will operate from 240 V AC @ 50 tlz or I I 0 VAC @ 60 llz (not user selectable, internal, facrory adjusnne,nt only, specify at the time of ordering) or 24 YD(, and will meet it's frrll poformance specification on either voltage supply. The DCMI2O also features a DC battery tickle charge facility, auto-sensing fan cooling, plus overload, shrt circuit and over temperature protection. The maximum recommended load for the DCM120 is 80 ohms. lnitial Set Up There is an unlabelle4 screwdriver adjustable output level contol located curfrally on the front panel of the DCMI20. will increase the power output, turning this control in a counter-clockwise direction will reduce the power output. The factory default setting for this conhol is such that a I volt input wilt give a 100 volt output. Turning this control in the clockwise direction Front Panel Controls Output Level: The output level control is unlabelled recessed (screwdriver adjustable) and is located in the centre of the front panel, just to the right of the DCM Series logo. Turning the control clockwise will increase the output of the DCM120 towards it's maxim'm output level while turning the control cormter-clockwise will decrease the output level. Adjust this contol for the desired output level depending on the level of the input signal (from a mixer or other sigrraisource). fni factory default setting for this control is zuch that a 1 volt input will give a 100 volt output. Power Switch: The rocker switch located in the front centre of the panel turns AC power on to the DCMI20. Rocking the power switch to the right to turns the AC pow€tr 'on'. When the AC power is 'on', a gre€n LED will glow in the amplifio status display window. Please note that this switch does not switch DC voltage. If a DC voltage supply is connected to the DCMI20, the amplifier will operate as soon as the connection is madg regardless of the positim of the AC power switch. If both an AC and DC voltage supply are connected and you rock the AC power switch to the 'off position, the DCM120 will automatically continue to op€rate normally from the DC supply (and the 'mains failure' LED in the amplifier status display window will also glow under these conditions; see the amplifier status display window section under Front Panel Confols later in this manual). Cooling Fans (Air lntake): The cooling ftn is temperature sensitive and will only switch on when the tqnp€rature of the DCMI2O had reached a predetermined range. The fan will stay on and only switch off again once the temperature of the DCM120 has frllen below a pre-determined level. So, the hct that the frn is not operating at anytime (and most noticeably to the op€rator at turn-ur) does not man that $s emplifia is ftulty itt any way, just that it is op€rating within a t€mp€rature range that does not need ftn cooling for adequate heat dissipation. If the DCMI2O is operating continually at conservative levels and froper load cmditions, it is possible that the cooling frn will not switch on at any time during normal operation. When operating, the ftn cause air flow from the front to the rear ofthe DCM120. Continued noct page3 Amplifier Status Display WindoW: Please refer to Figure #1 on the back page The status display window highliehts the operating conditions of the DCM120. sheet with numerical reference as follows: ofthis instruction t High TempefatUfe: This red LED glows if the hn has failed and the amplifier has been shut down by its' temperature control circuitry. If this LED is glowing and the fans have not ftiled, it means that the amplifio is operating in an ambient environme,nt that it naturally too hot for ftn cooling to make any difference to the temperature of the amplifier. Z PoWef: This LED glows green if AC power is switched on to the DCM120. Note that this LED does not indicate the pres€nce of a DC supply voltage tlains Failure: The LED glows red if there is a ftilure in the AC mains power supply. However, this LED glow if there is a DC supply voltage present. If no DC supply voltage is preseirt then this LED will not glow. ileter: will only w Output Level VU A 10 segment LED meter is provided to give an indication of the output signal level of the DCMI2O from -25 to +3 dB. For normal op€ration the LED's should oscillate in and out of the red zone. tf the LED's in the red zone are lit continually, then the output level control (or the level of the input signal to the DCMI2O) should be adjusted to reduce the output level. Too much output level can cause distortion and possible damage to the cornected speaker system. Rear Panel Gonnections Please refer to Figure #2 on the back page of these instructions with numerical references as follorrys: 3 Pin lEC, AC Mains Power lnlet. The operating voltage is 240 VAC @ 50Hzor 110 VAC @ 60llz. The AC power voltage level is not externally user selectable but is factory prs'set (via transformer selection). The inlet is equipped with an inbuilt AC fuse holder fitted with a 4 Amp slow blow fuse plus one spare fuse. Power consumption is 300 VA. Please ensure that the mains power cord is disconnected before attempting to check or rephce this fuse. Output Terminal Strip . Reading from left to right these connections are as follows: Common for low impedance 4 Ohms 8 Ohms Common for constant voltage systems 70 volts 100 volts 24 VDC Power Connection. rhe left side red post is the + (positive) terminal while the right side black post is the - (negative) terminal. The DC curr€nt drain is 8 Amps, manimum at full power. This socket also provides trickle charge to a DC battery supply (if connected) when the DCM120 is operated from AC mains power. The level of trickle charge is 300 md maximum. DC Low Voltage Fuse Receptacle. Access the DC fuse by turning the cap half a tum counter-clockwise with a screwdriver. The value of the fuse is l0 Amps Please ensure that the AC power switch is in the 'ofr position and that the mains power cord is disconnected before attenpting to check or replace this fusc lnput (& Parallel Output) XLR Signal Connection. The input to the DCM120 is transformer balanced @ 10K ohms. The pin configuration of both sockas is as follows: pin #l-earth; pin #2-active (hrgh, +); pin #3-active (low, -). The output socket is to allow the original input signal to be fed on to another amplifier. As these two sockets are wired in passive parallel, the failure of any one amplifier will not affect the signal flowing through that amplifia to another amplifier. tll!||l||tl lllllillil! llll||l!iiil ulE !l+ dl -_- --r (-'.' -- dl ) ilIB oIs= a----------------) -_-------c---------------) c-----------) -_----------) ---- oI (.------------ -_f -__- ol (--__--------- ol ililil!lr!llil cl c) -I I\) o l||l||ll!tl ltll||l!tl! l!o N DCM Series Circuit Description The DCM series are power amplifiers designed for commercial installations. They can be used for either low impedance (4 ohm/8 ohm) or constant voltage line speakers (100v/70v). These amplifiers can be mounted in a standard 19” equipment rack or they can be used on a shelf or table. The DCM series feature line level input (with parallel output) and are normally used with mixers, mixer amplifiers or other power amplifiers. The DCM series will operate from mains voltage or 24VDC. The DCM series also feature a DC battery trickle charge facility, auto-sensing fan cooling, plus overload, short circuit and over temperature protection. Power Switch This switch controls the switching of AC power to the amplifier. A blue ‘On’ LED will indicate whether the amplifier is switched on or off. This switch will not switch DC power on or off in DC operation. In DC operation mode, the amplifier is always on and the blue power LED will always be illuminated. If both AC and DC voltage supply are connected and the AC power switch is in the off position, the amplifier will continue to operate normally from the DC supply and the mains fail LED will indicate. Level Control The output level control is located in the centre of the front panel. It is a fully recessed screwdriver adjustable pot. Turning this pot cw will increase the gain of the amplifier. At maximum setting the input sensitivity is 300mV. The amplifier ships from the factory with the sensitivity set to 1V. Amplifier Status Display This VU meter indicates the output level of the amplifier. The sensing for the circuit is taken on the amplifier side of the output transformer. The 0dB level is referenced to 100V. This is an RMS meter, not a peak meter. Protect The protect LED will illuminate when the amplifier cuts out because of either over current or high temperature. The amplifier will switch back on after approx 4 sec for an over current trip. The amplifier will switch back on after the amplifier has cooled to 60degC for a thermal trip. Limiter The limiter is a hard limiter with an attack time of about 1msec. It is defeatable by removing the jumper on the solder side of the front pcb. This however is not recommended as voltage overload and speaker transformer current saturation may cause the amplifier to cut out under normal program material. Current Limit and Setup Current limit is controlled by a microprocessor (PIC12C509A). The detection is done by sensing voltage across the emitter resistors. Trimpot P1 on the front pcb is accessible through the hole in the top right of the chassis return (only visible with the lid off). Turning the trimpot ccw will decrease the point at which the amp cuts out ie the amp will cut out earlier. (P1 resistance is increased.) To set the current limit: 1. Reset the trimpot P1 turning fully clockwise. 2. Connect the amplifier to half it’s minimum load (10ohm for DCM500, 20ohm for DCM250, 40ohm for DCM120). 3. Run an rms 1kHz sine wave into the amplifier and set the input level so that you read 425mVDC (DCM250/500) or 825mVDC (DCM120) across the emitter resistor, measuring the side which has the higher current (measured as a voltage across the emitter resistors). 4. Turn the trimpot P1 ccw till the amplifier cuts out. The amplifier is set to the factory default. Thermal and Fan control and Setup The thermal cutout and fan is controlled by a microprocessor (PIC12C509A). The temperature is sensed using a 10k@25degC NTC. The fan is normally off and turns on to full speed at 60degC. This temperature is fixed and not adjustable. The thermal cutout temperature is set using the trimpot accessible through the hole in the top left side of the chassis return (only visible with the lid off). Turning the trimpot cw will decrease the point at which the amp cuts out ie the amp will cut out earlier. Power Amp The power amplifier is a push pull single supply amplifier driven by a class A transformer coupled front end. The drive is provided by HEXFETs (RF9520/9530) into NPN BJTs (TIP35C). When replacing the FETs it is recommended that you replace both FETs. The matching of these FETs determines the balancing of the emitter currents in the output devices. For optimum performance the emitter currents in each side should match to within 30% of each other. Bias Setup The amplifier is set with a bais setting of 1mV measured across the emitter resitors. Bias is set using the trimpots located on the power pcbs on each side of the amplifier. Turning the trimpots cw increases the bias. If the HEXFETs have been replaced the resistor in series with the pot may need to be changed. Use a lower value resistor if the bias cannot be turned off or a higher value if the bias cannot be turn on. AC Power Inlet The operating voltage is 230/240 VAC @ 50 Hz. switch is set correctly for your part of the world. The inlet is equipped with an in-built AC fuse containing the rated fuse and a spare. 24 Volt DC Power Inlet The DCM series feature optional 24VDC power to run off a battery back-up if required. This is connected via the rear binding posts. The front panel Power Switch will not switch DC power ‘on’ or ‘off’ in DC operation. In this mode the amplifier is always ‘on’. The trickle charge resistor across the diode is a 47ohm/5watt wire wound resistor. The maximum trickle current is 300mA supplied from internal 35V rails. 230V/240V Slide Switch The operating voltage of the amplifier is user selectable between 230V and 240V via a slide switch located on the center of the rear panel. This switch should be set to match the AC voltage of your country. The mains transformer is wound with a 230V winding plus a 10V winding internally connected. Speaker Output Terminal Strip The screw terminals located on the top left of the rear panel allow access to the direct speaker outputs of the amplifier. Reading from left to right the terminals are: COM 4 8 Common or “-” for low impedance speaker loads (4 or 8 ohms) Positive “+” for 4 ohm speaker loads (use with common) Positive “+” for 8 ohm speaker loads (use with common) DCM120 only COM 70 100 Common or “-” for 70v or100v speaker loads Positive “+” for 70v line speaker loads (use with common) DCM120/500 only Positive “+” for 100v line speaker loads (use with common) Please ensure that the correct “Common” is used. Low impedance and 70/100v loads can be used simultaneously but please pay careful attention to the overall speaker load. Note: The minimum impedance (or maximum load) at 100 volt line should be no less than DCM120 – 80 ohms DCM250 – 40 ohms DCM500 – 20 ohms XLR Audio Input and Parallel Output The DCM series includes both male and female 3 pin XLR connectors per channel. While the female is normally used as the input to the amplifier, both XLR’s are connected in parallel so either will work. The XLR’s inputs are transformer balanced and wired as: Pin 1: Shield. Pin 2: Hot, +, Positive Pin 3: Cold, -, Negative Fuse Sizes (DCM120) Mains: 230 VAC 4 Amperes Slow Blow HRC 20x5mm DC: 10 Amperes Slow Blow HRC 20x5mm (DCM250) Mains: 230 VAC 6.3 Amperes Slow Blow 20x5mm DC: 2 x 10 Amperes Slow Blow HRC 3AG (DCM500) Mains: 230 VAC 10 Amperes Slow Blow HRC 20x5mm DC: 2 x 35 Amperes Slow Blow 3AG TESTING PROCEDURE OF DCM 120/DCM 250/DCM 500 I. PRE-TESTING (of complete sets). • Check 1.1 All screw for tightness (Bridge rectifier and transistor bolts) 1.2 Earth Connection for good contact (solder and crimpling) 1.3 This setup has signal input to the Amplifier through male (XLR) 1.4 Check with Multimeter that there is a DC resistance of about 250 Ω between Pin2 & Pin3 of each of XLR’s. Also between (Pin 1 & Pin 3) and (Pin1 & Pin2). There should be very high resistance. (IE: no reading). 2. Electrical Check 2.1 Fuse Check: Mains fuse: DC fuse: DCM 120 DCM 250 DCM 500 4AT 10AT (x1) 6.3 AT 10AT (x2) 10 AT 35AT (x2) 2.2 Connect the Amplifier to the setup (Variac voltage = 0V) set all presets on front board (only) fully clockwise, voltage selector switch to 230V 2.3 Slowly increase the input voltage to 230V, keep watching the input current should not exceed 0.1A for DCM-120, 0.1A for DCM-250, 0.1A for DCM 500. 2.4 Check and reset if necessary all emitter resistor voltages with the help of preset. (Each emitter resistor voltage should be between 0.5 mV to 0.8 mV ) 2.5 Check DC voltage Main rail = 33V 7815 input = 30V 7815 output = 15.5V 2.6 Give input signal of 500 mV to get outputs as follows (@ 4Ω output load)/ 22V for DCM 120, 32VAC for DCM250, 44.7VAC for DCM 500. Check 100V O/p at 100vV line, Remove the input signal II. FINAL TESTING (This setup should have signal input to Amplifier through female (XLR) (The limiter link should be out of circuit initially.) 1. Connect the Amplifier to the setup, set voltage selector switch to 240V 2. Switch ON the set to 240VAC. 3. Slowly increase the input signal (of 1kHz) keep watching the 24dB LED, it should glow at approx 9V output. Increase the input signal to get 70VAC output. 4. Check Dc voltage of all emitter resistors, Minimum value should be within 30% of the maximum value. 5. Slowly increase the input signal, keep watching the 0db LED, it should glow at 100V ± 5V output voltage. 6. Set 100V 1kHz as 0db reference. Change frequency to 10kHz check dB level drop. It should be 2.5dB ± 0.5dB. 7. Change the frequency to 1kHz, reduce signal level to get 10VAC output. Half the output load. 8. Overload setting: - Check the DC voltage at the emitter resistors having the maximum voltage value. Increase input signal to get 820mV for DCM 120, 425mV (for DCM250 & DCM 500). Turn preset (P2) anticlockwise such that it just mutes the output signal and signal returns back slowly after 2 seconds. 9. Reduce the signal & re check whether the signal mutes at the corresponding above stated voltages. 10. Again make the output load to original full value. Turn volume preset fully anticlockwise, set input signal strength to 1V, set volume preset clockwise to get 100V output. 11. Set input signal strength to get output 110V VAC. Insert limiter link, the signal should reduce to 100V ± 5V. 12. Remove the input signal and check noise. It should measure less than 25mV. III. THERMAL & SOAK TEST 1. Connect the Amplifier to the setup : Output load = 4Ω Output Voltage: (DCM 120): 14V. (DCM 250):20V. (DCM 500): 40V 2. Set the Amplifier thermal cut off temperature at around 105°C with the help of preset P4. 3. Leave the unit “ON” (with lid fixed, if possible) for 24 hours. IV. Sound Test/Listening test. 1. Switch On the set. Check for any switch on thump. 2. Connect CD player to the input, listen for irregularities if any. 3. Switch off the set check for switch off noises. -c (J ? gj'. rt ur{ ( { L a/t \ A \.V -l - bl ? ,.e{ '.. U)[fi'. -l Fl a (D Cl- u) o a o \o r,' g3- f\ c roI ril'' q or fil (tG. lIC I't c F ft U' G F (tJ ? G (\a ,tt e\ r'l6 A11 t-JlF I aox pq I o I Fa a (J F. E fsl 3 O 0* \o j 3 t pa \o s $ts C\ H F a- (J A lal E H I $t a C3 N l -o E a, L (J \o ]-l A tr c) !F tA (J A E (\l a{ € g tE I r't t> l-" rl (J !F -{ lrrl ': t rl* u ldr -1.J. ; @ f\ \o 1 D 2 X1 1 500R 2 R2 3 220R R1 3 4 6 7 8 +35V 100R D R3 V1 TIP41C R4 220R TIP35C X2 1 5 TIP35C V4 R5 1K D1 R6 150R R7 150R V5 R8 47k D2 2 IRF9520 3 4 V2 R17 1K R18 R22 R19 1K R20 R22 5 R9 0R X3 1 C 2 R11 10R C1 820P R13 470R R10 10k NTC 35V R12 1K IC1 78L05 R15 10R R14 1K R16 4K7 X3 4 V3 BC556 5 V11 TIP41C 3 X4 1 FAN 2 D4 15V 6 C T2 100VAC 70AC D3 COM 2 5 1 D5 R34 47R R21 1K X7 R37 1K IC2 78L05 R41 NOT USED BC556 V9 R23 1K R22 470R R24 4K7 8 R43 22R 5 4 4 OHM COM 3 X6 R38 3K3 5 4 B R25 10R C2 820P 3 TO X7 B 2 R26 150R 1 R27 150R R28 1K IRF9520 R29 R22 R39 1K R40 R22 R42 10R X5 V7 V8 R31 1K 2 47k TIP35C + BATTERY 24V - D7 F2 10A R30 D6 T1 F1 4A BR1 +35VDC TIP35C S1A V6 1 X6 V10 D8 40A R33 220R C3 R32 220R 240AC IN S1B 10000U TIP41C +35V 500R R35 R36 100R A A Title Size A3 Date: File: 1 2 3 4 5 6 DCM120 POWER PCB CD6206-1 B Number 8-May-2003 C:\DCM Manuals\CD6206-12.DDB 7 Revision Sheet of Drawn By: 1 8 1 SBG 1 2 Microprocessor 3 4 5 6 7 8 Mute/Limiter/Drive VCC 13 VCC 2 3 4 VDD VSS GP5 GP0 GP4 GP1 GP3 GP2 8 R16 2M2 7 X3/1 6 C5 2u2 47K P2 5 R35 33K I/O Desc 7. GP0-OUT = 1/2VCC CON 6. GP1-OUT = FAN CON 5. GP2-OUT = PRTCT/MUTE VCC 4. GP3-IN = I LIMIT 3. GP4-IN = FAN SENSE 2. GP5-IN = THRML SENS 3 14 5 12 6 11 7 10 8 9 C13 47P R29 10K 2M2 R27 15 C17 2u2 R25 10K LK2 C9 .47u C12 R19 2u2 100K R30 10K V5 BC546 VU Display X1/2 V1 BC639 D1 C23 100P R12 100R C3 10u LK4 0R R8 100R R21 39k C2 2u2 R11 390R VCC LK6 0R 10k R22 C X3/2 IC2B LM358 Battery Indicator X2/1 (N/C) C6 2u2 R24 10k D2 R10 1K R7 100R X5 IC2A LM358 0R LK3 C19 47u R3 10K IC4B LM833-B AGND R9 5K6 V8 BC556 R17 47K D X1/1 R5 680R X1/3 R20 10k IC6/P5 C T1A R1 68K C1 2u2 VCC R26 10K C33 4u7 R23 10K C14 47P 4 100K R15 Pin IC3A SA571 2 2u2 C10 C8 100P C26 4u7 16 R28 1 D 1 100K IC6 PIC12C509 VDD IC4A LM833-A R4 10K V2 BC639 68K R2 X3/3 T1B X3/5 R6 680R AGND X3/4 X1/5 3 IC7 LN3915 C35 4u7 9 5 R48 1K 6 B D31 D17 11 D18 12 7 R49 10K 10 13 D19 D20 +3DB 0 R44 1K D16 VCC C32 4u7 V4 BC556 X1/4 -6 VCC D13 Fan Control X2/5 X2/6 (N/C) D27 IC6/P5 D10 MAINS FAIL Thermal Sense R42 1K R43 470R -3 Protect/On Indicator VDD R51 1K R55 10K P4 10K R56 10K IC6/P2 V6 BC546 IC6/P6 R46 1K2 14 D21 B X4/4 FAN CONTROL IC6/P3 -9 X2/4 X4/3 X4/1 8 R41 15 R45 2K7 -12 PROTECT POWER Power * * D22 16 D23 Current Limit R14 22R -15 X2/3 IC1 7815 IC5 7805 16VDC VCC VDD VDD X4/2 R41=15K=DCM120/500 R41=12K=DCM 250 17 D24 -18 18 D25 -21 R32 470K V9 BC556 X4/6 GND C7 D4 100u C4 C20 47u VDD 2u2 1 A D26 R33 22K IC6/P4 IC6/P7 4 R36 10K V7 BC546 V3 BC546 AGND 8V2 AGND 2 R31 10k C11 22u R13 10K C16 100u -25 C15 100u R34 22K C18 4u7 4 5 P1 2K DCM DRIVER Date: File: 3 X4/5 Title Number 6 Revision CD6200-1 A3 2 X2/2 R53 1K A Size 1 R18 1K 6-May-2003 Sheet of C:\Protel Files\CDTRAX\CD6200-14.DDB Drawn By: 7 D 1 1 SBG 8 DCM120 Output Component List Designator BR1 C1 C2 C3 D1 D2 D3 D4 D5 D6 D7 D8 F1 F2 IC1 IC37 R38 R39 R4 R40 Part Type KBPC 3506 820P 820P 15,000uF LED 1N4148 1N4007 1N4148 1N4007 LED 1N4007 40A ** T10A 78L05 78L05 220R NTC 10k KBPC 3506 1K 470R 1K 10R 4K7 1K R22 1K 500R R22 1K 470R 1K 4K7 10R 150R 150R 1K R22 100R 47k 1K 220R 220R 47R 500R 100R 1K 3K3 1K 220R R22 Description Bridge rectifier 400V 35A Multi layer Ceramic Capacitor Multi layer Ceramic Capacitor Electrolytic Capacitor 50V LED Green 3.0mm Diode Rectifier Diode Rectifier Diode Rectifier Diode Rectifier LED Green 3.0mm Diode Rectifier Stud Mount Rectifier Diode Fuse, Refer Manual Fuse 10A HRC Regulator 5V TO92 Regulator 5V TO92 Metal film resistor .5W Thermistor NTC Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Resistor, Metal Oxide 2W Metal film resistor .5W Metal film resistor .5W Wire wound resistor 5W Metal film resistor .5W Cermet, preset horizontal Wire wound resistor 5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Resistor, Metal Oxide 2W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Wire wound resistor 5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Thermistor NTC Wire wound resistor 5W Cermet, preset horizontal Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Wire wound resistor 5W R41 R42 R43 R5 R6 R7 R8 R9 S1A S1B T1 T2 V1 V10 V11 V2 V3 V4 V5 V6 V7 V8 V9 80D 10R 22R 1K 150R 150R 47k 1K Switch Switch Mains XFMR Output XFMR TIP41C TIP35C TIP41C IRF9520 BC556 TIP35C TIP35C TIP35C IRF9520 TIP35C BC556 Not Used Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Metal film resistor .5W Switch DPST Switch DPST Mains Transformer Output transformer Transistor Transistor TOP-3 Transistor TO220 Mosfet, Hexfet TO220 Transistor TOP-3 Transistor TOP-3 Transistor TOP-3 Transistor TOP-3 Mosfet, Hexfet TO220 Transistor TOP-3 Transistor TO92 DCM Series Drive Stage Component List Designator C1 C10 C11 C12 C13 C14 C15 C16 C17 C18 C19 C2 C20 C23 C26 C3 C32 C33 C35 C4 C5 C6 C7 C8 C9 D1 D10 D13 D16 D17 D18 D19 D2 D20 D21 D22 D23 D24 D25 D26 D27 D31 D4 IC1 IC2A IC2B IC3 IC4A IC4B IC5 IC6 Part Type 2u2 2u2 22u 2u2 47P 47P 100u 100u 2u2 4u7 47u 2u2 47u 100P 4u7 10u 4u7 4u7 4u7 2u2 2u2 2u2 100u 100P .47u 1N4148 L-LED(red) L-LED(red) 1N4148 L-LED(red) L-LED(red) L-LED(grn) 1N4148 L-LED(grn) L-LED(grn) L-LED(grn) L-LED(grn) L-LED(grn) L-LED(grn) L-LED(grn) L-LED(grn) 1N4148 1N4007 7815 LM358 LM358 SA571 LM833-A LM833-B 7805 PIC12C509 Description Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Multi layer ceramic capacitor Multi layer ceramic capacitor Electrolytic Capacitor 16V Electrolytic Capacitor 16V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Multi layer ceramic capacitor Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 35V Electrolytic Capacitor 16V Multi layer ceramic capacitor Metalised Poly Capacitor 63V Rectifier Diode LED 3.0mm LED 3.0mm Rectifier Diode LED 3.0mm LED 3.0mm LED 3.0mm Rectifier Diode LED 3.0mm LED 3.0mm LED 3.0mm LED 3.0mm LED 3.0mm LED 3.0mm LED 3.0mm LED 3.0mm Rectifier Diode Rectifier Diode Voltage regulator I.C TO220 Comparator, dual IC DIP Comparator, dual IC DIP Compander IC DIP Dual op-amp IC DIP Dual op-amp IC DIP Regulator IC TO92 Programmable IC DIP LK2 LK3 LK4 LK6 P1 P2 P4 R41 R41 R42 R43 R44 R45 R46 R48 R49 R5 R51 R53 R55 R56 R6 R7 R8 R9 0R 0R 0R 0R 2K 47K 10K 68K 1K 390R 100R 10K 22R 100K 2M2 47K 1K 100K 68K 10k 39k 10k 10K 10k 10K 10K 2M2 100K 10K 10K 10K 10k 470K 22K 22K 33K 10K 10K 15K* 12K** 1K 470R 1K 2K7 1K2 1K 10K 680R 1K 1K 10K 10K 680R 100R 100R 5K6 Link, zero ohms Link, zero ohms Link, zero ohms Link, zero ohms Cermet, preset Horizontal Potentiometer 16mm Cermet, preset Horizontal T1A T1B V1 V2 V3 V4 V5 V6 V7 V8 V9 RF2285A RF2285B BC639 BC639 BC546 BC556 BC546 BC546 BC546 BC556 BC556 Please note Please note Driver Transformer Driver Transformer Transistor TO92 Transistor TO92 Transistor TO92 Transistor TO92 Transistor TO92 Transistor TO92 Transistor TO92 Transistor TO92 Transistor TO92 * DCM120-DCM500 ** DCM250
http://manualzz.com/doc/1196612/audio-telex-dcm120-service-information
CC-MAIN-2018-13
refinedweb
5,062
69.31
Hi, I am working on a project where we are using angular-cli. I am configuring the paths property in the tsconfig.app.json (), so that I can import for example like so: import { MyComponent } from '@modules/core' instead of import { MyComponent } from '../../../modules/core' when I build with angular (ng serve or ng build) everything works fine. But webstorm doesnt recognize the path and I get an error on the input (and of course no code completion when I type in the import) Should I configure something ? (I dont want webstorm to do the typescript compilation, as angular-cli is already taking care of that) thank you for your help Anton Please can you provide your tsconfig.json? Please have a look at this sample project: The tsconfig file is src/tsconfig.app.json (so it is not the one in the root). This is particular to angular-cli () If you look on line 8 in src/app/app.module.ts you can see how I imported the button component. This only works beause I configured the paths property in the tsconfig.app.json. when you run the project (with thte command ng serve) everything is fine, but webstorm show it as an error. ( I believe this way of creating an alias is relatively new to Typescript ) thank you for your help in this issue Anton >The tsconfig file is src/tsconfig.app.json (so it is not the one in the root). sorry, but tsconfig.app.json is not tsconfig.json - it's just a config file internally used by the cli build process. TypeScript compiler doesn't consider such files, only tsconfig.json files are respected. If you run tsc in terminal, you will see the same error: C:\downloads\sample-master\sample>tsc src/app/app.module.ts(8,33): error TS2307: Cannot find module '@app'. Adding to the tsconfig.json in the root solves the issue I'm using Intellij IDEA Ultimate and I'm seeing the same problem. (note the /*) to get ng serve to compile. IntelliJ IDEA 2017.2.3 Build #IU-172.3968.16, built on August 21, 2017 Licensed to FUJIFILM TeraMedica / Mike Conner Subscription is active until December 14, 2017 JRE: 1.8.0_152-release-915-b11 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 7 6.1 Running tsc in terminal gives similar result for your mappings: C:\WebstormProjects\untitled>tsc app/test.ts(1,25): error TS2307: Cannot find module '@app/services/myService'. Try changing mappings to Yeah, my mistake. Between when I originally posted it and you responded, I had already seen the error and updated my comment. I originally had it as @app/*, based on a stackexchange post, but changed it, per your response to Anton ("Adding "paths": { "@app": ["app/"] },... to the tsconfig.json in the root solves the issue, and didn't realize that it broke the build before I first posted. Anyway, even after fixing it (switching back to "@app/*": "app/*"), I was still getting a problem. However, based on another post, I saw that someone was using "src for baseUrl: And appears to work. I'm guessing you don't have the problem because app is at the root of your project, for some reason. Looking at your screencap, the tooltip says: C:\WebstormProjects\untitiled\app\service\... Where untitled is presumably your project. But a project I generated with angular-cli is of the form: myproject\src\app That is, with a src in between. So app/* would not match anything. I'm guessing I could have instead changed the path mapping to "src/app/*", and not changed the baseUrl, too. Haven't tried it, yet.... OK tried it, that didn't work. Don't get it. Oh well, in any case, the baseUrl:src seems to do the trick. I have the same issue it would be nice to have a commonly applicable solution that works both with angular-cli, IntelliJ and Typescript. Is there an issue for this problem in YouTrack that I can follow? What issue, sorry? No bugs are reported in this thread, so there is nothing to track Hi, I have same problems on Mac OS. My tsconfig.json (root): The WebPack success compile and application correct work if I import the client as: But the PhpStorm write the error You don't have "baseUrl"specified in your tsconfig.json. And "paths"are resolved relative to "baseUrl", so this property is required. See Note that passing your tsconfig.json to tsc in terminal results in tsconfig.json(18,5): error TS5060: Option 'paths' cannot be used without specifying '--baseUrl' option. error. Adding to your tsconfig.json should solve the issue: @Elena Pogorelova, thank. All works! Hi, I have a project created using the Ionic CLI: I have configured 'compilerOptions' in 'tsconfig.json': Everything works as expected (e.g., npm run dev, npm run build, npm run test, etc.) except in WebStorm 2017.2 I receive the following error for '*.spec.ts' files: All other '*.ts' file are fine: Cheers Rob Hi, Just noticed that if I remove "**/*.spec.ts" from 'exclude' the error goes away: "include": [ "src/**/*.ts" ], "exclude": [ "node_modules", "src/test.ts", "e2e" ] Does WebStorm support a 'tsconfig.spec.json' ? Cheers Rob >Just noticed that if I remove "**/*.spec.ts" from 'exclude' the error goes away as the file is excluded from tsconfig.json, path mappings specified there are not applied to it - this is the expected behavior >Does WebStorm support a 'tsconfig.spec.json' ? No, it doesn't. TypeScript compiler service doesn't consider such files, only tsconfig.json files are respected. Hello, Same problem for me. My tsconfig.json: The error is : Angular: Can't resolve all parameters for myComponent. Someone can help me ? :) Thank you ! And your problem is also different. Guys, would you be so kind to create new threads for new issues/queries? Instead of adding comments to age-old threads, commenting on issues that have almost nothing in common with yours? Your error is thrown by Angular language service, not by the IDE itself. Looks related to and Try disabling the service (in Settings | Languages & Frameworks | TypeScript, clear the Angular language service checkbox) - does the problem persist? Sorry, I'll open a new topic next time! It works well with the change. Thank you very much Elena I have the same issue (Webstorm 2018.2.5, Ubuntu 18.04.1 LTS). Angular language service is turned off. Running ng build works fine, but I have an error in my editor. My tsconfig.json: I have the following project structure: --lab5 --backend --api.ts --frontend --tsconfig.json (baseUrl:"..", paths: { "@backend/*": ["backend/*"] }) --src --app --users --users.component.ts (import { UsersAjaxAPI} from '@backend/api') Webstorm still reports me an error, though it provides me a link and opens me the correct file if I press Ctrl+Mouse1 Similar configuration works fine for me: BTW, what is a result of running tsc -p . in frontend directory? Do you have any other tsconfig.json files in your project? Sample project that shows up the issue would be helpful It's a miracle, but yesterday I left my project with that error untouched. Today everything works fine, no errors are reported. I can't reproduce that issue, no matter what I do, though I still have to disable Angular language. This is still an issue. what issue? I have this Restarted everything a hundred times, still get cannot find module similar path mappings work fine for me. Please share a project that can be used to recreate the issue And, please, would you be so kind to create new threads for new issues/queries? Instead of adding comments to age-old threads, commenting on issues that have almost nothing in common with yours?
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000158164-Angular-CLI-with-paths-in-tsconfig
CC-MAIN-2022-05
refinedweb
1,301
68.36
Some explanations on the aspects module The main parts The core module defines the base class for all aspects. The weaver module defines the class which is responsible for weaving code. The Weaver class is a Singleton, and you can import the existing instance created in the weaver module, using this import command : from logilab.aspects.weaver import weaver The main methods which can be called on the weaver's instance are weave_pointcut and unweave_pointcut which weave and unweave some aspect-related code on a specified list of breakpoints. There are also some convenience methods to weave directly on an entire module, or class, or instance without having to create a PointCut's instance. The lib module contains some useful aspects like : - LoggerAspect which will trace all method calls. - ContractAspect which will enable design by contract in Python. - Other aspects exist like ProfilerAspect, DispatcherAspect, ConfirmationAspect or ObserverAspect, but they are not always fully implemented. Anyway, you can use them or want to have a look at them to give you ideas of useful aspects or improvements. Some unit tests, and some examples can be found in the tests or examples directory : aspects/examples/contract_example.py aspects/examples/logger_example.py Defining a Pointcut When you want to weave an aspect on an entire class, or module, you will directly use the weave_methods or weave_module methods. But, when you want to weave an aspect only in a part of the class (i.e. not on all methods), then what you'll have to do is to create a PointCut's instance, and then call the weave_pointcut method. A PointCut (in this package), is basically a dictionnary with instances or classes as keys, and the list of method's names which you want weave an aspect on. As PointCut inherits the 'dict' Python base type, you can directly defines its keys and values, though it is recommended to use the provided methods : add_method (resp. remove_method) which will add (resp. remove) a method_name, for a given instance or class, to the pointcut the list of static methods that instantiate directly a Pointcut from a class, an instance, or a module : - create_pointcut_from_module() - create_pointcut_from_class() When the pointcut is created, then you just have to weave the aspect on it by doing : weaver.weave_pointcut(pointcut, aspect_class) A simple use case (Taken from logger_example.py) : # Import the weaver and the aspect to use from logilab.aspects.weaver import weaver from logilab.aspects.lib.logger import LoggerApsect import sys stack = StackImpl() # Push an element on the stack, the method call is not traced stack.push("an element") # Weave aspect code (log will be done on sys.stderr) weaver.weave_methods(stack, LoggerAspect, sys.stderr) # Push an other element, method call will now be traced stack.push("another element") # Unweave logger aspect weaver.unweave(stack, LoggerAspect) # Now, call methods aren't traced anymore stack.push("a third element") In this example, we have weaved an aspect on a given instance. As a consequence, other instances of the same class will not be aspected. The best way of weaving all class instances, is to weave the aspect directly on the class, not on the instances. The syntax is exactly the same : weaver.weave_methods(StackImpl, LoggerAspect, sys.stderr) Creating your own aspects For now, it's only possible to wrap methods, not attribute accesses. To create a new aspect, you must define a class which inherits from AbstractAspect (in aspects.core), and define before(), after() and around() methods. Note that you can choose to override only one of this three methods since the default behaviour is to "simply pass". It is important, when overriding the around method to explicitly call self._proceed(...) which is the effective call to the wrapped method. Let's write a simple aspect which will write BEFORE before the method call and AFTER after. from logilab.aspects.core import AbstractAspect class SimpleAspect(AbstractAspect): def before(self, wobj, context, *args, **kwargs): """Before method """ print "BEFORE ",context['method_name'] def after(self, wobj, context, *args, **kwargs): """After method. print the return value """ print "AFTER ",self.method_name,", return value is ", context['ret_v'] This example is quite simple, and is not really useful, but it should show how to define your own aspects. Here is some information on the above code: - The before() parameters are : - self : The aspect instance - wobj : The weaved object instance (on which is called the wrapped method) - context : a dictionnary which holds a set of values in relation with method calls. (see below). - args and kwargs are the arguments passed to the wrapped method. If inside before(), you want to have the name and the value of each argument, you can use the function reassign_function_arguments in the aspects.prototypes module. It will return a dictionary containing arg names as keys, and arg values as values. - The after() and around() parameters are the same. - context can have the following keys : - method_name : the called method's name. - ret_v which : the value returned by the wrapped method. - excption which : the exception raised by the wrapped method, or None if no exception was raised. IMPORTANT : The weaver is a Singleton that holds all informations related to the weaving, for instance which method is weaved, which aspect it's weaved with, etc.. When an aspect is weaved on a method, the weaver will look is that aspect has already been instantiated, and in that case, it will use that aspect's instance to weave code around the method. This will soon be changed because it can be unconvenient. (aspects behave a bit like Singleton). Examples of aspects provided by the module The aspects module contains some useful aspects like : - LoggerAspect : which will. You can find more information about contracts and aspects here. - There are other aspects like ProfilerAspect (a simple method profiler), DispatcherAspect (to enable multimethods), ConfirmationAspect (to ask confirmation before an operation), or ObserverAspect (an aspect implementation of the Observer Design Pattern), but they are not always fully implemented. Anyway, you can use them or want to have a look at them to give you ideas of useful aspects or improvements. More information about AOP Here is a set of useful links for Aspect Oriented Programming: - The original idea. - Aspect home page. - Another page listing aspects links. - AspectJ is a Java exhaustive implementation of AOP. Here's an AspectJ tutorial. - Some citesite results. - Some other Python solutions for aspect programming : Pythius, and PEAK (which is actually not only an aspect implementation). Download The aspect aspects module can be downloaded from Logilab's ftp site. You will find the source distribution and some debian packages. To install it from the source distribution, just type python setup.py install after having unzipped the archive. Feedback Please send any comment, patch or question to the python-projects mailing-list.
https://www.logilab.org/file/3704
CC-MAIN-2020-34
refinedweb
1,122
55.84
AUPARSE_GET_NODE(3) Linux Audit API AUPARSE_GET_NODE(3) auparse_get_node - get the event's machine node name #include <auparse.h> const char *auparse_get_node(auparse_state_t *au); auparse_get_node gets the machine's node name if it exists in the audit event from the current event's timestamp data structure. Not all records have node names since its an admin configurable option. Returns a copy of the node name or NULL if it does not exist or there was an error. The caller must free the string. auparse_get_timestamp(3), auparse_get_time(3), auparse_get_milli(3). auparse_get_serial Sept 2007 AUPARSE_GET_NODE(3) Pages that refer to this page: auparse_get_milli(3), auparse_get_serial(3), auparse_get_time(3), auparse_get_timestamp(3)
http://man7.org/linux/man-pages/man3/auparse_get_node.3.html
CC-MAIN-2018-26
refinedweb
107
58.18
JSON Overview Up until recently XML was the solution that was often chosen as the data transmission format. Often times, the communication involved a very verbose form of XML known as SOAP. More recently a new format has arrived that has begun to replace XML as the data transmission format of choice, especially when dealing with web sites and web applications, called JSON. JSON stands for JavaScript Object Notation and is a lightweight data-interchange format that is easy for humans to read and write and is easy for machines to generate and parse. (I paraphrased this paragraph some from:) Most major programming languages have support for JSON in one way or another through libraries or, in some cases, built right in. RESTful services in .NET, for example, can return XML or JSON. Initially I thought JSON was just for objects, as its name suggests, but it turns out that it can be used to represent two different structures: - an Object - or, an Array Creating a JSON Object A JSON Object is created by having an opening curly brace ({) followed by name/value pairs. Each name/value pair is separated by a comma (,). The name/value pair itself is separated by a colon (:). The name is a string but the value can be a string, number, object, array, true, false, or null. Being able to use an object for the value portion of a name/value pair opens possibilities such as nesting additional JSON objects within a JSON object or creating functions within the JSON object. The JSON object is closed by using a closing curly brace (}) JSON objects are declared and initialized in one step and result in what’s known as a singleton object. Being able to create a singleton object is not unique to JSON. You can cause a standard JavaScript class to be created as a singleton object but there is a bit more work involved to do so. The difference is that, with JSON, the object cannot be declared in one spot and then initialized later like a standard class can be. The following is the simplest JSON object you can create: var objObject = {}; The above example is simply shorthand for writing the following: var objObject = new Object(); The following is an example of a JSON object created that has two properties FirstName and LastName with the values Sam and Smith respectively: var objEmployee = { "FirstName": "Sam", "LastName": "Smith" }; Using the new objEmployee object in JavaScript is simply a matter of using the dot operator to access the properties that were created as in the following example: alert("The employee’s name is: " + objEmployee.FirstName + " " + objEmployee.LastName); Creating a JSON Array To create a JSON Array you use an opening square bracket ([) followed by comma separated values and closed by a closing square bracket (]) The simplest JSON Array that you can create is an empty array using the following syntax: var arrArray = []; The above example is simply shorthand for writing the following: var arrArray = new Array(); The following is an example of creating an array containing three strings: var arrArray = [ "One", "Two", "Three" ]; Creating a JSON Class It totally depends on your needs if JSON is the right choice for you when it comes to creating classes. Some people find JSON classes simpler and easier to read. I personally don’t see a big difference between the readability of a standard JavaScript class and a JSON class. If you’re happy with all of your members and methods in a class being public, creating the class using JSON is a bit simpler especially since you don’t need to declare the class first and then initialize it later. This is because a JSON object/class is automatically initialized as soon as it’s declared resulting in what is known as a singleton object since you only get the one object per class declaration. This automatic initialization when the JSON class has been declared has its uses like if you wanted to have a global namespace object that contains some helper methods and don’t want to require the developer of the page(s) to initialize the object first before using the methods (acts like global functions but contained in a more structured class). A JSON class is constructed the same way a simple JSON object is created but instead of a simple variable or object, you use a function as the value portion of the name/value pair as in the following example: var Employee = { "FirstName": "Sam", "LastName": "Smith", // Our method to return the Employee's full name "GetFullName": function () { return (this.FirstName + " " + this.LastName); } }; alert(Employee.GetFullName()); Converting strings of JSON into JSON objects When requesting JSON data from a server it usually gets returned as a string of text. Whenever possible it is recommended that the parsing of a string into a JSON object be done using the native browser methods if the browser supports those methods. Converting a string of JSON into a JSON object, using the native browser object, is as simple as the following: var sJSON = "{ \"FirstName\": \"Sam\", \"LastName\": \"Smith\" }"; var objJSON = JSON.parse(sJSON); alert("JSON object's data: " + objJSON.FirstName + " " + objJSON.LastName); In Conclusion JSON is an interesting technology that can simplify some tasks as well as help to reduce the amount of bandwidth used when transmitting data between components over the internet/intranet especially when compared to SOAP. The large number of libraries and built-in functionality for JSON also makes passing data using this format much easier. (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) Zqudlyba Navis replied on Sat, 2011/04/23 - 9:01pm Javin Paul replied on Sun, 2011/04/24 - 6:43am I was looking for something which explains JSON in simple word and here my search ends. First paragraph has been nicely setup for anyone who is not aware of JSON like me . Just curios does Java also supports JSON , does it have any API for creating and consuming JSON object ? Thanks. Javin How Serialization works in Java Evan Shooter replied on Sun, 2011/04/24 - 10:20pm Abhishek Chavan replied on Mon, 2011/04/25 - 5:18am Anilchandra Noo... replied on Mon, 2011/04/25 - 9:51am Hi Gerard, Thanks for such a good article very crisp and clear.Many thanks for your time on this. Philippe Lhoste replied on Tue, 2011/04/26 - 8:10am Shoaib Almas replied on Sat, 2012/01/21 - 11:20am
http://java.dzone.com/news/json-overview
crawl-003
refinedweb
1,088
52.33
deque::front Visual Studio 2013 Returns a reference to the first element in a deque. If the return value of front is assigned to a const_reference, the deque object cannot be modified. If the return value of front is assigned to a reference, the deque object can be modified. When compiling with _SECURE_SCL 1, a runtime error will occur if you attempt to access an element in an empty deque. See Checked Iterators for more information. // deque_front.cpp // compile with: /EHsc #include <deque> #include <iostream> int main( ) { using namespace std; deque <int> c1; c1.push_back( 10 ); c1.push_back( 11 ); int& i = c1.front( ); const int& ii = c1.front( ); cout << "The first integer of c1 is " << i << endl; i++; cout << "The second integer of c1 is " << ii << endl; } The first integer of c1 is 10 The second integer of c1 is 11 Show:
https://msdn.microsoft.com/en-us/library/s78e3as4.aspx
CC-MAIN-2015-18
refinedweb
142
66.13
Your V-Play Sample Launcher App download has started! This app allows you to quickly test and run all the open-source examples and demo games available with the V-Play SDK. Before we start with the tutorial on how to create a match-3 game with V-Play, we should focus on the basic idea behind such games. I think most of you already know games like Candy Crush Saga or even got invited to play such games. The main concept is simple: The game continues like that until a certain criteria is reached, for example: We will stop our game when there are no groups left to remove. When this happens, we show the player score and provide a button to start a new game. The player can remove a group by clicking it and gets points based on the number of elements in the group. When you create the game with this tutorial you will learn how to: If you are not yet familiar with the basic setup of projects, QML or how to create your own entities, please consider taking a look at the following tutorial to help you get started: Now we are ready to go! But first things first, we still need to set the theme for our match-3 game: In the game Juicy Squash we want to mix the most delicious smoothie in the world! So let's fill the blender in our kitchen with all kinds of fruits and squash them to reach the perfect juicy score! ;-) We also provide the full source code of Juicy Squash made with V-Play in the V-Play SDK. See here where to find the demo in your SDK directory. You can find two game versions there: All the resources of the game should be placed within the assets directory of the project. You can download them here. Let us start with creating a new empty project in QtCreator. We will use the portrait mode as interface orientation. After you finish the project setup, please add the downloaded resources to the assets folder of your project. They should appear in the Other files\assets directory of the project tree. Please take care not to add an additional subdirectory that might be created when you unpack the resources archive. That's all the setup we need, let's start to implement the game! The first thing we want to accomplish is to create the fruits and place them within a grid. But before we add any new entities and complex calculations, you should replace your Main.qml with the following implementation. qml/Main.qml: import VPlay 2.0 import QtQuick 2.0 GameWindow { id: gameWindow activeScene: scene // the size of the Window can be changed at runtime by pressing Ctrl (or Cmd on Mac) + the number keys 1-8 // the content of the logical scene size (480x320 for landscape mode by default) gets scaled to the window size based on the scaleMode // you can set this size to any resolution you would like your project to start with, most of the times the one of your main target device // this resolution is for iPhone 4 & iPhone 4S screenWidth: 640 screenHeight: 960 // custom font loading of ttf fonts FontLoader { id: gameFont source: "../assets/fonts/akaDylan Plain.ttf" } Scene { id: scene // the "logical size" - the scene content is auto-scaled to match the GameWindow size width: 320 height: 480 // property to hold game score property int score // background image BackgroundImage { source: "../assets/JuicyBackground.png" anchors.centerIn: scene.gameWindowAnchorItem } // display score Text { // set font font.family: gameFont.name font.pixelSize: 12 color: "red" text: scene.score // set position anchors.horizontalCenter: parent.horizontalCenter y: 446 } } } These few lines will provide a basic design for our game. We define a BackgroundImage that already shows the game layout. This image is bigger than the actual scene size we defined. On different devices with other screen ratios more of the background image will show in order to avoid dark borders. Please check out the tutorial on scaling modes and support of multiple screen sizes if you are interested in this topic. We also display the player score in our own custom font. This is achieved by adding the FontLoader component and setting the source to our font in the assets directory. Let's hit play and see if everything works fine up to this point! Your screen should look like that: Now let's move on to the fruits we want to add. We have many different kinds of fruits in the game, but beneath the different appearance they share the same game logic. We can treat them as a single game entity with different visual representations. Just create a new file Block.qml within your qml folder and add the following lines of code. qml/Block.qml: import VPlay 2.0 import QtQuick 2.0 EntityBase { id: block entityType: "block" // each block knows its type and its position on the field property int type property int row property int column // emit a signal when block is clicked signal clicked(int row, int column, int type) // show different images for block types Image { anchors.fill: parent source: { if (type == 0) return "../assets/Apple.png" else if(type == 1) return "../assets/Banana.png" else if (type == 2) return "../assets/Orange.png" else if (type == 3) return "../assets/Pear.png" else return "../assets/BlueBerry.png" } } // handle click event on blocks (trigger clicked signal) MouseArea { anchors.fill: parent onClicked: parent.clicked(row, column, type) } } The main idea is to set up each block as an independent entity that knows its position on the grid and its type. Based on the value of the type property we simply show a different fruit image. In order to listen to clicks on a fruit by the player, we added a MouseArea that covers the whole item. Whenever a block is clicked, it emits a signal that holds all the relevant information. This way we can conveniently use a single function to handle the clicked signals from all the blocks in the game. And furthermore, we directly know at which grid position the click occurred and what type of fruit is at that position. The fruits are now ready to be created and added to the game, but we will need a lot of game logic and calculations for the grid. We do not want to directly place all of that within our game scene. To achieve a better separation of code and clear responsibilities of components we will create an additional item GameArea.qml to hold the grid of fruits and all the necessary calculations. qml/GameArea.qml: import VPlay 2.0 import QtQuick 2.0 Item { id: gameArea // shall be a multiple of the blockSize // the game field is 8 columns by 12 rows big width: blockSize * 8 height: blockSize * 12 // properties for game area configuration property double blockSize property int rows: Math.floor(height / blockSize) property int columns: Math.floor(width / blockSize) // array for handling game field property var field: [] // game over signal signal gameOver() // calculate field index function index(row, column) { return row * columns + column } // fill game field with blocks function initializeField() { // clear field clearField() // fill field for(var i = 0; i < rows; i++) { for(var j = 0; j < columns; j++) { gameArea.field[index(i, j)] = createBlock(i, j) } } } // clear game field function clearField() { // remove entities for(var i = 0; i < gameArea.field.length; i++) { var block = gameArea.field[i] if(block !== null) { entityManager.removeEntityById(block.entityId) } } gameArea.field = [] } // create a new block at specific position function createBlock(row, column) { // configure block var entityProperties = { width: blockSize, height: blockSize, x: column * blockSize, y: row * blockSize, type: Math.floor(Math.random() * 5), // random type row: row, column: column } // add block to game area var id = entityManager.createEntityFromUrlWithProperties( Qt.resolvedUrl("Block.qml"), entityProperties) // link click signal from block to handler function var entity = entityManager.getEntityById(id) entity.clicked.connect(handleClick) return entity } // handle user clicks function handleClick(row, column, type) { // ... } } At the top of the file we define the size of the game area and some additional properties for the block size (size of fruits) and the total number of rows and columns of the grid. We also already prepare a signal we will use later to relay the message that the game is over. The most important part of the object is the field property. It represents the game field (grid) as an array of block-entities. We then have a few functions that help us to fill our game field with fruits: index(row, column) rowand column). initializeField() clearField() createBlock(row, column) handleClick(row, column, type) clicked-signals from the blocks we create. The parameters tell us the position and the type of the block that has been clicked. We connect the signal of our dynamically created blocks with this function through the entity.clicked.connect(handleClick)command. Let's add the game area to our scene and trigger the initialization of the game field. qml/Main.qml: GameWindow { id: gameWindow // ... // initialize game when window is fully loaded onSplashScreenFinished: scene.startGame() // for dynamic creation of entities EntityManager { id: entityManager entityContainer: gameArea } // custom font loading of ttf fonts FontLoader { id: gameFont source: "../assets/fonts/akaDylan Plain.ttf" } Scene { id: scene // ... // game area holds game field with blocks GameArea { id: gameArea anchors.horizontalCenter: scene.horizontalCenter blockSize: 30 y: 20 } // initialize game function startGame() { gameArea.initializeField() scene.score = 0 } } } We also add the EntityManager component we are using in the createBlock-function and specify the game area as the entityContainer for all the blocks. The startGame-function resets the points and the game field. It will be called each time a new game has to be started. The line onSplashScreenFinished: scene.startGame() will trigger the very first initialization after the V-Play splash screen is gone. When you start the game at this point you should already see the grid filled with fruits! Looks delicious! This tutorial is a guide on how to create a match-3 game, so we want to find out when three or more fruits are together. When creating the fruits, we already connect their clicked signal to our handler function by stating entity.clicked.connect(handleClick). We are then going to check all the blocks that are neighbors to the one we clicked. If more than three blocks of the same type are connected, they will be removed.) } } // recursively check a block and its neighbors // returns number of connected blocks function getNumberOfConnectedBlocks(fieldCopy, row, column, type) { // stop recursion if out of bounds if(row >= rows || column >= columns || row < 0 || column < 0) return 0 // get block var block = fieldCopy[index(row, column)] // stop if block was already checked if(block === null) return 0 // stop if block has different type if(block.type !== type) return 0 // block has the required type and was not checked before var count = 1 // remove block from field copy so we can't check it again // also after we finished searching, every correct block we found will leave a null value at its // position in the field copy, which we then use to remove the blocks in the real field array fieldCopy[index(row, column)] = null // check all neighbors of current block and accumulate number of connected blocks // at this point the function calls itself with different parameters // this principle is called "recursion" in programming // each call will result in the function calling itself again until one of the // checks above immediately returns 0 (e.g. out of bounds, different block type, ...) count += getNumberOfConnectedBlocks(fieldCopy, row + 1, column, type) // add number of blocks to the right count += getNumberOfConnectedBlocks(fieldCopy, row, column + 1, type) // add number of blocks below count += getNumberOfConnectedBlocks(fieldCopy, row - 1, column, type) // add number of blocks to the left count += getNumberOfConnectedBlocks(fieldCopy, row, column - 1, type) // add number of bocks above // return number of connected blocks return count } // remove previously marked blocks function removeConnectedBlocks(fieldCopy) { // search for blocks to remove for(var i = 0; i < fieldCopy.length; i++) { if(fieldCopy[i] === null) { // remove block from field var block = gameArea.field[i] if(block !== null) { gameArea.field[i] = null entityManager.removeEntityById(block.entityId) } } } } } The first step is to implement the handleClick-function. We get the position and the type of the block that was clicked as parameters of the function. We then go on with copying the whole current game field into a new local variable fieldCopy. For this purpose the JavaScript function slice() is used, which is one of the fastest ways to copy a whole array. We will need this copy later when we search for and remove connected blocks. The most important function here is getNumberOfConnectedBlocks. It calculates the number of connected blocks based on four parameters: fieldCopy rowand column type Each call to getNumberOfConnectedBlocks will return zero if: rowor the columnparameter is outside of the bounds of our game field. type. If neither is the case, a valid block has been found. The function then removes this block from the field copy. After that all the neighboring blocks are checked in the same way by calling getNumberOfConnectedBlocks again, and the number of all connected blocks in the neighborhood is summed up and returned. To really grasp the concept behind this algorithm, you should be able to fully understand what it means when a function calls itself within its function body. This concept is called "recursion". Maybe you need to read up a bit more on this topic, but i am positive that you can master it. ;-) Once we have the result of this awesome function, we can easily react to the number of the connected blocks we found. If there are more than three, we remove them from the actual game field based on the empty spots in the copy of the field. Note: JavaScript arrays are automatically passed by reference, so the changes made to the field copy by the functions won't be lost. This is necessary, because we work with these changes in other functions like the additional recursion calls and the removeConnectedBlocks function. Press play and you can already start removing blocks! Now we want to move down higher blocks and create new fruits every time we remove a group. We use a new function moveBlocksToBottom for that purpose. This function will be called in our clicked-handler after we removed a group of blocks. In addition, we also calculate and increase the player score to complete our handler function.) moveBlocksToBottom() // calculate and increase score // this will increase the added score for each block, e.g. four blocks will be 1+2+3+4 = 10 points var score = blockCount * (blockCount + 1) / 2 scene.score += spot in grid.y = row * gameArea.blockSize break } } // if no block found, fill whole column up with new blocks if(moveBlock === null) { for(var newRow = row; newRow >= 0; newRow--) { var newBlock = createBlock(newRow, col) gameArea.field[index(newRow, col)] = newBlock newBlock.row = newRow newBlock.y = newRow * gameArea.blockSize } // column already filled up, no need to check higher rows again break } } } // end check rows starting from the bottom } // end check columns for empty fields } } The implementation of the moveBlocksToBottom-function takes care of the following tasks: We apply this function after we removed a group of connected blocks. The player score is then increased in a way that considers the number of blocks that have been removed. A group of three blocks will amount to 1+2+3 = 6 points, a group of four will give 1+2+3+4 = 10 points and so on. With these changes you can already start to play and gain points! A game is no fun if it is never over. Well, in fact the game is already over when there are no more blocks available to remove. At the moment, the user then is stuck with nothing to do. We want to determine if no more groups of three are existing and trigger our gameover-signal when that happens. We can easily do that by trying the getNumberOfConnectedBlocks function on all the blocks of the field. We will cover that by adding a new function isGameOver to our game area. qml/GameArea.qml: Item { id: gameArea // ... function handleClick(row, column, type) { // ... if(blockCount >= 3) { // ... // emit signal if game is over if(isGameOver()) gameOver() } } // ... // check if game is over function isGameOver() { var gameOver = true // copy field to search for connected blocks without modifying the actual field var fieldCopy = field.slice() // search for connected blocks in field for(var row = 0; row < rows; row++) { for(var col = 0; col < columns; col++) { // test all blocks var block = fieldCopy[index(row, col)] if(block !== null) { var blockCount = getNumberOfConnectedBlocks(fieldCopy, row, col, block.type) if(blockCount >= 3) { gameOver = false break } } } } return gameOver } } As we do not want to change the current game field when we check for connected blocks, we again operate on a copy of the field array. The function then works as follows: We now want to react to the signal and display a window with the player score and a "play again"-button when a gameover occurs. Let's add a new file GameOverWindow.qml. qml/GameOverWindow.qml: import VPlay 2.0 import QtQuick 2.0 Item { id: gameOverWindow width: 232 height: 160 // hide when opacity = 0 visible: opacity > 0 // disable when opacity < 1 enabled: opacity == 1 // signal when new game button is clicked signal newGameClicked() Image { source: "../assets/GameOver.png" anchors.fill: parent } // display score Text { // set font font.family: gameFont.name font.pixelSize: 30 color: "#1a1a1a" text: scene.score // set position anchors.horizontalCenter: parent.horizontalCenter y: 72 } // play again button Text { // set font font.family: gameFont.name font.pixelSize: 15 color: "red" text: "play again" // set position anchors.horizontalCenter: parent.horizontalCenter anchors.bottom: parent.bottom anchors.bottomMargin: 15 // signal click event MouseArea { anchors.fill: parent onClicked: gameOverWindow.newGameClicked() } // this animation sequence changes the color of text between red and orange infinitely SequentialAnimation on color { loops: Animation.Infinite PropertyAnimation { to: "#ff8800" duration: 1000 // 1 second for fade to orange } PropertyAnimation { to: "red" duration: 1000 // 1 second for fade to red } } } // shows the window function show() { gameOverWindow.opacity = 1 } // hides the window function hide() { gameOverWindow.opacity = 0 } } The window consists of an image, the player score and a "play again"-button that is already animated by combining a SequentialAnimation with two PropertyAnimations. In addition, the window also emits a signal when the button is clicked. We can open or close this window by calling the show- or hide-function. Note that only the opacity is set accordingly in these functions. We then use property bindings like visible: opacity > 0 and enabled: opacity == 1 to: We can add this window to our scene with just a few lines of code. qml/Main.qml: import VPlay 2.0 import QtQuick 2.0 GameWindow { id: gameWindow // ... Scene { id: scene // ... GameArea { id: gameArea anchors.horizontalCenter: scene.horizontalCenter y: 20 blockSize: 30 onGameOver: gameOverWindow.show() } // configure gameover window GameOverWindow { id: gameOverWindow y: 90 opacity: 0 // by default the window is hidden anchors.horizontalCenter: scene.horizontalCenter onNewGameClicked: scene.startGame() } // initialize game function startGame() { gameOverWindow.hide() gameArea.initializeField() scene.score = 0 } } } We added the GameOverWindow and implemented the handler onNewGameClicked to start a new game. We then set the onGameOver handler in our GameArea-object to show the window and hide it again when the startGame-function is called. Hit play and enjoy your fully playable Juicy Squash game! The game still feels a little bit stiff. We should use animations to fade out the blocks when removing them and actually let the fruits fall down from above. Let's start with preparing the animations in our Block.qml. qml/Block.qml: EntityBase { id: block entityType: "block" // hide block if outside of game area visible: y >= 0 // ... // fade out block before removal NumberAnimation { id: fadeOutAnimation target: block property: "opacity" duration: 100 from: 1.0 to: 0 // remove block after fade out is finished onStopped: { entityManager.removeEntityById(block.entityId) } } // animation to let blocks fall down NumberAnimation { id: fallDownAnimation target: block property: "y" } // timer to wait for other blocks to fade out Timer { id: fallDownTimer interval: fadeOutAnimation.duration repeat: false running: false onTriggered: { fallDownAnimation.start() } } // start fade out / removal of block function remove() { fadeOutAnimation.start() } // trigger fall down of block function fallDown(distance) { // complete previous fall before starting a new one fallDownAnimation.complete() // move with 100 ms per block // e.g. moving down 2 blocks takes 200 ms fallDownAnimation.duration = 100 * distance fallDownAnimation.to = block.y + distance * block.height // wait for removal of other blocks before falling down fallDownTimer.start() } } Note that we set visible: y >= 0 to hide the freshly created fruits that will be placed outside of the game area. They will automatically show when their animation moves them into the game area. We then use two NumberAnimations to realize the fade-out and the movement of the fruits. Before any block starts moving, it should wait for the fade-out of other blocks in the game. To achieve this we use a Timer and set the fade-out duration as its interval. We are going to start the movement after that time has passed. We can now use the fallDown- and remove-functions to animate the fruits: remove-function fades out the block and removes the entity from the game when the animation is finished. fallDown-function waits some time until the removing of other blocks in the grid is finished and then moves the block down by a certain distance. Let's use them within the removeConnectedBlocks- and moveBlockToBottom-functions of our game area. qml/GameArea.qml: Item { id: gameArea // ... // remove previously marked blocks function removeConnectedBlocks(fieldCopy) { // search for blocks to remove for(var i = 0; i < fieldCopy.length; i++) { if(fieldCopy[i] === null) { // remove block from field var block = gameArea.field[i] if(block !== null) { gameArea.field[i] = null block field.fallDown(row - moveRow) break } } // if no block found, fill whole column up with new blocks if(moveBlock === null) { var distance = row + 1 for(var newRow = row; newRow >= 0; newRow--) { var newBlock = createBlock(newRow - distance, col) gameArea.field[index(newRow, col)] = newBlock newBlock.row = newRow newBlock.fallDown(distance) } // column already filled up, no need to check higher rows again break } } } // end check rows starting from the bottom } // end check columns for empty fields } // ... } The removeConnectedBlocks-function now uses the new remove-function of the block. In the previous version of the function, we directly removed it with the entity manager. When we move a block to the bottom or create new blocks, we simply use the fallDown-function instead of changing the y-position of the blocks. Note that when we create new blocks, we now place them outside of the game area by setting newRow - distance as the initial grid position at the createBlock-call. We can watch the fruits fall down now, pretty cool! But at this point it would be possible to click and remove blocks while they are fading out or moving down. We want to ignore these signals to avoid unwanted behavior that may occur when we try to change the field while the previous changes aren't completed yet. For this purpose we will add a function to check if the field is ready. qml/GameArea.qml: Item { id: gameArea // ... // handle user clicks function handleClick(row, column, type) { if(!isFieldReadyForNewBlockRemoval()) return // ... } // ... // returns true if all animations are finished and new blocks may be removed function isFieldReadyForNewBlockRemoval() { // check if top row has empty spots or blocks not fully within game area for(var col = 0; col < columns; col++) { var block = field[index(0, col)] if(block === null || block.y < 0) return false } // field is ready return true } } If the field is not ready yet, we ignore all clicked-events in our handler function. The fieldIsReady()-function only returns true when every spot in the first row of the grid is filled with a block, that has finished moving into the game area. That's all we need to ignore clicks while we fade out and move our fruits. To complete the animations for our game, we also let the gameover-window fade in and out by defining a Behavior on the opacity property. qml/GameOverWindow.qml: Item { id: gameOverWindow // ... // fade in/out animation Behavior on opacity { NumberAnimation { duration: 400 } } // ... } This is as far as we go in terms of animations. When we play the game now, it may be over real quick because there are so many different fruit types on the field initially. This makes it very likely to run out of matches pretty soon. We can counter that by starting with fewer fruits and add other types later during the game. We just need to introduce some additional properties in our game area and use them accordingly. qml/GameArea.qml: Item { id: gameArea // ... // properties for increasing game difficulty property int maxTypes property int clicks // ... function initializeField() { // reset difficulty gameArea.clicks = 0 gameArea.maxTypes = 3 // ... } // create a new block at specific position function createBlock(row, column) { // configure block var entityProperties = { width: blockSize, height: blockSize, x: column * blockSize, y: row * blockSize, type: Math.floor(Math.random() * gameArea.maxTypes), // random type row: row, column: column } // ... } // handle user clicks function handleClick(row, column, type) { // ... if(blockCount >= 3) { // ... // increase difficulty every 10 clicks until maxTypes == 5 gameArea.clicks++ if((gameArea.maxTypes < 5) && (gameArea.clicks % 10 == 0)) gameArea.maxTypes++ } } // ... } We define two new properties maxTypes and clicks to hold the number of currently available types and the number of successful moves the player made. We reset these properties every time we initialize the field. The random type of a new block is then based on the maxTypes property. After each successful player move, we increase the click counter and based on that we may also increase the maximum number of types. We decided to start with only three fruit types and add a new type after every 10th successful move, until we reach our maximum number of types. Congratulations, you just completed this tutorial for the match-3 game Juicy Squash! Of course, you are welcome to include your own ideas, add some twists to the game or create your own match-3 game based on this one. The game is still lacking some major features, you can: You can also try adding blocks with special powers or multiple levels with different goals to make the game more interesting. If you have any questions regarding this match-3 game tutorial, don't hesitate to visit the support forums. Also visit V-Play Engine Examples and Demos to gain more information about game creation with V-Play and to see the source code of existing apps in the app stores. Voted #1 for:
https://v-play.net/doc/how-to-make-a-match-3-game-like-candy-crush/
CC-MAIN-2017-09
refinedweb
4,436
63.9
How should I use the timeit module if I want to start counting time somewhere in my code and then get the passed time? I think I am using the module wrong. import timeitstart = timeit.timeit()print "hello"end = timeit.timeit()print end - start To measure the elapsed wall-clock time between 2 points, you may use time.time(): The following code gives the execution time in seconds: import timestart = time.time()print("hello")end = time.time()print(end - start) import time start = time.time() print("hello") end = time.time() print(end - start) I will suggest you use timeit.default_timer instead of timeit.timeit. timeit.default_timer provides the best clock available on your platform and version of Python automatically:- from timeit import default_timer as timerstart = timer() end = timer() print(end - start) from timeit import default_timer as timer start = timer() end = timer() # It will print Time in seconds, e.g. 5.38091952400282 The timeit.default_timer is assigned to time.time() or time.clock() depending on OS. On Python 3.3+ default_timer is time.perf_counter() on all platforms To know more about this you can have a look at the following video:-
https://intellipaat.com/community/19266/python-how-to-measure-time-elapsed
CC-MAIN-2021-04
refinedweb
190
70.9