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
Closed Bug 330753 Opened 16 years ago Closed 14 years ago Lightning builds compiled with --enable-static fails Categories (Calendar :: Lightning Only, defect) Tracking (Not tracked) 1.0b1 People (Reporter: ssitter, Unassigned) References Details Lightning builds compiled with --enable-static fails If Thunderbird and Lightning are compiled with --enable-static / --disable-shared the resulting Thunderbird build and lightning.xpi does not work together. In my test I build Thunderbird and Lightning from 2006-03-16 trunk cvs on Windows 2000 using VC8. But this has also been reported in Calendar forum and newsgroup. Thunderbird can be started normally. But Lightning does not work with the following symptoms: - Lightning sidebar is displayed but Agenda and Calendar tabs are empty - When switching to a calendar view nothing except the nav buttons is displayed - It is not possible to create new Event or Task. No dialog is shown. - Creation of new calendar opens wizard but does not proceed after entering calendar name and pressing 'Next'. - Preference menu not working Many similar error messages are logged in JavaScript console. Most of the errors looks like the following and happen in different calendar locations: ---------------------------------------------------------------------- Error: [Exception... "Invalid ClassID or ContractID" nsresult: "0x80570017 (NS_ERROR_XPC_BAD_CID)" ... ---------------------------------------------------------------------- Error: [Exception... "Component returned failure code: 0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE) [nsIJSCID.getService]" ... ---------------------------------------------------------------------- Error: [Exception... "Component returned failure code: 0x80570015 (NS_ERROR_XPC_CI_RETURNED_FAILURE) [nsIJSCID.createInstance]" ... ---------------------------------------------------------------------- Error: nsIScriptableDateFormat is not defined ---------------------------------------------------------------------- Error: todoList has no properties ---------------------------------------------------------------------- Error: CalDateTime is not a constructor ---------------------------------------------------------------------- Error: Components.classes['@mozilla.org/calendar/datetime;1'] has no properties ---------------------------------------------------------------------- Error: this.startDay has no properties ---------------------------------------------------------------------- This has been seen before with the official builds (e.g. Bug 301973, Bug 314834, Bug 308958). As a result only the tinderbox configuration were changed. Even if it is not possible to fix the problem right now we should keep this bug open to help users to find this problem. Workaround: Build Lightning with --disable-static / --enable-shared. Happens also on Windows XP SP2 and Branch builds (MOZILLA_1_8_BRANCH). Errors her: Fehler: Components.classes['@mozilla.org/calendar/datetime;1'] has no properties Quelldatei: chrome://lightning/content/messenger-overlay-sidebar.js Zeile: 37 ---------- Fehler: Invalid ClassID or ContractID = NS_ERROR_XPC_BAD_CID Quelldatei: chrome://calendar/content/calendarUtils.js Zeile: 89 ---------- Fehler: Invalid ClassID or ContractID = NS_ERROR_XPC_BAD_CID Quelldatei:[ProfileDir]/extensions/%7Be2fda1a4-762b-4020-b5ad-a41df1933103%7D/components/calItemModule.js Zeile: 64 ---------- Fehler: Component returned failure code: 0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE) [nsIJSCID.getService] Quelldatei: chrome://calendar/content/calendarUtils.js Zeile: 46 Shared build works. Component: General → Lightning The bugspam monkeys have been set free and are feeding on Calendar :: Lightning Only. Be afraid for your sanity! QA Contact: general → lightning Could it be possible to move static to shared builds ? Currently, Minefield is - at least on linux - a shared build. Even it is a little bigger than static builds, but it could help using and debugging lightning. Commenting these lines in mozilla/mail/installer/Makefile.in (around line 90) "ifdef BUILD_STATIC_LIBS ifeq (WINNT,$(OS_ARCH)) MOZ_PKG_MANIFEST_P = $(srcdir)/windows/packages-static endif else $(error you need a "--enable-static --disable-shared" build to create an installer) endif" Could help. Is it possible or not ? Stefan, since lightning (trunk) now always builds as a shared lib and links against frozen API, this should work now. Can we close this bug? Yes, seems to work for Trunk builds now. What about the same issues on MOZILLA_1_8_BRANCH? Haven't tested a static branch thunderbird build, but lightning's components come per (enforced) shared lib now on branch, too. Resolving WORKSFORME per previous comments. Status: NEW → RESOLVED Closed: 14 years ago Resolution: --- → WORKSFORME Target Milestone: --- → 1.0 Target Milestone: 1.0 → 1.0b1
https://bugzilla.mozilla.org/show_bug.cgi?id=330753
CC-MAIN-2022-05
refinedweb
590
51.24
This forum is closed. Thank you for your contributions. Hello, another namespace problem, maybe another newbie question as I dont fully understand the web namespace yet. Im using Design 3 Trial to draw a piece of artwork for a button. Ive exported it to xaml and now have it opened inside Design 4 Beta with a common error. <?xml version="1.0" encoding="utf-8"?><ResourceDictionary xmlns="" xmlns: <DrawingBrush x: .... yadda yadda Error: The name "DrawingBrush" does not exist in the namespace I dont know whats going on...something with referencing...but its a web reference? Compatibility issue? I see that Namespace "" was used for SL 1 and "" for SL onwards so do I chance something in Design to point at the latter? Thank you After reading a similar thread on here I Exported from Design using the option 'XAML Silverlight 3 Canvas' not 'XAML Resource Dictionary'. NOTE: These forums arent very responsive in Oper 10.
https://social.msdn.microsoft.com/Forums/en-US/f903cf13-a698-4141-91e1-9ad2098e3de1/re-namespace-httpschemamicrosoftcomclient2007?forum=blend
CC-MAIN-2021-31
refinedweb
156
58.89
I believe I am having a logical issue with how to develop the section of code responsible for taking the remainder and checking if I can extract change from displayed change categories. It's designed to take a value of how much change you owe back to someone and make the most efficient set of change to give. My current output: The change for 328.0 Euro cents is: 1.64 € 2 1.28 € 1 0.56 € 0.50 1.4 € 0.20 0.8 € 0.10 1.6 € 0.05 1.5 € 0.02 1.0 € 0.01 The change for 328 Euro cents is: 1 €2 1 €1 0 €0.50 1 €0.20 0 €0.10 1 €0.05 1 €0.02 1 €0.01 import java.util.Scanner; // Enables user input public class Change { private static Scanner scnr; public static void main(String [] args) { scnr = new Scanner(System.in); double changeR = 0; // User input double oneCent = 0; // Number of one cent coins double twoCent = 0; // Number of two cent coins double fiveCent = 0; // Number of five cent coins double tenCent = 0; // Number of ten cent coins double twentyCent = 0; // Number of twenty cent coins double fiftyCent = 0; // Number of fifty cent coins double oneEUC = 0; // Number of one Euro cent coins double twoEUC = 0; // Number of two Euro cent coins System.out.println("Please enter the amount of change in Euro cents to be returned (a number between 0 & 499): "); changeR = scnr.nextInt(); // Gathers user input System.out.println("The change for " + changeR + " Euro cents is: "); // Outputs users inputted value twoEUC = changeR / 200; changeR = changeR % 200; oneEUC = changeR / 100; changeR = changeR % 100; fiftyCent = changeR / 50; changeR = changeR % 50; twentyCent = changeR / 20; changeR = changeR % 20; tenCent = changeR / 10; changeR = changeR % 10; fiveCent = changeR / 5; changeR = changeR % 5; twoCent = changeR / 2; changeR = changeR % 2; oneCent = changeR / 1; changeR = changeR % 1; System.out.println( twoEUC + " \u20ac" + " 2"); System.out.println( oneEUC + " \u20ac" + " 1"); System.out.println( fiftyCent + " \u20ac" + " 0.50"); System.out.println( twentyCent + " \u20ac" +" 0.20"); System.out.println( tenCent + " \u20ac" +" 0.10"); System.out.println( fiveCent + " \u20ac" +" 0.05"); System.out.println( twoCent + " \u20ac" +" 0.02"); System.out.println( oneCent + " \u20ac" +" 0.01"); return; } } As is common when dealing with money¹, you need to deal with integers only. Changing all your variables to int will give you the proper values, as integer division will make sure that 238 / 200 = 1. Instead of double division which will result in 238.0 / 200.0 = 1.19. ¹ Handling money in code (as well as real life) is a difficult problem. You need to present the output in a user readable form, so you don't want to show prices as 5.0001 € due to the problem of double imprecision, yet you don't want calculations to do "eager" rounding so the end result is off. One of the simplest ways is to take the smallest "atom", i.e. cents and deal in them only. Why not use double or float to represent currency
https://codedump.io/share/YQnYlqXwcA2n/1/java-euro-coin-change-denomination
CC-MAIN-2017-13
refinedweb
504
67.15
Hello, This message was posted using Page2Forum (attachment) from Extract Text From All the Pages of a PDF Document - Aspose.Pdf for .NET Hello, Hi Prasanth,<?xml:namespace prefix = o Thank you for considering Aspose.Pdf for .NET. Which version of Aspose.Pdf for .NET are you testing with? I tested your scenario with the latest version of Aspose.Pdf for .NET v6.5 and it works fine. Please download and try the latest version and if you still face any issue, please create a sample application and post it here, we will check it soon. Thank You & Best Regards, Hi Nausherwan, Hi Prasanth,<?xml:namespace prefix = o I think the issue you are facing is because you are not using the licensed version of Aspose.Pdf for .NET. You may get a 30 days temporary license to evaluate your required features of Aspose.Pdf. Please use the below link to acquire a temporary license (choose “Get a Temporary License” option). Please feel free to contact us in case you need any further details. Thank You & Best Regards, Hi Nausherwan, Hi Prasanth, <?xml:namespace prefix = o Please see the following documentation links regarding the details on how to setup the license in your code. Using File or Stream object Using as Embedded resource Please feel free to contact support in case you need any further assistance. Thank You & Best Regards,v
https://forum.aspose.com/t/problem-extracting-text-from-attached-pdf/101329
CC-MAIN-2022-21
refinedweb
231
66.94
Opened 4 years ago Closed 4 years ago Last modified 4 years ago #11993 closed defect (fixed) Mercurial plugin not loaded with setuptools>=8 Description Trac[loader] ERROR: Skipping "TracMercurial 1.0.0.6.dev0": (version conflict "ContextualVersionConflict: (trac 1.1.3dev-r13332, Requirement.parse('Trac>=1.0dev'), set(['TracMercurial']))" The mercurial plugin requires Trac >=1.0dev. But it seems setuptools 8 has changed version parsing: from pkg_resources import parse_version parse_version('1.1.3dev-r13332') > parse_version('1.1dev') In setuptools 7 and below this was True. In setuptools 8 and above this is False. It seems one of these versions must be changed to be compliant with PEP:0440? Attachments (0) Change History (10) comment:1 by , 4 years ago follow-up: 3 comment:2 by , 4 years ago The tag_svn_revision option requires pypi:setuptools_svn since setuptools 10.0. See. Even without the changing from dev to .dev, it seems that both version strings are compatible with PEP:0440 and the same value. Unfortunately, tag_svn_revision option currently generates incompatible version string with PEP:0440. >>> import setuptools >>> setuptools.__version__ '12.0.5' >>> parse_version('1.0.3dev') <Version('1.0.3.dev0')> >>> parse_version('1.0.3.dev') <Version('1.0.3.dev0')> >>> parse_version('1.0.3dev') == parse_version('1.0.3.dev') True >>> parse_version('1.0.3dev-r12345') <LegacyVersion('1.0.3dev-r12345')> >>> parse_version('1.0.3.dev-r12345') <LegacyVersion('1.0.3.dev-r12345')> follow-ups: 4 5 comment:3 by , 4 years ago Unfortunately, tag_svn_revisionoption currently generates incompatible version string with PEP:0440. Given the issues we've seen with that option (e.g. th:#10778 seen with plugins - assuming a similar issue could be seen installing Trac), it seems better to just remove it. Do you guys agree? comment:4 by , 4 years ago comment:5 by , 4 years ago …, it seems better to just remove it. Do you guys agree? Agreed. Otherwise, adding inherited egg_info command. Of course, I don't recommend to use it because the base class of egg_info might be modified in the future. $ PYTHONPATH=. /dev/shm/venv/bin/python setup.py egg_info running' $ grep '^Version:' Trac.egg-info/PKG-INFO Version: 1.1.4.dev13863 comment:6 by , 4 years ago Removed in [13902:13906]. I didn't look closely yet at whether #10658 should be closed. comment:7 by , 4 years ago comment:8 by , 4 years ago follow-up: 10 comment:9 by , 4 years ago SpamFilter also has a tag_svn_revision in setup.cfg. comment:10 by , 4 years ago SpamFilter also has a tag_svn_revisionin setup.cfg. I opened #12038 after encountering a problem due to the invalid version number. Apparently 1.1.3dev-r13332should become 1.1.3.dev13332. In egg_info we can change tag_buildfrom devto .dev, but with tag_svn_revisionsetuptools adds the -rautomatically so far. (Though since setuptools 10 that doesn't work anymore out of the box anyway.)
https://trac.edgewall.org/ticket/11993
CC-MAIN-2019-09
refinedweb
477
51.34
2016-02-17 9:33 GMT+01:00 Yury Gribov <address@hidden>: > My understanding is that visibility annotations are indeed useless when > calling external library function because linker will generate a PLT call > regardless. But they are very important for intra-library calls because > compiler will generate direct call and also optimize much more agressively > (especially under LTO). I'm not really sure about that but I'll let you have the benefit of the doubt. > The real problem here is that the same library header is typically used both > by external users and by library internals. AFAIK maintainers typically > annotate it and users have to live with one more (useless) public macro. Can we leave the #ifndef ... #endif clause out of the public headers and install them through "sed -e 's:ACL_API_EXPORT:extern:g'"? If so, can we also rename ACL_API_EXPORT to EXPORT so that the indentation will stay the same. Thanks, Andreas
https://lists.gnu.org/archive/html/acl-devel/2016-02/msg00020.html
CC-MAIN-2022-27
refinedweb
154
53.41
Today, we are pleased to announce the release of MauiKit and Maui Apps 1 S.C. We are present on Twitter and Mastodon: Stable release The 1.2.0 version brings updates, new features, bug fixes, and an improved cross-platform and convergent experience from the apps and the framework. For this release, the packages will be distributed directly from the MauiKit official webpage. The packages for Linux AMD and ARM AppImages, Android APKs, Debian DEBs, and Windows EXE, will be released soon. We will keep you informed when this happens. Some apps might be missing features or present some bugs; if it is the case that you want to report a bug or a feature request, you can open a ticket at the corresponding project repo; you can check the repositories at the Maui Invent Group. Follow the instructions on how to file an issue. We will have performance and bug fixes for the upcoming point releases for 1.2.1 and 1.2.2 before moving on to the 1.3 cycles, which will include new features. For more detailed information, check out the previous posts from Maui Weekly: Apps As of now, the Maui Project provides a set of applications to cover the basic set of standard utilities you might need on your personal computer, from a phone, tablet, or desktop: A file manager (Index), music player (VVave), an image viewer (Pix), text editor (Nota), notes taker (Buho), terminal emulator (Station), contacts manager (Communicator), document viewer (Shelf), a video player (Cinema), a camera app (Booth), and web browser (Sol). Some of the apps are in different states, most of them are stable, some of them are more feature-rich, and some others are in early stages. We have been testing the apps on the PinePhone with Plasma Mobile, and they work quite nicely, there’s still work to be done for startup times, but we are on the right path to get you covered. For this release cycle, we provide packages for Index, VVave, Pix, Nota, Buho, Station, Communicator, Cinema, and Shelf.. Index 1.2.0 What’s new The Index file manager gained support for compressed file types, an embedded file previewer for font file types, archives, and other multimedia file types. There are now more reliable configurations on the settings dialog, responsive support for split views, and a cleaner user interface. When enabled now, there are thumbnail previews for video files and PDFs; this is only available on Linux; other platforms might get this feature in future releases. The search field has been merged with the filter field, and the search now works correctly recursively. For more details, you can read the previous MauiWeekly blog posts linked above. Known issues - Thumbnail previews for PDF and video file types are only available for Linux. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Data syncing for cloud accounts using NextCloud API, there is already some work for it; further work needs to be done to bring it back. Pix 1.2.0 What’s new Optimized grid thumbnail preview sizes and shapes for small screens. A better settings dialog with more options to tweak the browsing experience. Paths are now added or removed correctly to the collection sources. The database system has been dropped in favor of using the file system using MauiKits FileLoader for asynchronous loading images directly from the file system, meaning your collection is always up to date. And overall, nicer browsing views for the tags, aka Albums and Folders views, with collage delegates that let you preview the contents and are updated dynamically. A new information dialog. Known issues - The basic editing tools are only available for testing when using the KImageEditor component, only available on Linux. - When AutoReload is enabled, and a new image is added to one of the collection sources, the whole collection is refreshed; this is not the desired behavior. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Add simple image editing options, right now, thanks to KImageEditor tools like the rotation, flip, crop, and other transformation options are already implemented. - Syncing of your image gallery across devices using NextCloud. - Face detection using AI. - Implement image metadata information with exiv2. Some initial work is done and should be ready for the next point release. VVave 1.2.0 What’s new Gained MPRIS support on Linux and now can use multimedia keys from a remote control or keyboard function keys to control your music or any other services that consume the MPRIS Dbus API. The backend for loading music files and creating playlists has been refactored to be faster. The album and artists’ artwork providers have been fixed, and now the images are correctly retrieved from services like Spotify, iTunes, LastFm, MusicBrainz, and Genius. Added a complete settings dialog with more options, like sorting, collection sources, artwork fetching, and many others. The playlists view has been cleanup and now uses the MauiKit Tagging feature, so tracks added to a playlist, aka a tag, can also be browsed from Index, the file manager. Several different small paper cut fixes were introduced, from the playback bar to the focus view. The YouTube support has been dropped and is planned to be migrated into its own application. Known issues - The cloud view artist’s roll does not work for filtering. - The streaming of cloud music files is not fully optimized and can take some time to load. - Vvave makes usage of NextCloud Music app API, so this app should be installed in your NextCloud instance. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Faster streaming of cloud music files and full usage of the available API Nota 1.2.0 What’s new Faster loading times of text documents. Correctly applying syntax highlighting styles when switching. Added more options to configure the text document, like tab spacing, font sizes, and family. A focus mode to hide distracting interface elements. The improved workflow of split views and tabs. Performance fixes on creation and deletion of tabs and splits. The views for browsing the recent and local text documents have been reviewed and now use the newest MauiKit components and display more relevant information. Known issues - When the places sidebar is disabled, you can still peek at the sidebar by mistake from time to time. - Rich text support is still not correctly supported. - Some text document file types might not be recognized. - Missing markup support. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Add support for rich text file types and markup support. - Support for loading external plugins to extend the functionality, initial work is already done, and some available plugins. - Implement, find, and replace functionality. Buho 1.2.0 What’s new Redesigned books view with a bigger book and booklet pages. The modal dialog popups for creating or editing notes have been removed to use stacked pages, resulting in more space. The syncing and updating of notes is now better on internal or external changes. The links view for collecting links has been dropped and is planned to be moved to Sol, the new Maui web browser app. Known issues - The syncing of notes can get mess-up if the internet collection is lost and the notes are modified; meanwhile, after the app is restarted, the notes might be modified and out of sync. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Support for markup should come directly from MauiKit Editor and DocumentHandler components, benefiting Nota, and any other app using these components. - Support for creating to-do lists. - Improve the syncing of notes. - Support for taking handwriting notes with Doodle component from MauiKit and image processing for translating the image to plain text. Communicator 1.2.0 What’s new Redesigned views and contact pages, dropped the modal dialog popups in favor of stacked pages. The backend was clean up and now adding or editing existing contacts is smoother. The Contact page now has contextual actions depending on the field: email, phone, or address. Known issues - Android support was dropped due to some refactoring and code cleaning from MauiKit; Android support should be restored in the next point release. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Syncing of contacts using NextCloud API. - Support for online accounts from NextCloud. Station 1.2.0 What’s new Correct handling of split views and tabs. Gained a settings dialog for basic configurations. Known issues - Station makes usage of QmlTermWidget; for the app to work, the version needs to be 1.0 and not later, which might cause the app to crash; this issue is still being investigated. For reporting new issues, bugs, or feature requests fill a ticket at: Roadmap - Add more options to the settings dialog to further configuration. - Improved touch UX interaction patterns. Shelf 1.0.0 What’s new Preview thumbnails in the grid view for the document collection. Updated interface using the newest MauiKit components, using AltBrowser for switching from list to grid views. The usage of the Poppler library is now done using the binaries instead of building the sources for Android, macOS, and Windows. Added support for CMake and added desktop file manifest for Linux. Known issues - Some of the viewer functions do not work. - Bookmarks of document pages do not work. For reporting new issues, bugs, or feature requests, fill a ticket at: Roadmap - Add support for other document file types, such as ePub. Cinema 1.0.0 What’s new Cinema is a new app for playing video, browsing, and organizing your video collection by creating albums, aka tags. It has support for not only quick-playing videos but also for queueing videos into a playlist. Known issues - Thumbnails previews for the video is only available on Linux. - Some video file types might not have support, depending on the platform and available plugins installed. For reporting new issues, bugs, or feature requests fill a ticket at: Roadmap - Polished the playback experience by allowing to have a different backend like VLC. - Add MPRIS support. MauiKit 1.2 MauiKit 1.2 introduces new components and a few more utilities for helping to build convergent applications. Some parts have been cleanup or dropped in favor of making MauiKit lighter. There is still a big load of work ahead of us, and this new release takes us a step closer to that convergent future. Since last May of 2020, when we had our first 1.1 stable release, we have been busy working on the framework components and utilities. With over 200 commits, 11360 additions, and 9430 deletions later, we are ready to introduce the new 1.2 release. What’s new The updated components include SettingsDialog, Page, ToolBar, ToolActions, and AboutDialog, among other fixes for the rest. New components: - Separator. - SettingTemplate. - Platform – dependent integrations classes for different platforms. - FileLoader – for asynchronous loading of files in the local filesystem. - Thumbnailer – image provider for generating image previews of different file types from a file URL. The FMH namespace implementation, which includes many useful utilities from file management, data modeling functions, etc., has now been moved to its won CPP file, clearing many compile warnings. Some of the removed parts include the FilePreviewer, the Tagging TagsModel in favor of using MauiKit abstract modeling classes, and some Android platform functions like contacts loading, which only makes sense on Communicator, the contacts app. Known issues - The Thumbnailer right now depends on KIO, so it won’t be available for other platforms other than Linux. - The Platform utility still lacks many needed functions and properties for getting relevant info like the presence or lack of input hardware, like a mouse, physical keyboard, or touch screens. - Multi-selection with touch gestures is still not perfect and can accidentally cause scrolling. Roadmap - Data syncing classes and an improved API for it. - Drop qmake in favor of fully using CMake. What’s next for MauiKit & Maui Apps 1.3 - Enable syncing of data and images on Pix, files in the Index file manager, and of contacts in Communicator. - Make Booth and Sol initial beta release. Our plans for 2021 are: - Fully utilize CMake. - More feature-rich applications - Improve data synchronization using NextCloud. - Improve performance. - Improve the UI cohesion on all supported platforms. - Move beta apps to stable.
https://nxos.org/maui/maui-1-2-0-release/
CC-MAIN-2020-50
refinedweb
2,070
63.19
When python prints or returns a stacktrace, it displays the appropriate line from the *current file on disk*, which may have changed since the program was run. It should instead show the lines from the file as it was when the code was executed. Steps to reproduce: 1. Save the following code to a file and run it in a terminal. import time time.sleep(600) 2. While it is running, insert a line before "time.sleep(600)", type some random characters, and save the file. The "time.sleep" should now be on line 4, and some random characters on line 3. 3. Now go back to the terminal and press Ctrl+C (to generate a stacktrace). Expected output: ^CTraceback (most recent call last): File "py1.py", line 3, in <module> time.sleep(600) KeyboardInterrupt Actual output: ^CTraceback (most recent call last): File "py1.py", line 3, in <module> some random characters KeyboardInterrupt
https://bugs.python.org/msg334544
CC-MAIN-2022-05
refinedweb
153
77.23
> Hey guys! I made a static class (in C#) called CodeLine. What I want this class's functions to do is to be called from other scripts and be told to automatically comment out certain lines of code. For example, when you press down a button, the script will comment out a line of code for you. When you let go of the button, it will uncomment the line of code for you. Here's the script: using System.Collections.Generic; using System; using UnityEngine; public static class CodeLine { public static void CommentLine(int line) { } public static void UncommentLine(int line) { } public static void CommentLine(int line, string word) { } public static void UncommentLine(int line, string word) { } } Is it possible to put something in these functions that will comment and uncomment lines of code during gameplay? Thanks! Answer by whydoidoit · Dec 08, 2012 at 05:46 PM No you can't modify code like that during game play - it has already been compiled from the text. On certain platforms it might be possible to emit code at runtime, but I'm not sure that it's ever included. You certainly could never emit code on iOS or the web player. You should probably consider using a Finite State Machine to control different parts of your game. I wrote a tutorial on Unity Gems about Finite State Machines that may help. Thanks. I'll try. A node in a childnode? 1 Answer If there is only 1 instance of a class, should it be Static? - C# 2 Answers How to list all the properties and methods from the class? 1 Answer MonoBehaviour methods in non-MonoBehaviour class 1 Answer How to execute a Skript global? 2 Answers
https://answers.unity.com/questions/360946/auto-commenting-lines.html?sort=oldest
CC-MAIN-2019-18
refinedweb
286
70.02
@vu.edu.pk Views: 4138 Hellow brother plz send me your number or text me 03462040540 Bhai 0302-6276747 please contact me. I need solution of assignment 411 Bhai 0302-6276747 please contact me. I need solution of assignment 411 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Assignment1 { internal class Program { private static void Main(string[] args) { student std = new student(); std.name = "Amanatali"; std.vuID = "MC130202773"; std.degreeprogramname = "MIT"; string filepath = @"E:\amanat\MIT\CS411\mc130202773.xml"; using (StreamWriter writer = new StreamWriter(filepath, false)) XmlSerializer serializer = new XmlSerializer(typeof(student)); Serializer.serialize(writer, std); } } } I have write the above code but it return error,,,pls guide me Same here..... agr solve ho jaye tu plz share kr dyna idea.. Sir please ap yeh code share kr dain ya video with guideline youtube py daal dain.? i'll be thankful...bht try ki phr b error a jata hy run krty hoye.. please guide us... yep there r 5 errors, pls upload the code solution file kasey mil skti ha Bhai 0302-6276747 please contact me. I need solution of assignment 411 Sir please upload the code with classes © 2022 Created by + M.Tariq Malik. Promote Us | Report an Issue | Privacy Policy | Terms of Service
https://vustudents.ning.com/group/cs411-visual-programming/forum/topics/cs411-visual-programming-assignment-no-1-solution-discussion-due?commentId=3783342%3AComment%3A6224431&groupId=3783342%3AGroup%3A4194109
CC-MAIN-2022-05
refinedweb
219
53.88
p6 = Pin(6, Pin.OUT, drive=Pin.DRIVE_3) # set maximum drive strength. Four drive strengths are supported, using the drive keyword argument to the Pin() constructor or Pin.init() method, with different corresponding safe maximum source/sink currents and approximate internal driver resistances: - Pin.DRIVE_0: 5mA / 130 ohm - Pin.DRIVE_1: 10mA / 60 ohm - Pin.DRIVE_2: 20mA / 30 ohm (default strength if not configured) - Pin.DRIVE_3: 40mA / 15 ohm The hold= keyword argument to Pin() and Pin.init() will enable the ESP32 “pad hold” feature. When set to True, the pin configuration (direction, pull resistors and output value) will be held and any further changes (including changing the output level) will not be applied. Setting hold=False will immediately apply any outstanding pin configuration changes and release the pin. Using hold=True while a pin is already held will apply any configuration changes and then immediately reapply the hold. See Deep-sleep mode for a discussion of pin behaviour during sleep. Use the machine.PWM class: from machine import Pin, PWM pwm0 = PWM(Pin(0)) # create PWM object from a pin freq = pwm0.freq() # get current frequency (default 5kHz) pwm0.freq(1000) # set PWM frequency from 1Hz to 40MHz duty = pwm0.duty() # get current duty cycle, range 0-1023 (default 512, 50%) pwm0.duty(256) # set duty cycle from 0 to 1023 as a ratio duty/1023, (now 25%) duty_u16 = pwm0.duty_u16() # get current duty cycle, range 0-65535 pwm0.duty_u16(2**16*3//4) # set duty cycle from 0 to 65535 as a ratio duty_u16/65535, (now 75%) duty_ns = pwm0.duty_ns() # get current pulse width in ns pwm0.duty_ns(250_000) # set pulse width in nanoseconds from 0 to 1_000_000_000/freq, (now 25%) pwm0.deinit() # turn off PWM on the pin pwm2 = PWM(Pin(2), freq=20000, duty=512) # create and configure in one go print(pwm2) # view PWM settings ESP chips have different hardware peripherals: A maximum number of PWM channels (Pins) are available on the ESP32 - 16 channels, but only 8 different PWM frequencies are available, the remaining 8 channels must have the same frequency. On the other hand, 16 independent PWM duty cycles are possible at the same frequency. See more examples in the Pulse Width Modulation tutorial. ADC (analog to digital conversion)¶ On the ESP32, ADC functionality is available on pins 32-39 (ADC block 1) and pins 0, 2, 4, 12-15 and 25-27 (ADC block 2). Use the machine.ADC class: from machine import ADC adc = ADC(pin) # create an ADC object acting on a pin val = adc.read_u16() # read a raw analog value in the range 0-65535 val = adc.read_uv() # read an analog value in microvolts ADC block 2 is also used by WiFi and so attempting to read analog values from block 2 pins when WiFi is active will raise an exception. The internal ADC reference voltage is typically 1.1V, but varies slightly from package to package. The ADC is less linear close to the reference voltage (particularly at higher attenuations) and has a minimum measurement voltage around 100mV, voltages at or below this will read as 0. To read voltages accurately, it is recommended to use the read_uv() method (see below). ESP32-specific ADC class method reference: - class ADC(pin, *, atten)¶ Return the ADC object for the specified pin. ESP32 does not support different timings for ADC sampling and so the sample_nskeyword argument is not supported. To read voltages above the reference voltage, apply input attenuation with the attenkeyword argument. Valid values (and approximate linear measurement ranges) are: ADC.ATTN_0DB: No attenuation (100mV - 950mV) ADC.ATTN_2_5DB: 2.5dB attenuation (100mV - 1250mV) ADC.ATTN_6DB: 6dB attenuation (150mV - 1750mV) ADC.ATTN_11DB: 11dB attenuation (150mV - 2450mV) Warning Note that the absolute maximum voltage rating for input pins is 3.6V. Going near to this boundary risks damage to the IC! - ADC.read_uv()¶ This method uses the known characteristics of the ADC and per-package eFuse values - set during manufacture - to return a calibrated input voltage (before attenuation) in microvolts. The returned value has only millivolt resolution (i.e., will always be a multiple of 1000 microvolts). The calibration is only valid across the linear range of the ADC. In particular, an input tied to ground will read as a value above 0 microvolts. Within the linear range, however, more accurate and consistent results will be obtained than using read_u16()and scaling the result with a constant. The ESP32 port also supports the machine.ADC API: - class ADCBlock(id, *, bits)¶ Return the ADC block object with the given id(1 or 2) and initialize it to the specified resolution (9 to 12-bits depending on the ESP32 series) or the highest supported resolution if not specified. - ADCBlock.connect(pin)¶ - ADCBlock.connect(channel) - ADCBlock.connect(channel, pin) Return the ADCobject for the specified ADC pin or channel number. Arbitrary connection of ADC channels to GPIO is not supported and so specifying a pin that is not connected to this block, or specifying a mismatched channel and pin, will raise an exception. Legacy methods: - ADC.read()¶ This method returns the raw ADC value ranged according to the resolution of the block, e.g., 0-4095 for 12-bit resolution. For compatibility, the ADC object also provides constants matching the supported ADC resolutions: - ADC.WIDTH_9BIT= 9 - ADC.WIDTH_10BIT= 10 - ADC.WIDTH_11BIT= 11 - ADC.WIDTH_12BIT= 12 Some ESP32 pins (0, 2, 4, 12-15, 25-27, 32-39) are connected to the RTC during deep-sleep and can be used to wake the device with the wake_on_ functions in the esp32 module. The output-capable RTC pins (all except 34-39) will also retain their pull-up or pull-down resistor configuration when entering deep-sleep. If the pull resistors are not actively required during deep-sleep and are likely to cause current leakage (for example a pull-up resistor is connected to ground through a switch), then they should be disabled to save power before entering deep-sleep mode: from machine import Pin, deepsleep # configure input RTC pin with pull-up on boot pin = Pin(2, Pin.IN, Pin.PULL_UP) # disable pull-up and put the device to sleep for 10 seconds pin.init(pull=None) machine.deepsleep(10000) Output-configured RTC pins will also retain their output direction and level in deep-sleep if pad hold is enabled with the hold=True argument to Pin.init(). Non-RTC GPIO pins will be disconnected by default on entering deep-sleep. Configuration of non-RTC pins - including output level - can be retained by enabling pad hold on the pin and enabling GPIO pad hold during deep-sleep: from machine import Pin, deepsleep import esp32 opin = Pin(19, Pin.OUT, value=1, hold=True) # hold output level ipin = Pin(21, Pin.IN, Pin.PULL_UP, hold=True) # hold pull-up # enable pad hold in deep-sleep for non-RTC GPIO esp32.gpio_deep_sleep_hold(True) # put the device to sleep for 10 seconds deepsleep(10000) The pin configuration - including the pad hold - will be retained on wake from sleep. See Pins and GPIO above for a further discussion of pad] Warning By default NeoPixel is configured to control the more popular 800kHz units. It is possible to use alternative timing to control other (typically 400kHz) devices by passing timing=0 when constructing the NeoPixel object. For low-level driving of a NeoPixel see machine.bitstream. This low-level driver uses an RMT channel by default. To configure this see RMT.bitstream_channel..
https://docs.micropython.org/en/latest/esp32/quickref.html
CC-MAIN-2022-21
refinedweb
1,240
56.66
23 XML fallacies to watch out for XML is truly wonderful stuff. I've spent the last 20 years (more or less) working with markup and plan to spend the next 20 (indifferent universe willing) doing the same. However, there are some major fallacies that are worth bearing in mind in order to maximize the very considerable return on investment that you can get from XML. There are many traps for the unwary. There are many aspects of the technology that you probably will not come across during standard training or standard reading materials that are well worth bearing in mind. As a document-oriented person, I am biased of course. If your use of XML is purely database-oriented some of these fallacies won't be relevant to you. So, YMMV is the order of the day. That said, here are my favorite XML fallacies (in no particular order): Fallacy 1: All documents have a single, true, unchanging, hierarchical, semantic structure that can be identified and turned into an XML schema. Fallacy 2: An XML schema can capture that structure perfectly, splitting documents crisply into those that are valid and those that are not. Fallacy 3: All documents have a single, unique semantic "type". It is just a matter of finding it and giving it a name. Fallacy 4: XML tags can capture all you need to know about a document and make it completely self describing. Fallacy 5: Creating an XML schema for a document type is the hard part. Everything else is just programming and configuration of off-the-shelf XML tools. Fallacy 6: There is business value in having your own custom tags all the way down to paragraphs and bulleted lists etc. Fallacy 7: XML tags do not cost money because they are very easy to create. Fallacy 8: One document schema is all you need to cover the entire life cycle of any given type of information, from creation through to publishing. Fallacy 9: Documents go through their entire life cycle conforming to the one true schema. That one true schema can be deduced by analyzing a subset of previously created, finished documents. Fallacy 10: XML schemas will not atrophy into structure-less controlled vocabularies as changes are made over time. Fallacy 11: When you find a document that does not fit the XML model you currently have, it is perfectly okay to just loosen the model until it fits. Fallacy 12: There are important differences between element type names and attributes when it comes to capturing the meaning of information. Fallacy 13: Document validity is a black and white matter of (non) conformance to a schema. Fallacy 14: Normal human beings are always more productive in grammar-driven structured authoring environments than they would be in "loose" word processors. Fallacy 15: The semantic structure of content always exists before the content itself has been created. You can start with the perfect end structure and just start pouring the content in, filling in the blanks as it were. Fallacy 16: Zipf's law does not apply to XML element types. Fallacy 17: It is only a matter of time before structure-controlled XML editors become as easy to use as word processors. Fallacy 18: It does not make sense to think of a word processor as a XML tool - even if it stores its data in XML. The XML produced by WP-style tools is nasty and brutish and devoid of any semantic value. It is not truly XML at all. Fallacy 19: It is only a matter of time before browsers can do all sorts of clever things with XML on the client side. Fallacy 20: The only valid way to capture and publish semantic information in documents is with tag names. Putting that sort of information into attributes is a hack. Fallacy 21: The XML namespaces specification is very small and therefore cannot be the cause of significant extra complexity in the XML processing tool-chain. Fallacy 22: Nesting elements is the only legitimate techniques for representing hierarchical structure in information. Fallacy 23: There are only 23 fallacies associated with XML.!
http://www.itworld.com/xml-fallacies-nlstipsm-080122
crawl-002
refinedweb
689
61.87
Communication between LoPy and Node.JS server - miguel1996 last edited by I have a LoPy collecting sensor data that I need to send to a Node.JS server running in a standard PC, wirelessly. I managed to get the LoPy and the PC connected to the same Wi-Fi network, but I have no idea how to send the data between them. This is what I have: from network import WLAN wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == 'network': print('Network found!') wlan.connect(net.ssid, auth=(net.sec, 'password'), timeout=5000) print('WLAN connection succeeded!') break
https://forum.pycom.io/topic/5189/communication-between-lopy-and-node-js-server
CC-MAIN-2022-21
refinedweb
105
69.89
CodePlexProject Hosting for Open Source Software So, I've tried numerous things so far and all have failed. Rather than posting all of my source code and hacking it up, does anyone know of the easiest way to get a HelloWorld WCF service implemented in an Orchard module? I need to post data from a form to the WCF form using jQuery. So, I think I finally have some sort of structure that shows potential. However, with every GET request to my WCF method, I continually receive a 400 Bad Request. I'm not sure if it's something missing in the config and project structure or what. My web.config for the service is stored in the same module as the service. Is that correct or should it be in the main web's web.config? The config looks like the following: <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="CustomizedAjaxBehavior"> <enableWebScript /> <webHttp automaticFormatSelectionEnabled="true" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="MyModule.TestService"> <endpoint address="" behaviorConfiguration="CustomizedAjaxBehavior" binding="webHttpBinding" contract="MyModule.Services.ITestService" /> </service> </services> </system.serviceModel> The service looks like the following: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] public class TestService : ITestService { JavaScriptSerializer _jsSerializer = new JavaScriptSerializer(); [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "HelloWorld")] public string HelloWorld(string firstName) { WebOperationContext.Current.OutgoingResponse.ContentType = "text/json"; return _jsSerializer.Serialize("Hello, " + firstName); } } Which inherits from the following interface: [ServiceContract(Namespace = "")] public interface ITestService : IDependency { [OperationContract(Name = "HelloWorld")] string HelloWorld(string firstName); } When I hit, I get the proper WCF page. However, when I try to hit the method, I get the 400 Bad Request exception. I've tried this both by using a browser and by using the following jQuery: function helloWorld() { var dataToPost = '{ "firstName": "Jason" }'; $.ajax({ cache: false, async: true, type: "GET", dataType: "json", url: "", data: dataToPost, contentType: "application/json;charset=utf-8", success: function (msg) { var status = JSON.parse(msg).HelloWorldResult; alert('Yes!'); }, error: function (msg) { alert('No!\n\n' + msg.statusText); } }); } Thanks in advance for any pointers! Jason, you might want to look at Bertrands older post about Orchard 1.1 features - there is a description of the WCF support: Where do you have your .svc file? I guess it's needed to make everything work. Correct me please if I'm wrong. Also regarding the Web.config - I'm pretty sure it should go to the main one.. Guess it would have helped for me to also post my Routes.cs. It's here: public class Routes : IRouteProvider { private static readonly ServiceRoute _testService = new ServiceRoute("Services/TestService", new OrchardServiceHostFactory(), typeof (ITestService)); public IEnumerable<RouteDescriptor> GetRoutes() { return new[] { new RouteDescriptor { Priority = 20, Route = _testService } }; } public void GetRoutes(ICollection<RouteDescriptor> routes) { foreach (var routeDescriptor in GetRoutes()) routes.Add(routeDescriptor); } } Nice discussion. Anyone can help on how to secure exposed wcf services in orchard, so a winforms app has to pass orchard credentials to access service? First, I'd break that into a separate thread just so it has greater exposure. Secondly, are you just looking to use Orchard's built-in authentication model? Depending on your WCF configuration (ie: REST, etc.) you can likely create a custom OrchardAuthorization attribute that requires an authorization token to be passed with the service and validate that user account within Orchard. I haven't done anything within Orchard, but I have with standard WCF services. pszmyd wrote:. Piotr, I did post my routes. Sorry that I didn't quote you on my posting. It's the 3rd up from this one. I'm still running into 400 Bad Request errors. Try this fix. ravetam wrote: Try this fix. Tried it with no luck. Same response. I am still on v1.3 so I had to add that change in manually in case anything else in that file has changed between 1.3 and 1.4. Hey Jason, I'll try to reimplement your scenario locally and try if I run into similar problems. You're running on a clean Orchard install, or have you made any customizations that touch routing (besides adding the WCF routes)? That sounds either as something caused by custom stuff or it may be a regression bug, because it worked before. Will check. It's a fairly clean install. The only thing I did was add a custom theme and basic content. That's it. Nothing to extend routing besides the WCF routes. I did dabble with the WebAPI routes, but I moved past that and removed that module. When i was implementing WCF Data Services, i notice it doesn't work with a .svc file. So i just rename the extension to .cs, and it works. @jgaylord Have you managed to make it work? I have not. I actually stepped away from it as I needed to get some things out the door first. Try this fix: This fix was required for me to get my WCF service working @ 1.4.0 @AimOrchard The correct answer, thank you very much.. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/350243
CC-MAIN-2017-39
refinedweb
864
50.94
Light-Weight Software Process for ISO 9000? 56 Disgruntled Software Engineer asks: "I work for a large engineering firm and it was recently decided in our company to have our software be ISO 9000 compliant. There exists a software development process in my organization, but it is extremely heavy-weight -- over two-dozen documents totaling 200 pages each! My team doesn't even have the time to read such a process, much less abide by it. I have been tasked by my team in creating a more light-weight process for our team to follow so that our software can pass the audit that is coming soon, but reading through the convoluted ISO website is not helping, and a 'plain English translation' that I found of the standard contains a bulleted list that is 17 pages long! I have not been able to get any idea of how to design a light-weight software engineering process that is ISO 9000 compliant with all of these extremely verbose documents and somewhat odd requirements. Also, the software that my team produces is more for research than for productization, and the dynamic nature of research does not mix well with the rigidity of a software process. What are the bare-minimum set of requirements for ISO 9000 software engineering compliance? What are some tips for designing a process that is light-weight and causes minimal damage in terms of efficient software development? Do you have any interesting experiences or wisdom regarding ISO 9000 and software engineering?" The Tao of Programming (Score:5, Funny). Re:The Tao of Programming (Score:2) Actually, I think it is funny that the parent post is rated "Funny" instead of insightful. Lightweight ISO-9000 is an oxymoron (Score:5, Insightful) If you look who pushes for ISO-9000 it's large and slow moving companies that are used to a large and wasteful style of doing business. The people that sing the praises of ISO-9000 are not usually the ones who have to do the work. If I were you I'd look for a way to get out from under ISO-9000. It that's not possible decide wether you want to stay with a company that thinks so little of it's staff that it mandates the use of a procedure that takes thousands of pages to describe. I've been through BS-5750, ISO-9000, SOX, 21CfrPart11 etc etc etc and it's always the same shit. Software is unlike any other process/tool/discipline that man has ever tried to control, the problems of bad software will not be solved by old and tired audit systems. There is no silver bullet that will address all problems! Re:Lightweight ISO-9000 is an oxymoron (Score:4, Interesting) I wish I had a few mod points One could infer the same about Disgruntled Software Engineer's firm, which already has Standards seem like a great idea. Unfortunately, some people extrapolate to conclude that more and more detailed standards must be an even greater idea. (e.g., "a bulleted list that is 17 pages long!") Having said that, I think there may be a way to give DSE an improvement on two fronts. As I see it, DSE needs two things: The second objective involves real work, so it needs to involve real people (not interns or "process experts"). Make the existing documentation match what truly works and throw out the rest. Note that, because of the requirements of the first objective, "throw out" needs to mean something like "re-document" (by segregating the truly important and valuable into short documents that are used and keeping the rest in impenitrable documents that no one but interns and process experts will read or discuss. It will also give them something to do. Note: if you have an intern or process expert who really adds value and don't think it's fair to relegate them to the space I've identified, then reward them with real titles that reflect real value. There is no silver bullet that will address all problems! Awww Re:Lightweight ISO-9000 is an oxymoron (Score:2) Of course, if the PHB understood in the first place that ISO is not about initial quality, but about being able to track down who to blame when something fails, they might not be so enthusiastic. The whole theory behind ISO 9000 is that, by being able to track down what failed, you can fix it and do better next production run. Doesn't work in software, because software is not a "production run". You don't want version 2, 3 and 4 to be an exact copy of version 1. Re:Lightweight ISO-9000 is an oxymoron (Score:4, Insightful) I've witnessed a CMM process developing, but never suffered through ISO-9000. CMM is interesting in that it has the possibility of being fairly lightweight (at least, level 2 or 3). The problem is that people never get the "point", accountability for ones actions and ability to find out what's going on, and see lots of documents. It gets worse, because there are always people in charge who practically live for documents, that's why they do things that involve writing lots of them, rather than developing software. Then, you have sycophants who want to ingratiate themselves to these people, they just make lots of "helpful suggestions." Then, you have a big group of people, kind of lost in what they're doing, but they're going to do it anyway. In a meeting once, I could sense that our process was getting out of control, and suggested that we have a checklist, so a developer, like I was, at the time, could keep track of all of the pointless crap that he had to do. The checklist idea was added to our process... so, now, the checklist was another thing to do. It had a place for the developer had his manager to sign that he had done each step in the process. My bullets telling me what I had to do to make these people happy became another insane requirement. When the org in question passed their audit (an external organization that I had been contracted to), they had a celebration touting how many documents they had produced in order to pass. In the end, there was a flood of inconvenient documents that provided no more transparency than there would be in their absence. I hope that I didn't offend any of my former coworkers with this. Re:Lightweight ISO-9000 is an oxymoron (Score:1, Insightful) Wrong. ISO-9001 can be horribly misused. However, the purpose of the 9001 is to make business sense. Yes, being auditable is one very strong point, usually much more important than some mysterious "ease". But with "ease" you do not mean ease of calculating defect trends, ease of finding corrections (from e.g. VCS), etc. you mean ease of not doing your job by "easily" correcting bugs without testing or any followup. ISO9001 does not bury stuff into Re:Lightweight ISO-9000 is an oxymoron (Score:1) Some ISO 9000 history: Originally, ISO 9000 was for manufacturing. Each station had a written procedure, was detailed enough for even a blue-collar, high-scool dropout, and it had few variables: make 100 ("how many") widgets that are green ("color"). So, not much variability. In 2001, ISO 9000 tried to include service industries, like software deve Re:Lightweight ISO-9000 is an oxymoron (Score:1) A previous employer tried to get me to do that (write ISO 9000 docs) so that he could hire my replacement at an even lower rate than he was paying me. I was working IT as a network administrator right out of college. He's ou Re:Lightweight ISO-9000 is an oxymoron (Score:3, Interesting) It's been expanded to IT and Software, as well as other purposes for which it is not suited. These are professions that require actual expertise, rather than the ability to mindlessly and accurately follow a set of instructions. Standards help keep nimble competitors at bay (Score:4, Insightful) It's not just becuase those companies like to waste time and money. These big, costly standards are a great way for big companies to compete with small, nimble competitors by getting business and government customers to require them. The increased cost and decreased efficiency keeps small companies out of the game. Re:Standards help keep nimble competitors at bay (Score:2) Get a consultant for a couple days (Score:5, Insightful) I was quite skeptical about ISO9000 at first, but I found that it almost always gets management sign-off and therefore you have an opportunity to encode proper software engineering practices in the procedure. When someone later comes to you with pressure to take shortcuts and crank out crap, you can point back to the procedure and say, 'sorry'. In the end this makes your job happier, despite the bureaucratic trappings of the system. Vagueness is Good (Score:5, Informative) 1. Scoop up butter with knife. 2. Apply to toast. as opposed to: 1. Get butter from fridge. 2. Get knife from drawer. 3. Get bread and place in toaster. Wait until done. 4. Scoop up butter with knife. 5. Apply to toast in back and forth motion covering toast. When they audit you they make sure you follow the procedures you have documented, and you can get into trouble if you really get into details. Re:Vagueness is Good (Score:1) I worked at a major telcom software house, and they were going for ISO9000 certification in the mid-90's while I was there. The key seemed to be that you have a process, that you follow the process, and that you document your following the process. Also important was a feedback loop that included not only internal sources (bugzilla), but external (a way for customers to lodge complaints/requests that is tracked and managed (b Re:Vagueness is Good (Score:1) Describe your process with the minimum detail necessary. ISO9000 isn't about adhering to any particular process, it's about fully documenting your processes and deviations from that process. You get certified by an auditor coming in and comfirming that your processes are adequately documented. How does this help software? It prevents that "brilliant" new marketing VP from coming in and demanding, simply demanding, that you add targeted customer content based Yes, ISO is easy this way! (Score:2) So we didn't. Straight text docs, simple instructions. Just cleaned up what we had laready written (didn't take that much), put things together in order and added a few checklists and charts, filled in the blanks, and made up a high Be Careful (Score:3, Insightful) In other words, forget what you're reading and create your own process, reporting, and compliance documents. Otherwise, you'll be creating a monster that will require several full-time ISO employees whose job description will essentially be, "make all other employees miserable". Our expert's advice was well worth her fee. Any "expert" you hire who advises a massive documentation effort is simply creating future contract work for themselves. Re:Be Careful (Score:3, Insightful) That is the most important point (Score:3, Insightful) That is the most important point: "Say what you do - do what you say" -- and be prepared to demonstrate it to someone else. The "do what you say" part is probabaly the biggest stumbling block. Most corporate cultures are not tuned to that much honestly. Corporations are used to having a pile of rules/regulations/processes and selectivly following them. That does not work with ISO9000. Don't do it. (Score:3, Informative) so the answer is to give up, and just wing it? Re:Don't do it. (Score:3, Interesting) Now if you REALLY want to go quality-wise, you could try NASA's approach. Of course, it means that your LOC will be down to almost nothing, but, hey, what you DO write will be amazingly bug-free. <url: ff.html> The 420,000 lines of code are backed up by 40,000 PAGES of specifications. And 20 years by 260 people. That's 6 lines of specifications for every line of code. In other words, your "hello world" program: #include < Re:Don't do it. (Score:3, Informative) Re:Don't do it. (Score:2) Re:Don't do it. (Score:2) As an aside, I'm really glad to see this article. I plan on bookmarking it and printing out the good comments to show to my boss... YOU set the standard in ISO 9000 (Score:4, Insightful) So reread the spec - it's asking you a question, not giving you a rulebook. What do your customers really want? What tradeoffs do you plan for to meet their needs? Everything in the spec is a question. The audit process is establishing how well you meet your organizations own unique goals. Obligatory Dilbert Cartoon (Score:5, Informative) ISO 9000 is easy.... (Score:4, Informative) 1) Write down what you're going to do. 2) Do it. 3) Write down that you did it. 4).... 5) Profit! Now, FDA rules for medical device software are a whole other game, so maybe my perspective is skewed. Ah, to forget ISO 13485 and go back to _just_ ISO 9000! ISO 9000 (Score:5, Informative) The purpose of ISO 9000 is not to tell you what your process is. You can use any process you want, as long as your customers will accept it. What ISO 9000 requires is that you be able to prove you are following it. If your process requires code reviews, you must have recorded minutes describing the results, and the follow-up, for each one. If you require iteration plans, you must keep records of those plans. If you require the use code analysis tools, you have to record the results of the use of those tools regularly, to show you are meeting whatever benchmarks you choose. And so on. You do whatever you want - just prove that you really are doing it. Put in your documented process everything that you do that you can document as having been done, and that you (as a group) want to keep doing. Do not put anything in your process that you cannot document. Keep a separate description of "best practices" - things that you expect developers to do, but that you do not want to insist on until you are more comfortable with them. In time, some of these methods may migrate into your documented process, but only when you are sure you want to be held accountable for following them. Re:ISO 9000 (Score:1) But no matter which process you use, I HIGHLY recommend that you invenst in tools that will help you follow the process. One such tool is Seapines TestTrack which we've also been using for the Ha! (Score:1) ISO 9000 Compliance (Score:2) Its all about good change-management (Score:1) Everytime you make a change in the program, a document should be written saying who did it, why, when, and what. Everything done to the program should be tracable. And no, a CVS log will not do, but it may help. Here's your problem! (Score:2) I've no experience of ISO9000 in a software development environment but I just ditched it last year at the engineering company I work for, having run the quality system since BS5750 days (UK). If you have a few thousand pages of software development processes to be picked over by an ISO auditor then your life is going to be a living hell. Ditch them and try t Re:Here's your problem! (Score:1) I took an ISO9000 course many years ago as I worked for a small company that needed to become certified for some contracts. Being small, we couldn't afford the ISO Guru. The one thing that the course taught us was that a single sheet of a clear and easy to follow process is better than a volume of detailed The case against ISO 9000 (Score:1) Here's the essense of the requirements (Score:1) Here's an example, you produce a web server - You need to build your software - document how you do that. You need to package your software - document how to do that. Deploy on a test server - document that process too. Setup a test server - document that. How d ISO 9000 is Your Friend (Score:2) As you write, one key is to keep things lightweight, so that everyone can read and follow the procedures. Another key is to write your own procedures - what usually happens is that someone snags a copy of another company's procedures and tries to use them Pick your favorite process and stick to it. (Score:3, Insightful) ISO 9000 boils down to two things: 1) Write down how you are going to do something. 2) Do it the way you said you would. To that end, pretty much any software engineering approach is ISO 9000 compliant, provided that you 1) write down how you are going to develop software and 2) develop software the way you said you would. That means you can pick any "lightweight" software development process you like. Agile, XP, TDD... whatever you want to do, you can do it, as long as you 1) write down how you are going to develop your software in an Agile/XP/TDD way, and 2) develop software the way you said you would. Re:Pick your favorite process and stick to it. (Score:2) If I'm ever put in charge of developing an ISO-9000 compliant software development process, I'll be sure to add a requirement that each engineer is required to drink a beer after fixing every bug! Lightweight PLC (Score:1) Light Weight ISO 9001 Software Development (Score:1) You may not want to hear this, but read on it gets better... As a consultant who supports companies like yours with ISO 9001 (in fact it was one of the software team who sent me the link) there is a way to set up a light weight system and the only people you'll have trouble with are your internal ISO 9001 advisers. Why, because often the over-kill gets put in to ensure the company and therefore their position does not fail an assessment. If I was advising you I would be asking you what you actually did It boils down to... (Score:1) 1) say what you do 2) do what you say 3) be able to repeat the process 4) be able to prove it (audit trails) This goes for CMM/SEI also.
http://slashdot.org/story/06/07/26/2356253/light-weight-software-process-for-iso-9000
CC-MAIN-2015-48
refinedweb
3,147
69.52
In lesson 4.4b -- An introduction to std::string, we defined a string as a collection of sequential characters, such as “Hello, world!”. Strings are the primary way in which we work with text in C++, and std::string makes working with strings in C++ easy. Modern C++ supports two different types of strings: std::string (as part of the standard library), and C-style strings (natively, as inherited from the C language). It turns out that std::string is implemented using C-style strings. In this lesson, we’ll take a closer look at C-style strings. C-style strings A C-style string is simply an array of characters that uses a null terminator. A null terminator is a special character (‘\0’, ascii code 0) used to indicate the end of the string. More generically, A C-style string is called a null-terminated string. To define a C-style string, simply declare a char array and initialize it with a string literal: Although “string” only has 6 letters, C++ automatically adds a null terminator to the end of the string for us (we don’t need to include it ourselves). Consequently, myString is actually an array of length 7! We can see the evidence of this in the following program, which prints out the length of the string, and then the ASCII values of all of the characters: This produces the result: string has 7 characters. 115 116 114 105 110 103 0 That 0 is the ASCII code of the null terminator that has been appended to the end of the string. When declaring strings in this manner, it is a good idea to use [] and let the compiler calculate the length of the array. That way if you change the string later, you won’t have to manually adjust the array length. One important point to note is that C-style strings follow all the same rules as arrays. This means you can initialize the string upon creation, but you can not assign values to it using the assignment operator after that! Since C-style strings are arrays, you can use the [] operator to change individual characters in the string: This program prints: spring When printing a C-style string, std::cout prints characters until it encounters the null terminator. If you accidentally overwrite the null terminator in a string (e.g. by assigning something to myString[6]), you’ll not only get all the characters in the string, but std::cout will just keep printing everything in adjacent memory slots until it happens to hit a 0! Note that it’s fine if the array is larger than the string it contains: In this case, the string “Alex” will be printed, and std::cout will stop at the null terminator. The rest of the characters in the array are ignored. C-style strings and std::cin There are many cases where we don’t know in advance how long our string is going to be. For example, consider the problem of writing a program where we need to ask the user to enter their name. How long is their name? We don’t know until they enter it! In this case, we can declare an array larger than we need: In the above program, we’ve allocated an array of 255 characters to name, guessing that the user will not enter this many characters. Although this is commonly seen in C/C++ programming, it is poor programming practice, because nothing is stopping the user from entering more than 255 characters (either unintentionally, or maliciously). The recommended way of reading C-style strings using std::cin is as follows: std::cin This call to cin.getline() will read up to 254 characters into name (leaving room for the null terminator!). Any excess characters will be discarded. In this way, we guarantee that we will not overflow the array! Manipulating C-style strings C++ provides many functions to manipulate C-style strings as part of the <cstring> header. Here are a few of the most useful: strcpy() allows you to copy a string to another string. More commonly, this is used to assign a value to a string: However, strcpy() can easily cause array overflows if you’re not careful! In the following program, dest isn’t big enough to hold the entire string, so array overflow results.. Another useful function is the strlen() function, which returns the length of the C-style string (without the null terminator). The above example prints: My name is: Alex Alex has 4 letters. Alex has 20 characters in the array. Note the difference between strlen() and std::size(). strlen() prints the number of characters before the null terminator, whereas std::size (or the sizeof() trick) returns the size of the entire array, regardless of what’s in it. Other useful functions: strcat() -- Appends one string to another (dangerous) strncat() -- Appends one string to another (with buffer length check) strcmp() -- Compare two strings (returns 0 if equal) strncmp() -- Compare two strings up to a specific number of characters (returns 0 if equal) Here’s an example program using some of the concepts in this lesson: Note that we put strlen(buffer) outside the loop so that the string length is only calculated once, not every time the loop condition is checked. strlen(buffer) Don’t use C-style strings It is important to know about C-style strings because they are used in a lot of code. However, now that we’ve explained how they work, we’re going to recommend that you avoid them altogether whenever possible! Unless you have a specific, compelling reason to use C-style strings, use std::string (defined in the <string> header) instead. std::string is easier, safer, and more flexible. > C++ provides many functions to manipulate C-style strings as part of the <cstring> library. Shouldn't it be <cstring> header, as there's no such thing as <cstring> library? yes, thanks! Hello Everyone! I use the std::strcat to do some strange thing and get strange result can you help analize the result. strcat is dangrous. when I try strcat the Hello to temp. the temp is a char[5] without any empty space. but I get result I use the clang compiler Apple clang version 11.0.3 (clang-1103.0.32.62) Target: x86_64-apple-darwin19.4.0 this is the code of strcat. The first parameter of `std::strcat` is the destination. You're appending `Hello` to `temp`. I think there is no more space for temp to store the hello. what can strcat do to. maybe the Memroy of temp was free and remalloc. `strcat` doesn't free or allocate anything. There wasn't enough space to append the string, so you're getting undefined behavior. It's the callers responsibility to allocate memory. In line 9, I think there should be a space after "std::cout << "myString". Why character array will end up with NULL terminator \0 and the other arrays like int arrays don't ?? Character arrays aren't zero-terminated by nature. Only the string literals are, because there needs to be a way of knowing when the string ends. When you create a character array from a string literal, all characters are copied into the array, including the zero-terminator. thank you a lot nascardriver #include <iostream> #include <iterator> // for std::size int main() { char name[255]; // declare array large enough to hold 255 characters std::cout << "Enter your name: "; std::cin.getline(name, std::size(name)); std::cout << "You entered: " << name << '\n'; return 0; } how can the line " std::cin.getline(name, std::size(name));" be written in C++11? Without `std::size`, you can get an array's length via Since `name` is an array of `char`, which has size 1, the division has no effect (Because x/1 = x). Thanks, I now understand that it works basically same as the fixed arrays. Hi, is there a reason why we choose the number 255 here? I feel that this has to do with 2 to the power of 8 is 256, so using 255 can lead to some sort of optimization? But why do we choose 255 but not 256? Thanks in advance! There's no particular reason -- a larger array would work just fine. C++ programmers just like numbers that are (2^n) - 1. Hi Alex, thanks for the explanation! >> Because not all compilers support strcpy_s(), strcpy() is a popular alternative -- even though it’s non-standard, and thus not included in a lot of compilers. strcpy() is standard and included in all compilers. May be you had strlcpy() in mind : size_t strlcpy( char *dst, const char *src, size_t siz); This function is an attempt of the BSD people to “fix” strncpy but, in many ways, strlcpy() is worse than strcpy(). This lesson was first published with 'strlcpy()', and then was "corrected" to use "strcpy" instead. Hi, Here I got the right result.. the output was: Copy this! is that still consider an error ? Accessing memory beyond an object invokes undefined behavior. You might get the expected output, you might get garbage, your program might crash, anything can happen. Because not all compilers support strcpy_s(), strlcpy() is a popular alternative. What a nice new std function :) I'm pretty sure you wanted to say "strcpy_s(), strcpy()" Thanks potedleo ;) Lesson updated I have a program that I need to make. It looks for a specific character in a long text and prints how many times it was used. I can check if the program is OK online on the website ( it uses a C++11 / C++14 compiler). The programs works, but I get another problem "Time Limit Exceeded". It takes about a second for the program to run and I need it to be faster. Do you have any idea what could help out? Thanks in advance. Formatted extraction via `operator>>` and `std::strlen` are slow. Your code is unsafe, as `word` will overflow if a word is longer than 20 characters. `operator>>` can be replaced with `read()`, which doesn't do any formatting. `std::strlen` is unnecessary, you know how long your buffer is. You can play around with the buffer size. Larger buffers should be faster. This code should be at least twice as fast as yours. A few minor typos: "An" should be "A": "compiler" should be "compilers": "Because not all compiler support strcpy_s()" "it's" should be "its": "It also has it’s own set of issues." Thanks for a great resource! Typos fixed. Thanks! "Because not all compiler support strcpy_s()..." I do not have strcpy_s (). I thought standard libraries are the same. But it looks like someone add new functionality to a standard library and someone else do not. The C++ standard defines some functions and types that are optional. Implementations with and without those entities are both valid. To guarantee that your code works everywhere, avoid those entities altogether unless you provide alternatives. To be even more confusing ... I have Arch Linux on 64 bit, CodeBlocks (using clang or gcc). If I use CodeBlocks, I can use std::size() (from <iterator> header) with both clang and gcc. If I use the terminal with clang++ or g++, std::size() (from <iterator> header) is not found or something like that. But CodeBlocks use the same clang (or gcc) that is installed on Arch Linux... 0_O You need to tell clang which standard to use Why is sizeof () always the same? On my system 32. sizeof (<some_structure_identifier_here>) gives me the size of that structure in bytes, but this is not the case with std::string objects. `std::string` stores a pointer to the char array, it doesn't store the string directly. You'll understand it by the end of this chapter. This is somehow unexpected for a beginner, because sizeof (arr) (where arr is a fixed array) gives the whole size of the array. Even if arr decays to a pointer. Maybe because it would be almost useless to give the size of a pointer, and more valuable to give the whole size of the array. But then sizeof (std::string) being always the same, it looks like it is also useless. Or maybe don't. So many little details in C++. :) > Even if arr decays to a pointer No. `sizeof(arr)` returns the size of the pointer if the array decayed. `sizeof` is supposed to give you the size of the data type, and that's what it's doing. If you want to know something type-specific, eg. string length, you should use the functions provided by that type (std::string::length). You only need `sizeof` if you're doing operations on the raw data. Use `std::size` for arrays. Is this better? Here strlen () is not called and executed for every iteration. Yes. If the condition is expensive (`std::strlen` has to loop through the string on every call) and doesn't change, you should store it in a temporary. Instead of 'strcpy()', why not just 'source = dest'? You'd copy the pointer, not the string. Pointers are covered in the next few lessons. Hi, I have a quick question. Say I was writing code to play a game of hangman. I'm guessing for that game, I will need to compare every single letter of a word. How would I do this using std::string? Thanks! Use a for-loop. Since you didn't post any code, this is what I suppose you're stuck at I don't want to spoil you, so I'm not posting the rest of the code. If you have another question, feel free to ask. If you just want to see the start of 1 possible implementation without trying yourself, have a look here Hi thanks for responding! I am not really coding that game, it was just an example in my mind. I was wondering how to look at the single letters in a string without c-style strings. And to be honest, I don't get most of your example. I'm guessing std::string::size_type is a special type of string? and if strSolution is the word in std::string type then what is strSolution.length()? is it just the length of that word? Are you jumping letter with ui? Is this material explained later in this tutorial? Chapter 17 is all about `std::string`. (Watch out, it's an old chapter with bad practices). `std::string::size_type` is the type used by `std::string` for indexing. It's some unsigned integer type. `std::string::length` (same as `std::string::size`) returns the length of the string. "Hello" -> 5 "BP" -> 2 ui starts at 0 and goes all the way up to the string's length minus 1. For example, given the string "Hello", ui goes 0, 1, 2, 3, 4. (5 is an invalid index). `std::string`'s individual characters can be accessed just like those of a C-style string, using `str[index]`. So since I still need to learn lot's or stuff before chapter 17, I thought I would just for the fun of it try using C-style strings for hangman. It is a bit ugly, and spaghetti like, but here is my attempt. I hope it is a bit ok... Thanks for all your help! The only place where you used a C-style string is line 63, which is only required for the fixed-size array. Other than that your code is already using `std::string`. You should be able to understand chapter 17, I don't know why Alex decided to wait until the end. Some suggestions: - Limit your lines to 80 characters in length for better readability on small displays. - Line 19+: I don't think char extraction can fail. - Line 69: That `false` doesn't do anything. The entire array is initialized to `false` by using empty curly brackets. - Line 98 has no effect. `lettersGuessed` isn't used after here. - You could remove the "word"/"letter" test by always reading a string and checking its length. If it's 1, you run the letter code. If it's > 1, you run the word code. How would I check the length of a array if it's size should be fixed? It doesn't matter what I put in the machine the size is fixed. I guess this can be solved by using non fixed arrays? I'll probably see those in a few chapters. Thanks again for your pointers! `std::string` is dynamic, ie. it's length is not known at compile-time, so you'd have to use a dynamically allocated array (Covered later in this chapter). The core lessons of this tutorial are focused on broad understanding. Originally, the lessons at the end were going to be a deeper dive into some of the more common classes of the standard library -- but I didn't get far in that approach. #include <iostream> int main() { char name[2]; // declare array large enough to hold 255 characters std::cout << "Enter your name: ";//mangesh std::cin.getline(name, 3); std::cout << "You entered: " << name << '\n'; Thank you so much for this wonderful tutorial! I finally feel I can learn c++! My question is the following: I wanted to change the value of one element of the string as: char ss[] = "feast"; ss[0] = "b"; std::cout << ss; which gives me the error: invalid conversion from 'const char*' to 'char' [-fpermissive]| but when I switch it to: ss[0] = 'b'; everything compiles fine. Why? "b" is a char array (const char *) 'b' is a char (char) ss[0] is a char You can't assign a char array to a char. Hello and good morning, why does an array outputs its address when we're using array(itself, without braces), and @string which is C-style string does not ?! Skim below to understand. Arrays decay into pointers. @std::cout<< treats char pointers as strings. So the difference between C-style strings and arrays is that @std::cout treats them different, ok? And they all are arrays with different type. Right ?! right I have a question. How come when you overflow the array (the example with strcpy()), it still prints out the array as it should (I can print out the string in the dest same as in the source)? The length of the dest (strlen) after copying is equal to the actual length of the dest + the length of the string that was copied, but the sizeof dest still returns declared length of the string. Is this dependent on the machine and/or the compiler? (Windows 7x64 and Code::Blocks 17.12) Does the compiler allocate the array dynamically? Also, what happens with the strlen, why is it the original length + lenght of the copied string, not just the length of the copied string OR the original length? Thank you for your time @std::strcpy doesn't check bounds, it copies as much as you tell it to. If you tell it to write to memory you're not supposed to access, behavior is undefined. @sizeof returns the length you declared the array with, it can't change at run-time. @std::strlen loops through the string until it finds the 0-terminator. Again, without bounds checks, if it accesses memory after the reserved length, behavior is undefined. Oh, ok, so if I got it right, it is a matter of pure luck if the program will output what we gave it if we write out of bounds? Like, if some other program overwrites the memory we accesed by going out of bounds, and wrote over the /0 terminator, the program will keep outputing random garbage, untill it, by chance, finds first /0 terminator? Thanks for the answer :) > some other program overwrites the memory we accesed That can't happen, at least not on the major OSs. But other variables or code in your program could conflict with the memory you're trying to access. @std::cout prints everything until it finds the 0-terminator, or your program crashes, because it's accessing memory which it's not allowed to access, whichever comes first. Thanks for clearing that up When I try to convert std::size(array) into an integer type, vb gives me an error and says that in order to convert from 'size_t' to' int' I need to do a narrowing conversion. However in your code you did not have to do a narrowing conversion. I changed my c++ version to c++17, and also tried changing it to the latest update, but the error message still came up. Could anyone please explain this to me? Thanks Use a @static_cast. Narrowing conversions usually cause a warning, you probably set your compiler up to treat warnings as errors (This is a good thing). Hello, can you please help me with this code: The problem is, when I read the string from the file, it repeats a character at the end. e.g. If I store "welcome" in the file, it prints "welcomee" on the screen although the file contains the string "welcome". * Line 8, 9, 12, 22: Initialize your variables with brace initializers. * Line 23: Booleans are false/true. * Line 14-19: Should be a for-loop. * Don't use "using namespace". * Missing printed trailing line feed. * Line 18: Use ++prefix unless you need postfix++. * Magic number: 80. Use @std::size. You're not writing a null-terminator to the file. Ok thanks Nascar! What I wonder now is this... Is there a way to convert a C-string into a std::string and vice versa.... Like this pseudo code: I'm not sure if I would ever actually need this, but just in case ;) std:: why its important ?? The first line only supports C style string variable as its first argument. The second line only supports string variable as its second argument. Are the getline functions same in both lines. I am confused with it. Hi Piyush! They're not the same, but they behave the same, use whichever you prefer, the second is easier to use since you don't need to know the length beforehand. Thanks for the reply Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/66-c-style-strings/
CC-MAIN-2020-29
refinedweb
3,736
73.88
PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) + Embedding Perl under Win32 perl v5.8.8 2006-06-30 1 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) Compiling your C program If you have trouble compiling the scripts in this documenta- tion, you're not alone. The cardinal rule: COMPILE THE PRO- GRAMS copy- ing the lib directory.) When you use Perl from C, your C program will-- usually--allocate, "run", and deallocate a PerlInterpreter object, which is defined by the perl library. If your copy of Perl is recent enough to contain this docu- mentation old 5.003_05, the incantation is a bit different: perl v5.8.8 2006-06-30 2 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) % fol- lowing dis- tribution,- ding Perl (the language), so I'll demonstrate embedding with miniperlmain.c, included in the source distribution. Here's a bastardized, nonportable version of miniperlmain.c con- taining the essentials of embedding: perl v5.8.8 2006-06-30 3 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) #include <EXTERN.h> /* from the Perl distribution */ #include <perl.h> /* from the Perl distribution */ static PerlInterpreter *my_perl; /*** The Perl interpreter ***/. perl v5.8.8 2006-06-30 4 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) Calling a Perl subroutine from your C program To call individual Perl subroutines, you can use any of the call_* functions documented in perlcall. In this example we'll use "call_argv". That's shown below, in a program I'll call showtime.c. #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; int main(int argc, char **argv, char **env) { char *args[] = { NULL }; PERL_SYS_INIT3(&argc,&argv,&env); my_perl = perl_alloc(); perl_construct(my_perl); perl_parse(my_perl, NULL, argc, argv, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; /*** skipping perl_run() ***/ call_argv("showtime", G_DISCARD | G_NOARGS, args); perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); } perl v5.8.8 2006-06-30 5 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) yielding the number of seconds that elapsed between January 1, 1970 (the beginning of the Unix epoch), and the moment I began writing this sentence. In this particular case we don't have to call perl_run, as we set the PL_exit_flag PERL_EXIT_DESTRUCT_END which exe- cutes END blocks in perl_destruct. If you want to pass arguments to the Perl subroutine, you can add strings to the "NULL"-terminated "args" list passed to call_argv. For other data types, or to examine return values, you'll need to manipulate the Perl stack. That's demonstrated in "Fiddling with the Perl stack from your C program". Evaluating a Perl statement from your C program Perl provides two API functions to evaluate pieces of Perl code. These are "eval_sv" in perlapi and "eval_pv" in per- lapi. Arguably, these are the only routines you'll ever need to execute snippets of Perl code from within your C program. Your code can be as long as you wish; it can contain multi- ple statements; it can employ "use" in perlfunc, "require" in perlfunc, and "do" in perlfunc to include external Perl files.) { STRLEN n_a; char *embedding[] = { "", "-e", "0" }; PERL_SYS_INIT3(&argc,&argv,&env); my_perl = perl_alloc(); perl_construct( my_perl ); perl_parse(my_perl, NULL, 3, embedding, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_run(my_perl); perl v5.8.8 2006-06-30 6 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) /** Treat $a as an integer **/ eval_pv("$a = 3; $a **= 2", TRUE); printf("a = %d\n", SvIV(get_sv("a", FALSE))); /** Treat $a as a float **/ eval_pv("$a = 3.14; $a **= 2", TRUE); printf("a = %f\n", SvNV(get_sv("a", FALSE))); /** Treat $a as a string **/ eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE); printf("a = %s\n", SvPV(get_sv("a", FALSE), n_a)); perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); } All of those strange functions with sv in their names help convert Perl scalars to C types. They're described in perl- guts and perlapi. expres- sion. It is also possible and in most cases a better stra- tegy to fetch the return value from eval_pv() instead. Example: ... STRLEN n_a; SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE); printf("%s\n", SvPV(val,n_a)); ... This way, we avoid namespace pollution by not creating glo- bal variables and we've simplified our code as well. Performing Perl pattern matches and substitutions from your C program The eval_sv() function lets us evaluate strings of Perl code, so we can define some functions that use it to "spe- cialize" in matches and substitutions: match(), substi- tute(), and matches(). perl v5.8.8 2006-06-30 7 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) I32 "SV" as according to the operation, returning the number of substitutions made. int matches(SV *string, char *pattern, AV **matches); Given an "SV", a pattern, and a pointer to an empty "AV", matches() evaluates "$string =~ $pattern" in a list context, and fills in matches with the array elements, returning the number of matches found. Here's a sample program, match.c, that uses all three (long lines have been wrapped here): #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; /** my_eval_sv(code, error_check) ** kinda like eval_sv(), ** but we pop the return value off the stack **/ SV* my_eval_sv(SV *sv, I32 croak_on_error) { dSP; SV* retval; STRLEN n_a; PUSHMARK(SP); eval_sv(sv, G_SCALAR); SPAGAIN; retval = POPs; PUTBACK; if (croak_on_error && SvTRUE(ERRSV)) croak(SvPVx(ERRSV, n_a)); return retval; } perl v5.8.8 2006-06-30 8 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) /** match(string, pattern) ** ** Used for matches in a scalar context. ** ** Returns 1 if the match was successful; 0 otherwise. **/ I32 match(SV *string, char *pattern) { SV *command = NEWSV(1099, 0), *retval; STRLEN n_a; sv_setpvf(command, "my $string = '%s'; $string =~ %s", SvPV(string,n_a), pattern); retval = my(1099, 0), *retval; STRLEN n_a; sv_setpvf(command, "$string = '%s'; ($string =~ %s)", SvPV(*string,n_a), pattern); retval = my_eval_sv(command, TRUE); SvREFCNT_dec(command); *string = get_sv("string", FALSE); return SvIV(retval); } /** matches(string, pattern, matches) ** ** Used for matches in a list context. ** ** Returns the number of matches, ** and fills in **matches with the matching substrings **/ perl v5.8.8 2006-06-30 9 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) I32 matches(SV *string, char *pattern, AV **match_list) { SV *command = NEWSV(1099, 0); I32 num_matches; STRLEN n_a; sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)", SvPV(string,n_a), pattern); my_eval_sv(command, TRUE); SvREFCNT_dec(command); *match_list = get_av("array", FALSE); num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/ return num_matches; } main (int argc, char **argv, char **env) { char *embedding[] = { "", "-e", "0" }; AV *match_list; I32 num_matches, i; SV *text; STRLEN n_a; PERL_SYS_INIT3(&argc,&argv,&env); my_perl = perl_alloc(); perl_construct(my_perl); perl_parse(my_perl, NULL, 3, embedding, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; text = NEWSV(1099,0);"); perl v5.8.8 2006-06-30 10 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED),n_a)); printf("\n"); /** Remove all vowels from text **/ num_matches = substitute(&text, "s/[aeiou]//gi"); if (num_matches) { printf("substitute: s/[aeiou]//gi...%d substitutions made.\n", num_matches); printf("Now text is: %s\n\n", SvPV(text,n_a)); } /** Attempt a substitution **/ if (!substitute(&text, "s/Perl/C/")) { printf("substitute: s/Perl/C...No substitution made.\n\n"); } SvREFCNT_dec(text); PL_perl_destruct_level = 1; perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); } perl v5.8.8 2006-06-30 11 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) substitute: s/Perl/C...No substitution made. Fiddling with the Perl stack from your C program When trying to explain stacks, most computer science text- books and per- lapi. Then you'll need to know how to manipulate the Perl stack. That's described in perlcall. Once you've understood those, embedding Perl in C is easy. Because C has no builtin function for integer exponentia- tion, let's make Perl's ** operator available to it (this is less useful than it sounds, because Perl implements ** with C's pow() function). First I'll create a stub exponentia- tion function in power.pl: sub expo { my ($a, $b) = @_; return $a ** $b; } Now I'll create a C program, power.c, with a function Perl- Power() that contains all the perlguts necessary to push the two arguments into expo() and to pop the return value out. Take a deep breath... #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; perl v5.8.8 2006-06-30 12 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1)" }; PERL_SYS_INIT3(&argc,&argv,&env); my_perl = perl_alloc(); perl_construct( my_perl ); perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_run(my_perl); PerlPower(3, 4); /*** Compute 3 ** 4 ***/ perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); }. perl v5.8.8 2006-06-30 13 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) occasion- ally "call_argv" in perlapi,OAD"ed sub- routines; our %Cache; use Symbol qw(delete_package); sub valid_package_name { my($string) = @_; $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg; # second pass only for words starting with a digit $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg; perl v5.8.8 2006-06-30 14 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) # Dress it up as a real package name $string =~ s|/|::|g; return "Embed" . $string; }__ perl v5.8.8 2006-06-30 15 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) /* persistent.c */ #include <EXTERN.h> #include <perl.h> /* 1 = clean out filename's symbol table after each request, 0 = don't */ #ifndef DO_CLEAN #define DO_CLEAN 0 #endif #define BUFFER_SIZE 1024 static PerlInterpreter *my_perl = NULL; int main(int argc, char **argv, char **env) { char *embedding[] = { "", "persistent.pl" }; char *args[] = { "", DO_CLEAN, NULL }; char filename[BUFFER_SIZE]; int exitstatus = 0; STRLEN n_a; PERL_SYS_INIT3(&argc,&argv,&env); if((my_perl = perl_alloc()) == NULL) { fprintf(stderr, "no memory!"); exit(1); } perl_construct(my_perl); exitstatus = perl_parse(my_perl, NULL, 2, embedding, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; if(!exitstatus) { exitstatus = perl_run(my_perl); while(printf("Enter file name: ") && fgets(filename, BUFFER_SIZE, stdin)) { filename[strlen(filename)-1] = '\0'; /* strip \n */ /* call the subroutine, passing it the filename as an argument */ args[0] = filename; call_argv("Embed::Persistent::eval_file", G_DISCARD | G_EVAL, args); /* check $@ */ if(SvTRUE(ERRSV)) fprintf(stderr, "eval error: %s\n", SvPV(ERRSV,n_a)); } } perl v5.8.8 2006-06-30 16 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) PL_perl_destruct_level = 0; perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); exit(exitstatus); } Now compile: % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts` Here's an example script file: #test.pl my $string = "hello"; foo($string); sub foo { print "foo says: @_\n"; } Now run: % persistent Enter file name: test.pl foo says: hello Enter file name: test.pl already compiled Embed::test_2epl->handler foo says: hello Enter file name: ^C Execution of END blocks Traditionally END blocks have been executed at the end of the perl_run. This causes problems for applications that never call perl_run. Since perl 5.7.2 you can specify "PL_exit_flags |= PERL_EXIT_DESTRUCT_END" to get the new behaviour. This also enables the running of END blocks if the perl_parse fails and "perl_destruct" will return the exit value., when perl is not built with any special options, the global variable "PL_perl_destruct_level" is set to 0, since extra perl v5.8.8 2006-06-30 17 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) cleaning isn't usually needed when a program only ever creates a single interpreter in its entire lifetime. Setting "PL_perl_destruct_level" to 1 makes everything squeaky clean: while(1) { ... /* reset global variables here with PL_perl_destruct_level = 1 */ PL_perl_destruct_level = 1; perl_construct(my_perl); ... /* clean and reset _everything_ during perl_destruct */ PL_perl_destruct_level = 1; perl_destruct(my_perl); perl_free(my_perl); ... /* let's go do it again! */ } When perl_destruct() is called, the interpreter's syntax parse tree and symbol tables are cleaned up, and global variables are reset. The second assignment to "PL_perl_destruct_level" is needed because perl_construct resets it to 0. Now suppose we have more than one interpreter instance run- ning at the same time. This is feasible, but only if you used the Configure option "-Dusemultiplicity" or the options "-Dusethreads -Duseithreads" when building perl. By default, enabling one of these Configure options sets the per-interpreter global variable "PL_perl_destruct_level" to 1, so that thorough cleaning is automatic and interpreter variables are initialized correctly. Even if you don't intend to run two or more interpreters at the same time, but to run them sequentially, like in the above example, it is recommended to build perl with the "-Dusemultiplicity" option otherwise some interpreter variables may not be ini- tialized correctly between consecutive runs and your appli- cation may crash. Using "-Dusethreads -Duseithreads" rather than "-Dusemulti- plicity" is more appropriate if you intend to run multiple interpreters concurrently in different threads, because it enables support for linking in the thread libraries of your system with the interpreter. Let's give it a try: #include <EXTERN.h> #include <perl.h> perl v5.8.8 2006-06-30 18 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) /* we're going to embed two interpreters */ /* we're going to embed two interpreters */ #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)" int main(int argc, char **argv, char **env) { PerlInterpreter *one_perl, *two_perl; char *one_args[] = { "one_perl", SAY_HELLO }; char *two_args[] = { "two_perl", SAY_HELLO }; PERL_SYS_INIT3(&argc,&argv,&env); one_perl = perl_alloc(); two_perl = perl_alloc(); PERL_SET_CONTEXT(one_perl); perl_construct(one_perl); PERL_SET_CONTEXT(two_perl); perl_construct(two_perl); PERL_SET_CONTEXT(one_perl); perl_parse(one_perl, NULL, 3, one_args, (char **)NULL); PERL_SET_CONTEXT(two_perl); perl_parse(two_perl, NULL, 3, two_args, (char **)NULL); PERL_SET_CONTEXT(one_perl); perl_run(one_perl); PERL_SET_CONTEXT(two_perl); perl_run(two_perl); PERL_SET_CONTEXT(one_perl); perl_destruct(one_perl); PERL_SET_CONTEXT(two_perl); perl_destruct(two_perl); PERL_SET_CONTEXT(one_perl); perl_free(one_perl); PERL_SET_CONTEXT(two_perl); perl_free(two_perl); PERL_SYS_TERM(); } Note the calls to PERL_SET_CONTEXT(). These are necessary to initialize the global state that tracks which interpreter is the "current" one on the particular process or thread that may be running it. It should always be used if you have more than one interpreter and are making perl API calls on both interpreters in an interleaved fashion. PERL_SET_CONTEXT(interp) should also be called whenever "interp" is used by a thread that did not create it (using either perl_alloc(), or the more esoteric perl_clone()). perl v5.8.8 2006-06-30 19 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1): static void xs_init (pTHX); EXTERN_C void boot_DynaLoader (pTHX_ CV* cv); EXTERN_C void boot_Socket (pTHX_ CV* cv); EXTERN_C void xs_init(pTHX) { char *file = __FILE__; /* DynaLoader is a special case */ newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); newXS("Socket::bootstrap", boot_Socket, file); } Simply put: for each extension linked with your Perl execut- able (determined during its initial configuration on your computer or when adding a new extension), a Perl subroutine perl v5.8.8 2006-06-30 20 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) is created to incorporate the extension's routines. Nor- mally,, perlguts, and perlapi for more details. In general, all of the source code shown here should work unmodified under Windows. However, there are some caveats about the command-line exam- ples shown. For starters, backticks won't work under the Win32 native command shell. The ExtUtils::Embed kit on CPAN ships with a script called genmake, which generates a simple makefile to build a program from a single C source file. It can be used like this: C:\ExtUtils-Embed\eg> perl genmake interp.c C:\ExtUtils-Embed\eg> nmake C:\ExtUtils-Embed\eg> interp -e "print qq{I'm embedded in Win32!\n}" perl v5.8.8 2006-06-30 21 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) You may wish to use a more robust environment such as the Microsoft Developer Studio. In this case, run this to gen- erate perlxsi.c: perl -MExtUtils::Embed -e xsinit Create a new project and. Finally, select Build -> Build interp.exe and you're ready to go. If you completely hide the short forms forms of the Perl public API, add -DPERL_NO_SHORT_NAMES to the compilation flags. This means that for example instead of writing warn("%d bottles of beer on the wall", bottlecount); you will have to write the explicit full form Perl_warn(aTHX_ "%d bottles of beer on the wall", bottlecount); (See "Background and PERL_IMPLICIT_CONTEXT for the explana- tion of the "aTHX_"." in perlguts ) Hiding the short forms is very useful for avoiding all sorts of nasty (C preproces- sor or otherwise) conflicts with other software packages (Perl defines about 2400 APIs with these short names, take or leave few hundred, so there certainly is room for con- flict.) You can sometimes write faster code in C, but you can always write code faster in Perl. Because you can use each from the other, combine them as you wish. Jon Orwant <orwant@media.mit.edu> and Doug MacEachern <dougm@covalent.net>, with small contributions from Tim Bunce, Tom Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya Zakharevich. Doug MacEachern has an article on embedding in Volume 1, Issue 4 of The Perl Journal ( ). Doug is also the developer of the most widely-used Perl embed- ding: the mod_perl system (perl.apache.org), which embeds Perl in the Apache web server. Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl have used this perl v5.8.8 2006-06-30 22 PERLEMBED(1) Perl Programmers Reference Guide PERLEMBED(1) model for Oracle, Netscape and Internet Information Server Perl plugins. Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant. All Rights Reserved. Permission is granted to make and distribute verbatim copies of this documentation provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified ver- sions of this documentation under the conditions for verba- tim. perl v5.8.8 2006-06-30 23.
http://www.mirbsd.org/htman/sparc/man1/perlembed.htm
CC-MAIN-2014-10
refinedweb
2,882
53.51
Hello, I've another problem with project 14. The color sometimes changes very slowly or somtimes it doesn't change at all. It's the same with the numbers in the black field in processing. I've look at the poti's values at a arduino programm and it works. They change very fast. I think the code is right because I've tested it with the from the arduino software, too. There's the same problem. Can anyone help me? I have downloaded the last version of processing (2.0b7), but executing the processing code I receive the "serial does not run in 64-bit mode" (I use Windows 7 x64), any solution? I know this is an issue. We all very much want a 64-bit serial library.I don't have time to make and test one across all the necessary platforms.We hope that someone will soon.It is marked as an "enhancement" because we have never had a 64-bit library. Calling it a major bug won't change the fact that I don't have time to fix it right now.For the time being, comment #5 explains a workaround."comment #5: On Linux and Windows, download the 32-bit version of Processing. " void loop() { // read the value of A0, divide by 4 and // send it as a byte over the serial connection Serial.write(analogRead(A0)/4); delay(100);} Hello.I downloaded the 32-bit version but I still can't compile. I get the same error that I got on the 64-bit version, "serial is only compatibl wit the 32-bit download of Processing.".Someone pls help! import processing.serial.*;Serial myPort;PImage logo;int bgcolor = 0;void setup() { colorMode(HSB, 255); logo = loadImage(""); size(logo.width, logo.height); println("Avilable serial ports"); println(Serial.list()); myPort = new Serial(this, Serial.list()[1], 9600); // parameters : which application, which port & what speed}void draw() { if (myPort.available() > 0) { // if(there is something in the buffer) bgcolor = myPort.read(); print(" "); println(myPort.read()); println(bgcolor); } background(bgcolor, 255, 255); // hue, brightness, saturation. max value 255 image(logo, 0, 0); // image() is used to draw. --- what to draw , x-coordiante to start, y-coordiante to start ---} As for the color changing rate problems you are seeing, it appears to be a serial buffering issue. The Arduino is sending reading sample updates too fast for Processing to keep up with. I don't know why they made the Arduino code sample that fast (1 millisecond delay is about 1000 samples per second), it's not really necessary.But here is a quick fix workaround to this. Change the sample delay from 1 millisecond to 100 milliseconds. This should slow down the Arduino sampling slow enough for Processing to keep up with.Try this:Code: [Select]void loop() { // read the value of A0, divide by 4 and // send it as a byte over the serial connection Serial.write(analogRead(A0)/4); delay(100);} if ( myPort.available() > 0) { // read the value and store it in a variable bgcolor = myPort.read(); myPort.clear(); // print the value to the status window println(bgcolor); } Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=142311.msg1294333
CC-MAIN-2016-18
refinedweb
559
68.47
Managing multiple balls collisions with Flash: AS3 version Filed Under Actionscript 3, Flash, Tutorials, Users contributions • 20 Comments Some days ago Sunil Changrani sent me a the script to manage multiple balls collisions with Flash, in AS2. Now, it's time for Andrew Cook to give us the AS3 version. Hi Emanuele, I've been coming to your blog for over a year now. I am doing a new game with Ball vs. Ball collision and turn to your tutorials for help. I am programming my game in AS3, so I reprogrammed the tutorial in AS3. I thought you might want to check it out. There are three files. The main .fla, a document class, and a Ball class. Thank you for starting your great blog that helps developers like me all the time. I really appreciate the way you give back to the development community. Keep it up! This is the script to solve collisions: - package - { - import flash.display.MovieClip; - import flash.display.Stage; - import flash.events.Event; - import flash.events.KeyboardEvent; - public class BallCollision extends MovieClip - { - private var mcBallContainer:MovieClip; - private var nNumBalls:Number = 15; - private var nStageWidth:Number = 500; - private var nStageHeight:Number = 400; - public function BallCollision ( ) : void - { - mcBallContainer = new MovieClip ( ) ; - mcBallContainer.x = mcBallContainer.y = 0; - stage.addChild(mcBallContainer); - this.addEventListener ( Event.ENTER_FRAME, enterFrameHandler ); - for ( var i = 0; i <nNumBalls; i++ ) - { - var mcBall:Ball = new Ball ( Math.floor ( ( Math.random() * 12 ) - 4 ), Math.floor ( ( Math.random() * 12 ) - 4 ) ); - mcBall.x = Math.random() * nStageWidth; - mcBall.y = Math.random() * nStageHeight; - mcBallContainer.addChild ( mcBall ); - } - } - private function enterFrameHandler ( E:Event ) : void - { - for ( var i = 0; i <mcBallContainer.numChildren; i++ ) - { - var mcBall1:* = mcBallContainer.getChildAt( i ); - for ( var j = i + 1; j <mcBallContainer.numChildren; j++ ) - { - var mcBall2:* = mcBallContainer.getChildAt( j ); - var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x ); - var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y ); - var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY ); - if ( nDistance <20 ) - { - solveBalls ( mcBall1, mcBall2 ); - } - } - } - } - private function solveBalls ( MCBallA:MovieClip, MCBallB:MovieClip ) : void - { - var nX1:Number = MCBallA.x; - var nY1:Number = MCBallA.y; - var nDistX:Number = MCBallB.x - nX1; - var nDistY:Number = MCBallB.y - nY1; - var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY ); - var nRadiusA:Number = MCBallA.width/2; - var nRadiusB:Number = MCBallB.width/2; - //var nRadius:Number = 10; - var nNormalX:Number = nDistX/nDistance; - var nNormalY:Number = nDistY/nDistance; - var nMidpointX:Number = ( nX1 + MCBallB.x )/2; - var nMidpointY:Number = ( nY1 + MCBallB.y )/2; - MCBallA.x = nMidpointX - nNormalX * nRadiusA; - MCBallA.y = nMidpointY - nNormalY * nRadiusA; - MCBallB.x = nMidpointX + nNormalX * nRadiusB; - MCBallB.y = nMidpointY + nNormalY * nRadiusB; - var nVector:Number = ( ( MCBallA.nSpeedX - MCBallB.nSpeedX ) * nNormalX )+ ( ( MCBallA.nSpeedY - MCBallB.nSpeedY ) * nNormalY ); - var nVelX:Number = nVector * nNormalX; - var nVelY:Number = nVector * nNormalY; - MCBallA.nSpeedX -= nVelX; - MCBallA.nSpeedY -= nVelY; - MCBallB.nSpeedX += nVelX; - MCBallB.nSpeedY += nVelY; - } - } - } And this is the one to manage balls - package - { - import flash.events.Event; - import flash.display.MovieClip; - public class Ball extends MovieClip - { - public var nSpeedX:Number; - public var nSpeedY:Number; - private var nStageWidth:Number = 500; - private var nStageHeight:Number = 400; - public function Ball ( NSpeedX:Number, NSpeedY:Number ) : void - { - nSpeedX = NSpeedX; - nSpeedY = NSpeedY; - this.addEventListener ( Event.ENTER_FRAME, onEnterFrameHandler ); - } - private function onEnterFrameHandler ( E:Event ) : void - { - this.x -= nSpeedX; - this.y -= nSpeedY; - if ( this.x>= nStageWidth - 10 ) - { - this.x = nStageWidth - 10; - nSpeedX *= -1; - } - else if ( this.x <= 10 ) - { - this.x = 10; - nSpeedX *= -1; - } - if ( this.y>= nStageHeight - 10 ) - { - this.y = nStageHeight - 10; - nSpeedY *= -1; - } - else if ( this.y <= 10 ) - { - this.y = 10; - nSpeedY *= -1; - } - } - } - } Enjoy the result And download the source code They can be easily customized to meet the unique requirements of your project. 20 Responses to “Managing multiple balls collisions with Flash: AS3 version” Trackbacks - Adobe Flash CS3- AS3 and AS2 game tutorials roundup | Lemlinh.com on August 19th, 2008 6:36 pm [...]) How many balls can this handle before it lags? Nice post! I was able to get to a 1500 ball count before I saw a major chuck of lag. :) AS3 is no joke and it is only getting better :) Thats quite a leap from the 300 we saw in AS2 I have CS3 and I think I will take the leap to AS3 after today! How would u make an angle that the ball would hit? like a ball hitting an angled wall. | | O – - -/ okay the lines didnt work out well lol. lets try this again. …..| …..| …..| O—-/ where the dashes are the balls old places. Balls are touching. Gay :P change var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY ); if ( nDistance <20 ) { to var nDistanceSqr:Number = (nDistX * nDistX) + (nDistY * nDistY); if ( nDistanceSqr <400 ) { for extra speed. Additionally, There is no need to take the absolute value of nDistX and nDistY in these lines… var nDistX:Number = Math.abs ( mcBall1.x – mcBall2.x ); var nDistY:Number = Math.abs ( mcBall1.y – mcBall2.y ); Once you square them it doesn’t matter if they are negative or not. Shouldn’t be a huge boost but every little bit helps. Also, while we are optimizing there is no need really to declare nDistX and nDistY explicitly but I can see why it would be helpful for the tutorial. Great work!! Any thoughts on what happens if a ball has simultanious collisions from both sides? AKA Newtons cradle? Does anyone know how to add the functionality of being able to grab, hold and throw these balls? This is a great effort btw. does anyone know how the collisionBall cobject is created? i cant see it anywhere. u say 1500???? it laggs with me with 300 balls 150 balls is ok on my pc. Hey Emanuele, I’m just started using AS3. I’m creating a game where you drive a bumper car, there’s two variables, speed and rotate. Is there way you can make a realistic bounce off the walls. Thanx Andrew, this is great, *however* you have not commented your code, in particular your physics (use of the dot product etc.) so you are assuming everyone knows what this does. I ranked this 4 out of 5, it is otherwise a superbly well structured and relatively fast rehash on the bouncy ball theme. yes some explanation of the physics would be greatly appreciated… anyone want to take a stab at it… maybe I’ll try. hey,i used this code in my own game. and stumbled upon a problem. when you increase the balldiameter, then they wotn bounce anymore, they just stik to eachother and shake like hell. on balldiameter of 30 they sometimes get knocked out of this stickiness, but when made the ball diameter 40 they just stick to 1 bick chunk, and shake. im talking about this: if ( nDistance <20 ) {solveBalls ( mcBall1, mcBall2 );} if made the 20 into 30 or 40, this happens I wanted to, instead of a variable boundary, add walls. I’ve tried swapping the edge detection script in ball.as with “this.hitTestObject(wall)” (I have a non-dynamic movieclip on the stage instanced as wall) but the ball ignores it and goes straight through. help appreciated. Anyone care to help explain this definition ? var mcBall1:* = mcBallContainer.getChildAt( i ); especially the * . Do we mean McBall1 is of type object and we don’t care which type at this point ? Thanks in advance If I remember correctly, mcBall1:* means that mcBall1 is of type undefined, so yes, it can be any type.
http://www.emanueleferonato.com/2008/06/07/managing-multiple-balls-collisions-with-flash-as3-version/
crawl-002
refinedweb
1,212
69.89
MVC is the next step in the ASP.NET Web application developments. Here we will discuss in brief about this Web Development framework. MVC is the next step in the ASP.NET Web application developments. Here we will discuss in brief about this Web Development framework.ASP. NET MVCMVC is a lightweight web application framework. There are two frameworks currently offered by Microsoft; they are ASP.NET Web forms and ASP.NET MVC. ASP.NET includes the common set of libraries and other features that both the frameworks work on top of. ASP.NET MVC removes many of the weaknesses encountered in the ASP.NET Web forms. One such drawback or weakness of ASP.NET Web forms is the complex markup that is generated for the server controls. Developers have no control over the markup generated for the server controls, which makes working with JavaScript difficult. Another advantage offered by MVC is that the URLs are more user friendly then in traditional Web Forms.MVC stands for Mode View Controler. It is a User Interface design pattern that separates the responsibilities between Input/Output, Flow of control and Data that is passed between the View and Controller. So a view object handles display and input/output, the controller handles flow of control and model represents the data that is passed between the two.ASP.NET MVC is based on this design pattern.Let's first understand how the request is processed by ASP.NET MVC. Figure 1: Flow in ASP.NET MVC ApplicationWhen we make a request using an URL then that request first goes to the controller. The controller fetches the data from the model and updates the view. View is an aspx page that contains HTML and some server side code.Controllers are composed of various actions which execute depending upon the URL.[HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Test View"; return View(); }Index() is the action here which is also the default action. In this code ViewData represents the dictionary that is accessible to the view. View() renders the view to the response.Index is the default Action that is executed if the user doesen't specify a specific URL for action. In the above code since view method is called without any parameters it will return a view that matches the action; here it is Index. In this case the application will look for the view in View/Home/Index.aspx. This is the convention used in MVC i.e views are stored in a directory named after the controller.View is an aspx file that contains just the HTML markup and some controller helper functions. In the view we use the <%= %> tag to execute the server side code that renders HTML; this is quite common in ASP.The request comes to aspnet_isapi dll through the IIS which passes the request to our application. The applicaton request arrives first at the global.asax where the RegisterRoutes method is called which maps the URL string with the action in the controller handling the request.The following is the code that extracts from the RegisterRoutes method: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }The search pattern is /{controller}/{action}/{id}?{querystring}. For example maps to Controller=HomeController and Action=Index in the HomeController. We could achieve this in the ASP.NET webforms also but this is the default in ASP.NET MVC.Figure 2: Default Folder Structure The above is the default folder structure for an ASP.NET MVC application. Models - Holds all the model classes Views - Holds Subdirectory for each controller. In the above image you can see that there is one more project in the solution. MVC has been designed with one important design goal and that is testability. The project that Visual Studio adds by default is based on the NUnit framework but we can use other testing frameworks as well like mbUnit and xUnit. An important thing to remember is that MVC is stateless since it doesn't use the viewstate as in ASP.NET web forms. This makes the framework light as the viewstate is not passed back and forth with each request. View All View All
https://www.c-sharpcorner.com/uploadfile/ashish_2008/mvc-framework-in-net/
CC-MAIN-2021-43
refinedweb
710
67.65
I want to integrate Firebase analytic with the Xamarin.Form application so I wanted to know Firebase analytics support for Xamarin.forms? How can I integrate with it? Answers Yes, it does, but you need to handle the logic in each project. So basically: 1. Add Firebase Analytics nuget package to each platform project (you don't need it in the Forms project) 2. Follow the instructions for each platform for initializing Firebase. iOS AppDelegate - FinishedLaunching Firebase.Analytics.App.Configure(); Android MainActivity - OnCreate firebaseAnalytics = FirebaseAnalytics.GetInstance(this); @RaymondKelly Then how can I manage the click events happen through the xamarin.forms? You will need to create a dependancy service in each platform. In my case I made a class called Analytics. IOS example: [assembly: Xamarin.Forms.Dependency(typeof(App.iOS.Analytics))] namespace App.iOS { public class Analytics : IAnalytics {.... I then have a function for each type of event I want to log. E.g. 'public void ConnectToServer(Server server) { @RaymondKelly Thanks for your reply hope this will work for me Hi, is there any way to use old Google Analytics Api, becasue I don't see this option anymore on web panel - there is only Firebase. When I add to Xamarin.iOS project the nuget package with Firebase I get those errors: Hi, can you tell me because I'm getting this strange error? Error CS0234: The type or namespace name 'App' does not exist in the namespace 'Firebase.Analytics' (are you missing an assembly reference?) (CS0234) It refers to: Firebase.Analytics.App.Configure(); Here you can see Firebase resources on my project: What do you think is going wrong? Thank you in advance! Well... I solved after 3 minutes from last post. I'm sorry! I don't know why but something changed. Actually "Firebase.Analytics." doesn't longer contain the "App" class. It's now in "Firebase.Core"! I downloaded the sample project from GitHub to try to compile and I saw it. Taking a look to the documentation I see that (now) it's written: I'm quite sure it was in Analytics in the past because I was able to compile the code some months ago. @Tedebus. Your right, "Firebase.Core" working for me. Thank you! I tried to install Firebase.Analytic on IOS project and I got the below error. Do anyone experience the same issue? What would be the solution? Could not install package 'Xamarin.Firebase.Analytics 42.1021.1'. You are trying to install this package into a project that targets 'Xamarin.iOS,Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. KahFaiLok. You are trying to install the android version in iOS. Search for Xamarin iOS firebase Analytics. App.Configuremethod was moved from Firebase.Analyticsnamespace to Firebase.Corenamespace in the mayor release from v3.x to v4.x. Please, import Firebase.Coreto your libraries to use this method. Hi, I am trying to add Firebase to my Xamarin.Forms project. I added the Nuget pacjages to iOS and Droid in my iOS AppDelegate: Firebase.Core.App.Configure(); then I created a class FirebaseAnalytics.cs: but I getting this error: Error CS1519: Invalid token '(' in class, struct, or interface member declaration (CS1519) (ZayedAlKhair.iOS) for this line: Firebase.Analytics.Analytics.LogEvent(EventNamesConstants.Login, parameters); Kindly help.. Thanks You have to remove the braces from the token manually. In my case I do like this token.Trim('<').Trim('>').Replace(" ", ""); Hello @WojciechKulik , I'm experiencing almost the same problem actually. Did you find a solution for that? Hello, check this answer from stackoverflow: This is how i'm using firebase so far without problems. Does it work also for UWP somehow? @Wojciech_Kulik, it works! Thanks! I know this post has been around for a while, but I wanted to first thank you all for the useful answers. I don't mind bumping this since this was the only useful result in google. To add real value though, I had to track this down for documentation. The change that the Firebase.Analytics to Firebase.Core move has this in git's log
https://forums.xamarin.com/discussion/comment/356851
CC-MAIN-2020-40
refinedweb
695
53.58
In the previous blog, we learned about Text-to-Speech Recognition in Python. This time we will learn about Speech Recognition in Python. This will be a major step toward the creation of a voice assistant. Speech Recognition Package is not built into python, so we’re going to install it using the python package installer. Installing Packages There are many voice recognition packages exist on PyPI. Some of them are: 2. assemblyai 4. pocketsphinx 6. watson-developer-cloud 7. witsource – realPython In this blog, we will primarily focus on SpeechRecognition Module. $ pip install SpeechRecognition Bash/Shell This will install the Speech Recognition Package in Python. Now, we can use this package and its function for speech recognition. And can move a step further in our Voice Assistant Creation. The Speech Recognition will use our machine’s microphone to recognize the speech and convert to string. We will have to install PyAudio for this purpose. When we pip install pyaudio, error occurs, so this time we will install pyaudio by downloading and then installing using pipwin. Download PyAudio .whl file from the link. Change the directory to the downloaded file. $ pip install .\PyAudio-0.2.11-cp39-cp39-win_amd64.whl Bash/Shell One more work around is first install pipwin then install pyaudio using pipwin. $ pip install pipwin Bash/Shell $ pipwin install pyaudio Bash/Shell The necessary packages for Speech Recognition have been installed. Now we can code the speech recognition in python. Speech Recognition in Python import speech_recognition as sr recognizer = sr.Recognizer() with sr.Microphone() as source: print("Listening...") recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) try: print("Recognizing...") query = recognizer.recognize_google(audio) except sr.UnknownValueError: print("Could not understand audio") print(query.lower()) Python Let’s understand the code line by line. First of all import speech_recognition library, in this case, we have imported it as an alias as the original name of the import is quite long. Recognizer class in Speech Recognition Library recognizer = sr.Recognizer() Python After importing, the first step is to create an instance of the Recognizer present in the speech_recognition library. Now the recognition variable that contains the speech recognition instance of the Recognizer will be used to call any function in it. Microphone Class with sr.Microphone() as source: Python After the creation of the instance of Recognizer, we access the machine’s Microphone using the speech_recognition library. The code above is the code for the file handling in python. For the microphone instance, we provide an alias i.e the source. Adjust For Ambient Noise recognizer.adjust_for_ambient_noise(source) Python The adjust_for_ambient_noise() function from the recognizer takes the microphone instance as input. This function makes the necessary changes to the settings that allow the speech to be heard in a slightly noisy environment. Save Microphone Input Using Listen() audio = recognizer.listen(source) Python Above code stores the speech in a audio variable. Error Handling in Speech Recognition One thing to keep in mind is that the recognizer might fail sometime to recognize the speech and thus we will have to handle the error. It may happen that the error might affect our microphone so handling error becomes necessary. try: print("Recognizing...") query = recognizer.recognize_google(audio) except sr.UnknownValueError: print("Could not understand audio") print(query.lower()) Python Speech Recognizer API There are many recognizers that the SpeechRecogntion Module ships with. Example: recognize_bing(): Microsoft Bing Speech Recognisers recognize_google(): Google Web Speech Recognizer API recognize_google_cloud(): requires the installation of the google-cloud-speech package recognize_houndify(): Houndify by SoundHound recognize_ibm(): IBM Speech to Text Recognizer recognize_sphinx(): CMU Sphinx – PocketSphinx must be installed recognize_wit(): Wit.ai In the above list of recognizers, only recognize_sphinx() works offline with a Sphinx CMU engine, rest requires internet connection. Here, we will be using the Google Web Speech Recognizer API. recognizer.recognize_google(audio) The recognize_google() function uses the google speech recognizer to recognize the recorded voice. If the recognize_google() function fails to recognize the speech it will throw an UnknownValueError, that we catch in the except block and print the error message to the console. If everything works fine, the recognized speech will be saved in the query variable and printed. This is our simple Python Speech Recognition. Our Next target is to Combine Text-to-Speech and Speech Recognition so that we can give an assistant command and give voice output.
https://hackthedeveloper.com/speech-recognition-python/
CC-MAIN-2021-39
refinedweb
723
50.23
Data visualization is a crucial step in any exploratory data analysis or report. It’s usually easy to read, and it can give us insight into the dataset in one look. Data visualization is a crucial step in any exploratory data analysis or report. It’s usually easy to read, and it can give us insight into the dataset in one look. There are dozens of great tools for business intelligence, such as Tableau, Google Data Studio, and PowerBI that allow us to create graphs easily. A data analyst or data scientist will often create visualizations on a Jupyter Notebook using Python. Luckily, there are dozens of great Python libraries that create great graphs. However, the million-dollar question is: which one is the best? Whether you are a student or a professional, you should know a few options out there. There are not perfect libraries. Thus, you should know the pros and cons of each data visualization. I will go over four of the most popular Python libraries for data visualization: Matplotlib, Seaborn, Plotly Express, and Altair. To do so, I will create a simple bar plot and analyze how easy it is to use each library. For this blog, I will use a city dataset. You can find the notebook here. This blog will analyze how easy it is to set up a barplot, how easy it is to customize the graph to make it minimally presentable, and the library documentation. Setting up the dataset First, let’s import all the important libraries. It’s very likely that you already have Matplotlib and Seaborn installed on your computer. However, you might not have Plotly Express and Altair. You can easily install them using pip install plotly==4.14.3 and pip install altair vega_datasets. import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import altair as alt import plotly.express as px Now we will import the dataset. For demonstration purposes, let’s only create a data frame with the top 15 more populated cities in the US. I will also fix the capitalization of the names of the cities. It will facilitate the editing process when we create the visualizations. df = pd.read_csv('worldcitiespop.csv') us = df[df['Country'] == 'us'] us['City'] = us['City'].str.title() cities = us[['City', 'Population']].nlargest(15, ['Population'], keep=’first’) Now we should be ready to analyze each library. Are you ready? *Winner: *Plotly Express *Losers: *Matplotlib, Altair, and Seaborn In this category, all the libraries performed well. They are all easy to set up, and the results with basic editing are good enough for most of the analysis, but we need to have winners and losers, right? Matplotlib is very easy to set up and remember the code. However, the chart doesn’t look good. It will probably do the job for data analysis, but its result for a business meeting is not great. data-analysis python data-visualization data-science libraries 🔵 Intellipaat Data Science with Python course: this Data Science With Python Training video, you... In this tutorial, we'll learn Clash of Python Data Visualization Libraries. Let's explore it with us now. Python Libraries For Data Science. Top Data science libraries introduction of The Python programming language is assisting the developers in creating standalone PC games, mobiles, and other similar enterprise applications. I work on strategic questions and provide actionable, data-driven insights to inform product and engineering decisions. In this article, I’ll use Python to explore and visualize the classic titanic data. In Conversation With Dr Suman Sanyal, NIIT University,he shares his insights on how universities can contribute to this highly promising sector and what aspirants can do to build a successful data science career.
https://morioh.com/p/deefa38757f1
CC-MAIN-2021-25
refinedweb
622
57.87
#include "ltkrn.h" #include "ltclr.h" L_LTCLR_API L_INT L_SaveICCProfile(pszFilename, pICCProfile, pSaveOptions) Saves (embeds) an ICC profile in an image file. Character string containing the name of the file in which to save/embed an ICC profile. Pointer to an ICCPROFILEEXT structure that contains the ICC profile to save/embed. Pointer to optional extended save options. Pass NULL to use the default save options, and the profile will be saved on page 1. ICC profiles can be saved into JPEG, TIFF or GIF files. TIFF files are multipage, so the profile can be saved to a particular page using the pSaveOptions parameter. Initialize the structure pointed to by pICCProfile first by calling L_InitICCProfile. If L_SaveICCProfile succeeds, free the ICC profile by calling L_FreeICCProfile. In fact, when any ICCPROFILEEXT structure initialized by L_InitICCProfile is no longer needed, the memory must be freed by calling L_FreeICCProfile. The pData member of the ICCPROFILEEXT structure points to one block of memory that contains the entire ICC profile. The uDataSize contains the size of the material pointed to by pData. As tags are added or deleted, these members are not automatically updated. Ordinarily, to update these members, you must call L_GenerateICCPointer. And since L_SaveICCProfile depends on the values of pData and uDataSize, unless they already have correct data, they must be updated by calling L_GenerateICCPointer. Required DLLs and Libraries Win32, x64. For an example, refer to L_InitICCProfile. Direct Show .NET | C API | Filters Media Foundation .NET | C API | Transforms Media Streaming .NET | C API
https://www.leadtools.com/help/sdk/v21/colorconversion/api/l-saveiccprofile.html
CC-MAIN-2021-25
refinedweb
249
51.24
Lesson 6. How to Dissolve Polygons Using Geopandas: GIS in PythonSpatial data open source python Workshop Learning Objectives After completing this tutorial, you will be able to: - Aggregate the geometry of spatial data using dissolvebased on an attribute in Python - Aggregate the quantitative values in your attribute table when you perform a dissolve in Python What You Need You will need a computer with internet access to complete this lesson and the spatial-vector-lidar data subset created for the course. Download spatial-vector-lidar data subset (~172 MB) In this lesson, you will use Python to aggregate (i.e. dissolve) the spatial boundaries of the United States state boundaries using a region name that is an attribute of the dataset. Then, you will aggregate the values in the attribute table, so that the quantitative values in the attribute table will reflect the new spatial boundaries for regions. Import Packages and Data To get started, import the packages you will need for this lesson into Python and set the current working directory. # import necessary packages to work with spatial data in Python import os import numpy as np import geopandas as gpd import matplotlib.pyplot as plt import matplotlib.lines as mlines from matplotlib.colors import ListedColormap import earthpy as et # make figures plot inline plt.ion() # load the box module from shapely from shapely.geometry import box Dissolve Polygons Based On an Attribute with Geopandas Dissolving polygons entails combining polygons based upon a unique attribute value and removing the interior geometry. Below you will dissolve the US states polygons by the region that each state is in. When you dissolve, you will create a new set polygons - one for each region in the United States. To begin, explore your data. Using .geom_type you can see that you have a mix of single and multi polygons in your data. Sometimes multi-polygons can cause problems when processing. It’s always good to check your geometry before you begin to better know what you are working with. # query the first few records of the geom_type column state_boundary_us.geom_type.head() 0 MultiPolygon 1 Polygon 2 MultiPolygon 3 Polygon 4 Polygon dtype: object Next, select the columns that you with to use for the dissolve and that will be retained. In this case, we want to retain the columns: - region - geometry # select the columns that you with to use for the dissolve and that will be retained state_boundary = state_boundary_us[['region', 'geometry']] # dissolve the state boundary by region us_regions = state_boundary.dissolve(by='region') # view the resulting geodataframe us_regions And finally, plot the data. Note that when you dissolve, the column used to perform the dissolve becomes an index for the resultant geodataframe. Thus, you will have to use the reset_index() method when you plot, to access the region column. If you do not reset the index, the following will return and error, as region is no longer a column, it is an index! us_regions.plot(column = 'region', ax=ax) You can use us_regions.reset_index().plot(column = 'region', ax=ax) to reset the index when you plot the data. # create the plot fig, ax = plt.subplots(figsize = (10,6)) # plot the data us_regions.reset_index().plot(column = 'region', ax=ax) # Set plot axis to equal ratio ax.set_axis_off() plt.axis('equal'); Dissolve and Aggregate Data Attributes In the example above, you dissolved the state level polygons to a region level. However, you did not aggregate or summarize the attributes associated with each polygon. Next, you will learn how to aggregate quantitative values in your attribute table when you perform a dissolve. To do this, you will add aggfunc = 'summaryfunction' to your dissolve call. You can choice a suite of different summary functions including: - first - mean - max And more. Read more about the dissolve function here. Aggregate the data using the ‘sum’ method on the ALAND and AWATER attributes (total land and water area). The values for ALAND and AWATER will be added up for all of the states in a region. Those new summed values will be returned in the new dataframe. # select the columns that you wish to retain in the data state_boundary = state_boundary_us[['region', 'geometry', 'ALAND', 'AWATER']] # then summarize the quantative columns by 'sum' regions_agg = state_boundary.dissolve(by='region', aggfunc = 'sum') # display the new dataframe regions_agg # create the plot fig, ax = plt.subplots(figsize = (12,8)) # plot the data using a quantile map of the new ALAND values regions_agg.plot(column = 'ALAND', edgecolor = "black", scheme='quantiles', cmap='YlOrRd', ax=ax, legend = True) # Set plot axis to equal ratio ax.set_axis_off() plt.axis('equal'); Optional Challenge 1 Create a quantile map using the AWATER attribute column. Optional Challenge 2 Aggregate the data using the ‘mean’ method on the ALAND and AWATER attributes (total land and water area). Then create two maps: - a map of mean value for ALAND by region and - a map of mean value for AWATER by region Share onTwitter Facebook Google+ LinkedIn
https://www.earthdatascience.org/workshops/gis-open-source-python/dissolve-polygons-in-python-geopandas-shapely/
CC-MAIN-2018-34
refinedweb
820
54.12
Use this procedure to create a logical unit number (LUN) from unassigned disk drives or remaining capacity. See theSun StorEdge RAID Manager Release Notes for the latest information about LUN administration. This product supports the use of hardware RAID and host-based software RAID. For host-based software RAID, this product supports RAID levels 0+1 and 1+0. You must use hardware RAID for Oracle Parallel Server (OPS) data stored on the storage array. Do not place OPS data under volume management control. You must place all non-OPS data that is stored on the storage arrays under volume management control. Use either hardware RAID, host-based software RAID, or both types of RAID to manage your non-OPS data.. When you use host-based software RAID with hardware RAID, the hardware RAID levels you use affect hardware maintenance. If you use hardware RAID level 1, 3, or 5, you can perform most maintenance procedures without volume management disruptions. If you use hardware RAID level 0, some maintenance procedures require additional volume management administration because the availability of the LUNs is impacted. Do not configure LUNs as quorum devices. The use of LUNs as quorum devices is not supported. With all nodes booted and attached to the storage system, create the LUN on one node. After the LUN formatting completes, a logical name for the new LUN appears in /dev/rdsk on all nodes. These nodes are attached to the storage system. For the procedure about how to create a LUN, see the Sun StorEdge RAID Manager User’s Guide. If the following warning message displays, ignore the message. Continue with the next step. Use the format(1M) command to verify Solaris logical device names. Copy the /etc/raid/rdac_address file from the node on which you created the LUN to the other node. If you copy this file to the other node, you ensure consistency across both nodes. Ensure that the new logical name for the LUN that you created appears in the /dev/rdsk directory on both nodes. On one node, update the global device namespace. Ensure that the device ID numbers for the LUNs are the same on both nodes. In the sample output that follows, the device ID numbers are different. Are the device ID numbers that you received from running the scdidadm command in Step 5 the same for both nodes? If the device ID numbers are the same, proceed to Step 7. If the device ID numbers are different, perform the procedure in How to Correct Mismatched Device ID Numbers before you continue with Step 7 of this procedure. If you want a volume manager to manage the new LUN, incorporate the new LUN into a diskset or disk group. For more information, see your Solstice DiskSuite/Solaris Volume Manager or VERITAS Volume Manager documentation.
http://docs.oracle.com/cd/E19263-01/817-0174/createlun/index.html
CC-MAIN-2015-18
refinedweb
472
65.01
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. Memo - tested with python >= 2.7 Kezako Memo ? Memo is a networked, in-memory, key-value store written in Python. Yes it's a Redis clone scriptable in Python! Documentation Memo has no executable you have to build one yourself - don't panik it's really easy - using memo.Memo class and by registering the structures you need, here is an example Memo server: from memo import Memo from memo.structures.suggest import Suggest server = Memo(address='127.0.0.1', port=8008) server.add_structure(Suggest) server.start() This a server for suggesting spelling correction see the implementation in memo.structures.suggest. So how to use it Redis, before scripting was implemented, you were implementing complex data-structures outside of Redis by making calls to the needed COMMANDS. In Memo you won't do that. Instead you build structures classes that will be the entry points of your application. The benefit is similar to Redis scripting you won't need the same number of network round-trip to achieve the same and this will be done using Python. Creating a new datastructure is straightforward, see the following example FIFO datastructure: from memo.structures.base import Base from util import check_if_key_exists class FIFO(Base): def __init__(self, server, key): super(Suggest, self).__init__(server, key) self.fifo = list() @staticmethod def FIFOADD(server, key, *values): """Add an element in the fifo list create fifo if it does not exists""" if key in server.dict: if server.dict[key].is_dead: server.dict[key] = FIFO(server, key) else: if not isinstance(server.dict[key], Suggest): return 'WRONG VALUE' else: server.dict[key] = FIFO(server, key) # the key exists and is not dead dict_value = server.dict[key] for value in values: dict_value.fifo.append(value) return 'OK' @check_if_key_exists def PICK(self): value = self.fifo[0] self.fifo.remove(value) return value This data structure has 2 methods: - FIFOADD is a staticmethod which means it's probably will have in charge of creating the key value if it does not exists, indeed that's what it does. If the requested key doesn't exists or expired, it create a new FIFO and add the value. Structures staticmethod must have a unique name among all the structures registred against a Memo server. - PICK will return the first value of the FIFO if the FIFO did not expire. This structure can be used in the client like so: client.FIFOADD('task queue', 42) client.FIFOADD('task queue', 42, 43) client.PICK('task queue') The client doesn't discover the available methods, it sends every COMMAND to the server and the servers answers a tuple with the first value being RESPONSE if the command exists the element of the tuple being the result of the command, or ERROR if it doesn't exists. Mind the fact that if you call a command that exists but the key expired or doesn't exists it will still return an ERROR. A pattern that might come handy are pure static methods structures that in fact reuse structures registred against the server but this methods are the only methods that the client will need to call. This is usefull if you need to make use of expiration. For instance the following data-structure use memo.structures.List to store and retrieve search results for a given search index. Since we are in Python we can use any Python library, given a search(index, query) function that returns a list of dictionnary describing search results, a search results cache can be implemented using the following class: from memo.structures.base import Base from util import check_if_key_exists class SearchCache(Base): @staticmethod def SEARCH(server, index, query): key = '%s:%s' % (index, query) # try to retrieve cached results response = server.play(('GET', (key,)) if response[0] == 'ERROR': results = search(index, query) server.play(('LSET', results)) # persist for 15 minutes server.play(('EXPIRE', (60*15,))) return results else: return response[1] Happy hacking! License - Memo server: AfferoGPLv3 - Client: LGPLv3
https://bitbucket.org/amirouche/memo
CC-MAIN-2016-30
refinedweb
684
57.77
NAME SSL_set_fd - connect the SSL object with a file descriptor SYNOPSIS #include <openssl/ssl.h> int SSL_set_fd(SSL *ssl, int fd); int SSL_set_rfd(SSL *ssl, int fd); int SSL_set_wfd(SSL *ssl, int fd); DESCRIPTION SSL_set_fd() sets the file descriptor fd as the input/output facility for the TLS/SSL (encrypted) side of ssl. fd will typically be the socket file descriptor of a network connection. When performing the operation, a socket BIO is automatically created to interface between the ssl and fd. The BIO and hence the SSL engine inherit the behaviour of fd. If fd is non-blocking, the ssl will also have non-blocking behaviour. If there was already a BIO connected to ssl, BIO_free() will be called (for both the reading and writing side, if different). SSL_set_rfd() and SSL_set_wfd() perform the respective action, but only for the read channel or the write channel, which can be set independently. RETURN VALUES The following return values can occur: - 0 The operation failed. Check the error stack to find out why. - 1 The operation succeeded. SEE ALSO SSL_get_fd, SSL_set_bio, SSL_connect, SSL_accept, SSL_shutdown, ssl , bio
https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_fd.html
CC-MAIN-2018-13
refinedweb
184
56.66
- 0shares - Facebook0 - Twitter0 - Google+0 - Pinterest0 - LinkedIn0 Polymorphism: In object oriented programming, polymorphism is a concept that can process the objects differently with respect to the data type or the class of the objects. Polymorphism redefines the methods for derived classes or child classes.. Now we are introducing early binding and late binding. Binding is a process, that is used to convert the variable names and function names into machine. There are two types of binding in C++ programming language; early binding and late binding. Early binding means that the compiler is able to convert the variable names and functions names into machine language address directly. All the functions have a different address in machine language; therefore, the compiler directly goes to that function. The direct function call is solved by early binding. Late binding is also called dynamic binding. In C++ programming language dynamic means at run time. It means that when it is not possible for the compiler to run a program or to know which function is to be call until run time, this is known as late binding. In C++ programming, to get late binding, we use function pointers. A function pointer refers to a pointer that point to function instead of variables. Consider the following example to understand the concept of late binding: Virtual Function A virtual function is a function that is declared in the base class. It is declared using a keyword virtual. A virtual function that is defined in the base class and has some versions in the derived class too tells the compiler that there is no need to add a static linkage for this function. We only need to call the function anywhere or any point in the program. Consider the following example. # include <iostream> using namespace std; # include <conio.h> class base { public: virtual void show (); }; void base :: show ( ) { cout << ”base class” ; } class derived: public base { public: void show (); }; void derived :: show () { cout << ”derived class” ; } void main () { derived d; base *b = new d; b -> show (); getche (); } Working of above program: In the main function, pointer is used to call the function show () through late binding. As we are using a pointer, we use the dereferencing operator (->) to call the function. The function is called using the base class pointer. In the line base *b =new d; the pointer b contains the address of object of derived class that is d. Therefore the function show () of derived class is called and it prints:
http://www.tutorialology.com/cplusplus/polymorphism/
CC-MAIN-2017-22
refinedweb
413
62.58
21 March 2011 07:42 [Source: ICIS news] (Adds details after paragraph 5) By Helen Lee and Felicia Loo SINGAPORE (ICIS)--Shell has declared force majeure on monoethylene glycol (MEG) after shutting down its 800,000 tonne/year mixed-feed cracker in Pulau Bukom, Singapore, market sources said on Monday. “We have declared force majeure under some of our chemicals contracts,” said a company spokesperson, without elaborating which products have been affected. “This is because the ethylene cracker unit on our Pulau Bukom manufacturing site is facing operational issues and this has affected our ability to supply product to some of our customers,” the spokesperson said. “The rest of our operations at Bukom are not affected,” the spokesperson added. Sources said the cracker was forced to shut since 18 March and that MEG was one of the products affected. The cracker had recently completed a turnaround and was restarted over the weekend of 12-13 March. The cracker was shut at 21:00 ?xml:namespace> They added that the shutdown period would last 10 days. "Prompt C3 supplies will be affected," said one trader. But traders added that spot C3 demand from the There was also FM on ethylene exports, traders said. The spokesperson said Shell was working to resume normal operations and supply as soon as possible so as to minimise potential impact on its customers. “We very much regret the impact this has on some of our customers. We will continue to work with them and to keep them regularly updated with regard to our ability to resume normal operations and supply,” the spokesperson added. Shell’s 750,000 tonne/year MEG plant in “Things are in a bit of a flux now because it is just the first working day after the FM so they are waiting to assess the market situation,” according to a source close to the company. A northeast Asia-based ethylene trader said it was suspending offers for now and it had no firm selling ideas until a clearer picture of the impact of the outage emerged. “There’s a perceived ethylene shortage in the north because of issues in With additional reporting by Nurluqman Suratman, Mahua Chakravarty and Yu Guo
http://www.icis.com/Articles/2011/03/21/9445464/shell-shuts-bukom-cracker-declares-fm-on-meg.html
CC-MAIN-2014-42
refinedweb
368
57.4
Merged in gforth-EC patches \ Etags support for GNU Forth. \ variable LAST must contain a pointer to the last \ header, NAME>STRING must convert that pointer to a string, and \ HEADER must be a deferred word that is called to create the name. include last-loadfilename 2@ d<> if #ff r@ emit-file throw #lf r@ emit-file throw sourcefilename 2dup r@ write-file throw last-loadfilename 2! s" ,0" r@ write-line throw endif rdrop ; : put-tags-entry ( -- ) \ write the entry for the last name to the TAGS file \ if the input is from a file and it is not a local name source-id dup 0<> swap -1 <> and \ input from a file current @ locals-list <> and \ not a local name last @ 0<> and \ not an anonymous (i.e. noname) header if tags-file-id >r r@ put-load-file-name source drop >in @ r@ write-file throw 127 r@ emit-file throw bl r@ emit-file throw last @ name>string r@ write-file throw bl r@ emit endif ; : (tags-header) ( -- ) defers header put-tags-entry ; ' (tags-header) IS header
http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/etags.fs?rev=1.7;sortby=log;f=h;only_with_tag=v0-3-0
CC-MAIN-2020-10
refinedweb
182
56.93
Christian Anton wrote: > >I'm wanting to use mailman on a postfix-powered machine with virtual >domains. As i found out that "out-of-the-box" mailman does not support >this fine (one only namespace for mailing list names etc) i found this >patch in the FAQ of mailman: > > >The problem i have with it is that it seems to be for an older version >of mailman. It says something of version 2.1.1. I'm using 2.1.5 so it >will not apply. I tried to patch the file manually reading the patch and >making the changes in the source file, everything installes fine but >when i try to access mailman's "listinfo" cgi with a browser, i get this: > >Mar 14 17:45:11 2005 admin(4153): >@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ >admin(4153): [----- Mailman Version: 2.1.5 -----] >admin(4153): [----- Traceback ------] >admin(4153): Traceback (most recent call last): >admin(4153): File "/home/mailman/scripts/driver", line 94, in run_main >admin(4153): pkg = __import__('Mailman.Cgi', globals(), locals(), >[scriptname]) >admin(4153): File "/home/mailman/Mailman/Cgi/listinfo.py", line 27, in ? >admin(4153): from Mailman import MailList >admin(4153): IndentationError: unindent does not match any outer >indentation level (MailList.py, line 449) <snip> Indentation is critical in Python. You have not properly matched indentation between the patch and the base in MailList.py. It is safest to indent with spaces only. Mixing spaces and tabs in one file causes problems. -- Mark Sapiro <msapiro at value.net> The highway is for gamblers, San Francisco Bay Area, California better use your sense - B. Dylan
https://mail.python.org/pipermail/mailman-users/2005-March/043507.html
CC-MAIN-2020-24
refinedweb
261
65.73
Posted 16 Apr 2009 Link to this post Hi, I am designing an RSS Feed reader using a RAD Grid and RAD Combo box. My combo box will list all the sites whose feeds I subscribe to (e.g. this site, MSDN, etc etc). On the selection of a feed, I want to fire an event handler (implemented) but I want to get the corresponding feed URL of a site title (using my dictionary collection in C#). However, you cannot add new parameters to an event handler unless you override it. This raises confusion for me. I have an event which is derived from RADComboBox... (can't remember exact name), and I've added the extra field in the derived constructor. However, when I call the event handler at onSelectionChanged, I get this error: Error 5 No overload for 'NewEventHandler' matches delegate 'Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventHandler' Code: public class NewEventHandler : Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs { public string Url; public NewEventHandler(string text, string oldtext, string value, string oldValue, string Url) : base(text, oldtext, value, oldValue) { } } I then call this event handler on the appropriate/relevant event, and pass in the parameters in the constructor of the event handler, like so: onselectedindexchanged="NewEventHandler" protected void NewEventHandler(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e, string Url) { What am I doing wrong? Thanks Posted 17 Apr 2009 Link to this post Is there an example of this (Either in general ASP.NET or in specific to rad controls)? I ask, because I don't have much experience modifying event functionality. Posted 20 Apr 2009 Link to this post Posted 21 Apr 2009 Link to this post
http://www.telerik.com/forums/deriving-new-event-handler-for-onselectionchanged
CC-MAIN-2017-34
refinedweb
272
55.44
My application is assumed to be running on a Mac OS X system. However, what I need to do is figure out what version of Mac OS (or Darwin) it is running on, preferably as a number. For instance, import os os.system("uname -r") >>> import platform >>> platform.mac_ver() ('10.5.8', ('', '', ''), 'i386') As you see, the first item of the tuple mac_ver returns is a string, not a number (hard to make '10.5.8' into a number!-), but it's pretty easy to manipulate the 10.x.y string into the kind of numbers you want. For example, >>> v, _, _ = platform.mac_ver() >>> v = float('.'.join(v.split('.')[:2])) >>> print v 10.5 If you prefer the Darwin kernel version rather than the MacOSX version, that's also easy to access -- use the similarly-formatted string that's the third item of the tuple returned by platform.uname().
https://codedump.io/share/wRYF8nDH1m8c/1/how-to-detect-mac-os-version-using-python
CC-MAIN-2017-43
refinedweb
150
68.97
2D text annotation More... #include <vtkTextMapper.h> 2D text annotation vtkTextMapper provides 2D text annotation support for VTK. It is a vtkMapper2D that can be associated with a vtkActor2D and placed into a vtkRenderer. To use vtkTextMapper, specify an input text string. Definition at line 47 of file vtkTextMapper.h. Definition at line 50 of file vtkTextM2D. Reimplemented in vtkOpenGLTextMapper. Methods invoked by print to print information about the object including superclasses. Typically not called by the user (use Print() instead) but used in the hierarchical print process to combine the output of several classes. Reimplemented from vtkMapper2D. Reimplemented in vtkOpenGLTextMapper. Creates a new text mapper. Return the size[2]/width/height of the rectangle required to draw this mapper (in pixels). The input text string to the mapper. Set/Get the text property. Shallow copy of an actor. Reimplemented from vtkAbstractMapper. Set and return the font size (in points) required to make this mapper fit in a given target rectangle (width x height, in pixels). A static version of the method is also available for convenience to other classes (e.g., widgets). Set and return the font size (in points) required to make each element of an array of mappers fit in a given rectangle (width x height, in pixels). This font size is the smallest size that was required to fit the largest mapper in this constraint. Use these methods when setting font size relative to the renderer's size. These methods are static so that external classes (e.g., widgets) can easily use them. Release any graphics resources that are being consumed by this mapper. The parameter window could be used to determine which graphic resources to release. Reimplemented from vtkAbstractMapper. Override Modifiedtime as we have added Clipping planes. Reimplemented from vtkAbstractMapper. Definition at line 130 of file vtkTextMapper.h. Definition at line 131 of file vtkTextMapper.h.
https://vtk.org/doc/nightly/html/classvtkTextMapper.html
CC-MAIN-2020-50
refinedweb
311
61.63
Opened 10 years ago Closed 9 years ago #3083 closed defect (fixed) MySQL IntegrityError Exception on object creation Description When two users try to register _simulaneously_ with the same username, they both pass validation (because at that moment nobody of them is registered), but when we do actual user.save(), one of them gets MySQL IntegrityError (Duplicate Key Error). Yes, I can handle it, from MySQLdb import IntegrityError try: user.save() except IntegrityError: errors['username'] = 'User with this username already exists', but there is dependence to MySQL. I can't simply do "except:", because there can be another trouble, such as no connectivity to database during restart, but user would get confusing message about invalid username. The same thing is with all models. Change History (6) comment:1 Changed 10 years ago by comment:2 Changed 10 years ago by comment:3 Changed 10 years ago by Sorry, I didn't see that Adrian put it into "Database Wrapper" category. It could be there, or generic views, or admin ;-) comment:4 Changed 10 years ago by I'm not a fan of Django magically handling IntegrityError(s), there are different ways to handle them and picking just one won't be very flexible, though I don't use generic views for my add/edit/update so I'm a bit biased. Like I mentioned on Django-users I think the best approach to this is simply to remove the dependency on the db module by making IntegrityError available directly through django.db, I'll submit a patch that does this soon. comment:5 Changed 9 years ago by comment:6 Changed 9 years ago by jordanl: yes, it does. I propose to do it like this, so there's no need to interprete database error messages: But perhaps someone has a better idea. If there's a good pattern, maybe the generic views could use it, too? Since there's a multitude of ways to solve this and it is not clear how to proceed (Adrian has rejected the above solution), I only put this into "Design decision needed". Some references from django-users:
https://code.djangoproject.com/ticket/3083
CC-MAIN-2016-50
refinedweb
354
57.71
#include <db.h> int memp_sync(DB_ENV *env, DB_LSN *lsn); The memp_sync function ensures that any modified pages in the pool with log sequence numbers less than the lsn argument are written to disk. If lsn is NULL, all modified pages in the pool are flushed. The primary purpose of the memp_sync function is to enable a transaction manager to ensure, as part of a checkpoint, that all pages modified by a certain time have been written to disk. Pages in the pool that cannot be written back to disk immediately (for example, pages that are currently pinned) are written to disk as soon as it is possible to do so. The expected behavior of the Berkeley DB or other Transaction subsystem is to call the memp_sync function and then, if the return indicates that some pages could not be written immediately, to wait briefly and retry again with the same log sequence number until the memp_sync function returns that all pages have been written. To support the memp_sync functionality, it is necessary that the pool functions know the location of the log sequence number on the page for each file type. This location should be specified when the file is opened using the memp_fopen function. It is not required that the log sequence number be aligned on the page in any way. The memp_sync function returns a non-zero error value on failure, 0 on success, and returns DB_INCOMPLETE if there were pages which need to be written but that memp_sync was unable to write immediately. In addition, if memp_sync returns success, the value of lsn will be overwritten with the largest log sequence number from any page that was written by memp_sync to satisfy this request. The memp_sync function may fail and return a non-zero error for the following conditions: The memp_sync function was called without logging having been initialized in the environment. The memp_sync function may fail and return a non-zero error for errors specified for other Berkeley DB and C library or system functions. If a catastrophic error has occurred, the memp_sync function may fail and return DB_RUNRECOVERY, in which case all subsequent Berkeley DB calls will fail in the same way.
http://pybsddb.sourceforge.net/api_c/memp_sync.html
CC-MAIN-2017-47
refinedweb
367
51.72
Using lxml.objectify to Parse XML With Python Join the DZone community and get the full member experience.Join For Free A couple years ago I started a series of articles on XML parsing. I covered lxml’s etree and Python builtin minidom XML parsing library. For whatever reason I didn’t notice lxml’s objectify sub-package, but I saw it recently and decided to check it out. In my mind, the objectify module seems to be even more “Pythonic” than etree is. Let’s take some time and go over my old XML examples using objectify and see how it’s different! Let’s Get This Party Started! If you haven’t already, go out and download lxml or you won’t be able to follow along very well. Once you have it, we can continue. We’ll be using the following piece of XML for our parsing pleasure: <?xml version="1.0" ?> <zAppointments reminder="15"> <appointment> <begin>1181251680</begin> <uid>040000008200E000</uid> <alarmTime>1181572063</alarmTime> <state></state> <location></location> <duration>1800</duration> <subject>Bring pizza home</subject> </appointment> <appointment> <begin>1234360800</begin> <duration>1800</duration> <subject>Check MS Office website for updates</subject> <location></location> <uid>604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800</uid> <state>dismissed</state> </appointment> </zAppointments> Now we need to write some code that can parse and modify the XML. Let’s take a look at this little demo that shows a bunch of the neat abilities that objectify provides. from lxml import etree, objectify #---------------------------------------------------------------------- def parseXML(xmlFile): """""" with open(xmlFile) as f: xml = f.read() root = objectify.fromstring(xml) # returns attributes in element node as dict attrib = root.attrib # how to extract element data begin = root.appointment.begin uid = root.appointment.uid # loop over elements and print their tags and text for e in root.appointment.iterchildren(): print "%s => %s" % (e.tag, e.text) # how to change an element's text root.appointment.begin = "something else" print root.appointment.begin # how to add a new element root.appointment.new_element = "new data" # print the xml obj_xml = etree.tostring(root, pretty_print=True) print obj_xml # remove the py:pytype stuff #objectify.deannotate(root) etree.cleanup_namespaces(root) obj_xml = etree.tostring(root, pretty_print=True) print obj_xml # save your xml with open("new.xml", "w") as f: f.write(obj_xml) #---------------------------------------------------------------------- if __name__ == "__main__": f = r'path\to\sample.xml' parseXML(f) The code is pretty well commented, but we’ll spend a little time going over it anyway. First we pass it our sample XML file and objectify it. If you want to get access to a tag’s attributes, use the attrib property. It will return a dictionary of the attribute’s of the tag. To get to sub-tag elements, you just use dot notation. As you can see, to get to the begin tag’s value, we can just do something like this: begin = root.appointment.begin If you need to iterate over the children elements, you can use iterchildren. You may have to use a nested for loop structure to get everything. Changing an element’s value is as simple as just assigning it a new value. And if you need to create a new element, just add a period and the name of the new element (see below): root.appointment.new_element = "new data" <code> When we add or change items using objectify, it will add some annotations to the XML, such as <em>xmlns:py=" py:pytype="str"</em>. You may not want that included, so you'll have to call the following method to remove that stuff: <code>[python] etree.cleanup_namespaces(root) You can also use “objectify.deannotate(root)” to do some deannotation chores, but I wasn’t able to get it to work for this example. To save the new XML, you actually seem to need lxml’s etree module to convert it to a string so you can save it. At this point, you should be able to parse most XML documents and edit them effectively with lxml’s objectify. I thought it was very intuitive and easy to pick up. Hopefully you will find it useful in your endeavors as well. Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/using-lxmlobjectify-parse-xml
CC-MAIN-2022-21
refinedweb
713
58.99
16 December 2011 09:11 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The price increase came into effect on 15 December and the latest list prices are at Rs64.50/kg on a delivered ( “The weakening local currency has become a concern for all importers and they prefer local material,” a major Indian producer said. At the same time, producers said they are concerned over the uncertainties in the upstream ethylene market. Ethylene prices increased by $30-60/tonne (€23-46/tonne) during the past two weeks from an average price of $1,110/tonne CFR (cost & freight) northeast (NE) Asia in the first week of December to $1,140-1,170/tonne CFR NE Asia on 15 December. “[The increase] is also cost-pushed,” a second local producer said. However, the producers added that the hike in prices is difficult for buyers to accept. “We see hesitance in purchasing,” a third producer said, adding that most players are staying on the sidelines and expecting the prices to fall in the near term. Major PVC producers in ($1 = Rs53.64) For more on ethylene and polyvinyl chloride,
http://www.icis.com/Articles/2011/12/16/9517113/india-pvc-producers-raise-pvc-prices-by-rs1.5kg-on-weaker.html
CC-MAIN-2014-49
refinedweb
187
62.68
If you would like to use cordova events in your app, use this package. import Cordova from this package and you ready to go! ## installation dependencies: cordova: ^1.0.1 ## import import 'package:cordova/cordova.dart'; ## supported events - deviceready - backbutton - menubutton - pause - resume Add this to your package's pubspec.yaml file: dependencies: cordova: ^1.0.2 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:cordova/cordova.dart'; We analyzed this package on Jun 12, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: web Primary library: package:cordova/cordova.dartwith components: html, js. Maintain an example. (-10 points) Create a short demo in the example/ directory to show how to use this package. Common filename patterns include main.dart, example.dart, and cordova.dart. Packages with multiple examples should provide example/README.md. For more information see the pub package layout conventions.
https://pub.dev/packages/cordova
CC-MAIN-2019-26
refinedweb
182
53.88
Segmentation Fault or SIGSEGV is a dreaded error of most C programmers. It mostly occurs due to invalid access of memory. Most of the times the invalid memory access is a mistake. However recently one of my friend asked me a question (who was asked the same in an interview) as to what happened if an arbitrary address is accessed? The question was as follows: #include <stdio.h> int main(int argc, char *argv[]) { int *p; p = (int*)1; printf("%d %d", p, *p); return 0; } Now I had never come across a scenario where you assign a value directly to a pointer variable and my first thought was, would this even compile? As a matter of fact it did, when I did compile with gcc. But on running the output file, I got the dreaded Segmentation Fault. Now curious as to why, I stepped through the code using gdb and this is what I stumbled upon: breakpoint 1, main () at test.c:6 6 p = (int*)1; (gdb) p p $1 = (int *) 0x0 (gdb) n 7 printf("%d %d", p, *p); (gdb) p p $2 = (int *) 0x1 (gdb) p *p Cannot access memory at address 0x1 (gdb) n Program received signal SIGSEGV, Segmentation fault. 0x00000000004004ac in main () at test.c:7 7 printf("%d %d", p, *p); Now let’s dissect what exactly is going on. Variable is a pointer variable, means it can hold an address. Since its an integer pointer, p can hold address of an integer variable. Now when we assign (int*)1 to p, what is happening is 1 is being assigned to p. But 1 is not being assigned directly, since 1 is prefixed with (int*) which is essentially casting 1 as an address of an integer variable. Hence p is being assigned an address 0x01 which is a valid instruction! Now in all probability, 0x01 is a valid address, but most definitely not a valid address for the program we are running. (We know the OS and other programs are already running, so we can be certain some other process is running at the first memory location, which is a valid address, but not valid for our program to access!) Hence on trying to print the value at this address, we encounter Segmentation Fault!
https://sudhinrblog.wordpress.com/2015/08/
CC-MAIN-2018-13
refinedweb
381
69.72
Introduction Ever wondered how these search engines like Google and Yahoo work. And ever thought about how can they scan all through the internet and return relevant results in just About 5,43,00,000 results (0.004seconds). Well, they work on the concept of Crawling and Indexing. - Crawling: Automated bots looks for pages that are new or updated. And stores the key information like — URL, title, keywords, and so on from the pages to be used later. - Indexing: Data captured from crawling is analyzed like — what the page is about. Key content, images, and video files on the page are used in the process. This information is indexed and stored to be returned later for a search query. Hence, whenever we asked them to search anything for us they are not scanning through the length and breadth of the internet but just scanning through those indexed URLs in step 2. Well, today we would work on how to develop a small prototype, very similar to the indexing functionality of any search engine. We would be using a tweets dataset on #COVID and try to index them based on our search term. A. Importing packages import pandas as pd from rank_bm25 import * What is BM25? BM25 is a simple Python package and can be used to index the data, tweets in our case, based on the search query. It works on the concept of TF/IDF i.e. - TF or Term Frequency — Simply put, indicates the number of occurrences of the search term in our tweet - IDF or Inverse Document Frequency — It measures how important your search term is. Since TF considers all terms equally important, thus, we can’t only use term frequencies to calculate the weight of a term in your text. We would need to weigh down the frequent terms while scaling up the rare terms showing their relevancy to the tweet. Once you run the query, BM25 will show the relevancy of your search term with each of the tweets. You can sort it to index the most relevant ones. B. Preparing your tweets Since this is not a discussion on Twitter API, will start using an excel based feed. You can clean your text data on these key steps to make the search more robust. 1. Tokenization: Splitting the sentence into words. So that each word can be considered uniquely. from nltk.tokenize import word_tokenize sentence = “Jack is a sharp minded fellow” words = word_tokenize(sentence) print(words) Output: ['Jack', 'sharp', 'minded', 'fellow'] 2. Removing special characters: Removing the special characters from your tweets def spl_chars_removal(lst): lst1=list() for element in lst: str=”” str = re.sub(“[⁰-9a-zA-Z]”,” “,element) lst1.append(str) return lst1 3. Removing stop words: Stop words are commonly used words (is, for, the, etc.) in the tweets. These words do not signify any importance as they do not help in distinguishing two tweets. I used Gensim package to remove my stopwords, you can also try it using nltk, but I found Gensim much faster than others. One can also easily add new words to the stop words list, in case your data is particularly surrounded with those words and is frequently occurring. #adding words to stopwords from nltk.tokenize import word_tokenize from gensim.parsing.preprocessing import STOPWORDS #adding custom words to the pre-defined stop words list all_stopwords_gensim = STOPWORDS.union(set([‘disease’])) def stopwprds_removal_gensim_custom(lst): lst1=list() for str in lst: text_tokens = word_tokenize(str) tokens_without_sw = [word for word in text_tokens if not word in all_stopwords_gensim] str_t = “ “.join(tokens_without_sw) lst1.append(str_t) return lst1 4.”. This technique is important for noisy texts such as social media comments, text messages, and comments to blog posts where abbreviations, misspellings, and use of out-of-vocabulary words (oov) are prevalent. People tend to write comments in short-hand and hence this pre-processing becomes very important. 5. Stemming: Process of transforming the words to their root form. It’s the process of reducing inflection in words (e.g. troubled, troubles) to their root form (e.g. trouble). The “root” in this case may not be a real root word, but just a canonical form of the original word. Stemming uses a heuristic process that chops off the ends of words in the hope of correctly transforming words into their root form. It needs to be reviewed as in the below example you can see “Machine” gets transformed to “Machin”, “e” is chopped off in the stemming process. import nltk from nltk.stem import PorterStemmer ps = PorterStemmer() sentence = “Machine Learning is cool” for word in sentence.split(): print(ps.stem(word)) C. Tokenizing tweets and running BM25 This is the central piece where we run the query for search. We search the tweets based on the word “vaccine” user-based. One can enter a phrase too and it will fluently as we tokenize our search term in the 2nd line below. You can check the association of each tweet with your search term using .get_scores function. doc_scores = bm25.get_scores(tokenized_query) print(doc_scores) As we enter n=5 in .get_top_n we would get five most associated tweets as our result. You can put the value of n according to your needs. D. Top Five associated Tweets E. Additional use cases of BM25 There can be many use cases where a search feature is required. One of the most relevant ones is around parsing the PDF and developing a search function over the PDF content. This is one of the widely used cases for BM25. As the globe slowly shifts to better data strategy and efficient storage techniques, the old PDF documents can be retrieved efficiently using algorithms like BM25. Hope you enjoyed reading this and find this helpful. Thank you, folks! Reference Links The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.You can also read this article on our Mobile APP One Comment Amazing. You’ve explained it in a very concise and clear manner. Will try this out.
https://www.analyticsvidhya.com/blog/2021/05/build-your-own-nlp-based-search-engine-using-bm25/
CC-MAIN-2021-25
refinedweb
1,006
65.01
On Wed, Sep 13, 2000 at 02:38:07PM -0700, Darren/Torin/Who Ever... wrote: > Dom. > of course you cannot test version numbers only. yes, version could help to choose whether or not the test is needed. you know that below a certain version you are speaking of db2 in glibc2 and above you are speaking of db2 out of glibc2. between these versions you have ambiguity and test is needed. what to do in this test i'm not able to tell you. > I suppose that I could have configure write a C program that included > <db.h> and linked with -ldb. If it failed, try including <db2/db.h> and > if that worked, then I've isolated the problem in configure. > i suppose you should care what the linker is linking your test code at too, but you already know this. i have a printed manual of autoconf i've never read too much. it seems not to be a great pain write new tests, but for sure it is neither *that* easy. i never did such a thing before. IMHO, your problem your problem is best solved by autoconf. btw, if i'm not wrong, these changes in glibc2 affects many other developers. maybe in autoconf's upstream level they will write this test. maybe. i'm sorry i cannot help you more :(( cheers ps: and if you check for something like __DB_H__ after the header that in older glibc2 would have included it? if this symbol is not defined, it means that you are talking about a glibc2 without db2. so you know where to look for it. <db2/db.h>! since i don't know which relation exists between glibc2 headers and db2 ones, i could be completely wrong. :( just an idea to make simpler the test for autoconf. something like: #include <whatever_glibc2_header_should_include_db_H.h> int main() { #ifdef __DB_H__ return 0; #elif return 1; #endif } checking the return of this test you should know what kind of db.h you have and you don't even care about which library to link it at! this code should work without any db2 library linked, since it doesn't reference any external symbol. hmm, i'm not so sure of this last words... i'm not a great developer. but once you know who db.h is, you know which db2 shared library you need. ... more 2 cents... :) -----[ Domenico Andreoli, aka cavok --[ get my public gpg key at -----[ 3A0F 2F80 F79C 678A 8936 4FEE 0677 9033 A20E BC50 Attachment: pgpcC5jkRVWWl.pgp Description: PGP signature
https://lists.debian.org/debian-devel/2000/09/msg00982.html
CC-MAIN-2016-50
refinedweb
426
84.47
There might be times when you have to remove a specific node (or multiple nodes) from service, either temporarily or permanently. This might include cases of troubleshooting nodes that are in a bad state, or retiring nodes after an update to the AMI so that all nodes are using the new AMI. This topic describes how to temporarily prevent new workloads from being assigned to a node, as well as how to safely remove workloads from a node so that it can be permanently retired. The kubectl cordon <node> command will prevent any additional pods from being scheduled onto the node, without disrupting any of the pods currently running on it. For example, let’s say a new node in your cluster has come up with some problems, and you want to cordon it before launching any new runs to ensure they will not land on that node. The procedure might look like this: $ kubectl get nodes <none> 51m v1.14.7-eks-1861c5 ip-192-168-3-110.us-east-2.compute.internal Ready <none> 12d v1.14.7-eks-1861c5 $ kubectl cordon ip-192-168-24-46.us-east-2.compute.internal node/ip-192-168-24-46.us-east-2.compute.internal cordoned $ kubectl get no,SchedulingDisabled <none> 53m v1.14.7-eks-1861c5 ip-192-168-3-110.us-east-2.compute.internal Ready <none> 12d v1.14.7-eks-1861c5 Notice the SchedulingDisabled status on the cordoned node. You can undo this and return the node to service with the command kubectl cordon <node>. Identify user workloads Before removing a node from service permanently, you must ensure there are no workloads still running on it that should not be disrupted. For example, you might see the following workloads running on a node (notice the specification of the compute namespace with -n and wide output to include the node hosting the pod with -o): $ kubectl get po -n domino-compute -o wide | grep ip-192-168-24-46.us-east-2.compute.internal run-5e66acf26437fe0008ca1a88-f95mk 2/2 Running 0 23m 192.168.4.206 ip-192-168-24-46.us-east-2.compute.internal <none> <none> run-5e66ad066437fe0008ca1a8f-629p9 3/3 Running 0 24m 192.168.28.87 ip-192-168-24-46.us-east-2.compute.internal <none> <none> run-5e66b65e9c330f0008f70ab8-85f4f5f58c-m46j7 3/3 Running 0 51m 192.168.23.128 ip-192-168-24-46.us-east-2.compute.internal <none> <none> model-5e66ad4a9c330f0008f709e4-86bd9597b7-59fd9 2/2 Running 0 54m 192.168.28.1 ip-192-168-24-46.us-east-2.compute.internal <none> <none> domino-build-5e67c9299c330f0008f70ad1 1/1 Running 0 3s 192.168.13.131 ip-192-168-24-46.us-east-2.compute.internal <none> <none> Different types of workloads must be treated differently. You can see the details of a particular workload with kubectl describe po run-5e66acf26437fe0008ca1a88-f95mk -n domino-compute. The labels section of the describe output is particularly useful to distinguish the type of workload, as each of the workloads named as run-… will have a label like dominodatalab.com/workload-type=<type of workload>.. The previous example contains one each of the major user workloads: run-5e66acf26437fe0008ca1a88-f95mkis a Batch Job, with label dominodatalab.com/workload-type=Batch. It will stop running on its own once it is finished and disappear from the list of active workloads. run-5e66ad066437fe0008ca1a8f-629p9, is a Workspace, with label dominodatalab.com/workload-type=Workspace. It will keep running until the user who launched it shut it down. You have the option of contacting users to shut down their workspaces, waiting a day or two in the expectation they will shut them down naturally, or removing the node with the workspaces still running. (The last option is not recommended unless you are certain there is no un-synced work in any of the workspaces and have communicated with the users about the interruption.) run-5e66b65e9c330f0008f70ab8-85f4f5f58c-m46j7, is an App, with label dominodatalab.com/workload-type=App. It is a long-running process, and is governed by a kubernetes deployment. It will be recreated automatically if you destroy the node hosting it, but will experience whatever downtime is required for a new pod to be created and scheduled on another node. See below for methods to proactively move the pod and reduce downtime. model-5e66ad4a9c330f0008f709e4-86bd9597b7-59fd9, is a Model API. It does not have a dominodatalab.com/workload-typelabel, and instead is easily identifiable by the pod name. It is also a long-running process, similar to an app, with similar concerns. See below for methods to proactively move the pod and reduce downtime. domino-build-5e67c9299c330f0008f70ad1is a Compute Environment. It will finish on its own and go into a Completedstate. Manage long-running workloads For the long-running workloads governed by a Kubernetes deployment, you can proactively move the pods off of the cordoned node by running a command like this: $ kubectl rollout restart deploy model-5e66ad4a9c330f0008f709e4 -n domino-compute Notice the name of the deployment is the same as the first part of the name of the pod in the above section. You can see a list of all deployments in the compute namespace by running kubectl get deploy -n domino-compute. Whether the associated app or model experiences any downtime will depend on the update strategy of the deployment. For the two example workloads above in a test deployment, one App and one Model API, we have the following (describe output filtered here for brevity): $ kubectl describe deploy run-5e66b65e9c330f0008f70ab8 -n domino-compute | grep -i "strategy\|replicas:" Replicas: 1 desired | 1 updated | 1 total | 1 available | 0 unavailable StrategyType: RollingUpdate RollingUpdateStrategy: 1 max unavailable, 1 max surge $ kubectl describe deploy model-5e66ad4a9c330f0008f709e4 -n domino-compute | grep -i "strategy\|replicas:" Replicas: 2 desired | 2 updated | 2 total | 2 available | 0 unavailable StrategyType: RollingUpdate RollingUpdateStrategy: 0 max unavailable, 25% max surge The App in this case would experience some downtime, since the old pod will be terminated immediately ( 1 max unavailable with only 1 pod currently running). The model will not experience any downtime since the termination of the old pod will be forced to wait until a new pod is available ( 0 max unavailable). If desired, you can edit the deployments to change these settings and avoid downtime. Manage older versions of Kubernetes Earlier versions of kubernetes do not have the kubectl rollout restart command, but a similar effect can be achieved by "patching" the deployment with a throwaway annotation like this: $ kubectl patch deploy run-5e66b65e9c330f0008f70ab8 -n domino-compute -p '{"spec":{"template":{"metadata":{"annotations":{"migration_date":"'$(date +%Y%m%d)'"}}}}}' The patching process will respect the same update strategies as the above restart command. In cases where you have to retire many nodes, it can be useful to loop over many nodes and/or workload pods in a single command. Customizing the output format of kubectl commands, appropriate filtering, and combining with xargs makes this possible. For example, to cordon all nodes in the default node pool, you can run the following: $ kubectl get nodes -l dominodatalab.com/node-pool=default -o custom-columns=:.metadata.name --no-headers | xargs kubectl cordon To view only apps running on a particular node, you can filter using the labels discussed previously: $ kubectl get pods -n domino-compute -o wide -l dominodatalab.com/workload-type=App | grep <node-name> To do a rolling restart of all model pods (over all nodes), you can run: $ kubectl get deploy -n domino-compute -o custom-columns=:.metadata.name --no-headers | grep model | xargs kubectl rollout restart -n domino-compute deploy When constructing such commands for larger maintenance, always run the first part of the command by itself to verify that the list of names being passed to xargs and to the final kubectl command are what you expect.
https://admin.dominodatalab.com/en/5.0/admin_guide/7965b6/remove-a-node-from-service/
CC-MAIN-2022-27
refinedweb
1,307
51.07
Im working on a problem today and I getting errors for some reason. Problem statement: Code : Design and implement an application that creates a histogram, which allows you to visually inspect the frequency distribution of a set of values. The program should read in an arbitrary number of integers that are in the range 1 to 100 inclusive; then produce a chart similar to the one below that indicates how many input values fell in the range 1-10, 11-20, and so on. Print one asterisk for each value entered. Here's the catch, making that problem is okay for me, but what if i wanted it to create it from reading values from a txt file? This is my final code: Code : import java.util.*; import java.io.*; public class Histogram { public void displayIntArray(int[] iAr) { for(int index = 0; index < iAr.length; index++) { System.out.println(iAr[index]); } } public int[] readIntArrayFromFile(String fileName) throws Exception { Scanner fileScan = new Scanner(new File(fileName)); int counter = 0; while(fileScan.hasNext()) { fileScan.next(); counter++; } int[] iArray = new int[counter]; Scanner fScan = new Scanner(new File(fileName)); counter = 0; while(fScan.hasNext()) { iArray[counter] = fScan.nextInt(); counter++; } return iArray; } public int[] initializeCounterArray(int[] inArray) { final int SIZE = 10; final int MIN = 1; final int MAX = 100; int[] counters = new int[SIZE]; int n, nextt, ix; while (n < 0); { int[] numbers = new int[n]; } for (int index = 0; index < inArray.length; index++) { int number = inArray[index]; if (number >= MIN && number <= MAX) { int newIndex = (number - 1) / SIZE; counters[newIndex]++; } } return counters; // Creates the histogram values String[] stars = {" 1 - 10 |", "11 - 20 | ", "21 - 30 | ", "31 - 40 | ", "41 - 50 | ", "51 - 60 | ", "61 - 70 | ", "71 - 80 | ", "81 - 90 | ", "91 - 100 | "}; //10 strings for the different parameters for (ix = 0; ix < n; ix++) { nextt = numbers[ix]; if (nextt < 11) { stars[0] += "*"; } else { if (nextt < 21) { stars[1] += "*"; } else { if (nextt < 31) { stars[2] += "*"; } else { if (nextt < 41) { stars[3] += "*"; } else { if (nextt < 51) { stars[4] += "*"; } else { if (nextt < 61) { stars[5] += "*"; } else { if (nextt < 71) { stars[6] += "*"; } else { if (nextt < 81) { stars[7] += "*"; } else { if (nextt < 91) { stars[8] += "*"; } else { stars[9] += "*"; } } for (ix = 0; ix < 10; ix++) { System.out.println(stars[ix]); } } } } } } } } } } } I've got the driver class all good to go but just in case: Code : public class Driver { public static void main(String[] args) throws Exception { int[] numbers, counters; Histogram hist = new Histogram(); numbers = hist.readIntArrayFromFile("data-8.3.txt"); counters = hist.initializeCounterArray(numbers); hist.displayIntArray(counters); } } The only error im getting from this is the " nextt = numbers[ix]; " part of the code. ive tried implementing some commands at the top but nothing worked. But does everything look good? So if you feel that the code is not good, please feel free to make any required changes. I appreciate everyone taking their time out of their day to help me out, it really means alot Thank you!
http://www.javaprogrammingforums.com/%20file-i-o-other-i-o-streams/12549-creating-program-reads-file-printingthethread.html
CC-MAIN-2014-10
refinedweb
483
58.32
" "TOMOYO Linux" is our work in the field of security enhancement for Linux. You can try TOMOYO Linux 1.5.1 on Ubuntu 7.10's Live CD Changes from previous posting. * Made patches against latest -mm tree. This time, we made patches for -mm tree. Documents about installing and experiencing TOMOYO Linux are available at . * Avoid namespace_sem deadlock. To avoid the possibility of AB-BA deadlock (see for detail), we made patches not to access namespace_sem from LSM. Instead, we made some wrapper functions to pass "struct vfsmount" to LSM functions in a way of associating "struct vfsmount" with "struct task_struct" suggested at... . We would like to merge either AppArmor's "Pass struct vfsmount to ..." patches or our patches marked as [01/18], [02/18], [03/18] into mainline kernel so that AppArmor and TOMOYO Linux can safely access "struct vfsmount" from LSM. * Avoid rcu_read_lock() by inserting mb() when appending to list. I heard from an embedded system developer that holding RCU's read lock for long time affects response time since it disables preemption. Since list elements are append-only and nobody needs to refer ->prev element, we made patches not to call rcu_read_lock() by replacing smp_wmb() with mb(). * Don't send access logs to auditing system. TOMOYO Linux generates two types of logs. One is access logs in the form of policy file. The other is other messages like warning/info. We were sending both logs to auditing system. But some users complain about the flooding of access logs on the console. Thus, we decided to stop sending access logs to auditing system and removed AUDIT_TMY_GRANTED and AUDIT_TMY_REJECTED from include/linux/audit.h . Now, we are sending access logs to /sys/kernel/security/tomoyo/ interface. Logs other than access logs are sent to auditing system or printk() depending on kernel config. * Added capabilities support. TOMOYO Linux 2.1 now supports capabilities supported by TOMOYO Linux 1.5.1 . But some of them doesn't work due to LSM limitation (i.e. missing hooks). Patches consist of four types. * [TOMOYO 01-03/18]: Essential modifications against -mm kernel. * [TOMOYO 04-16/18]: LSM implementation of TOMOYO Linux. * [TOMOYO 17/18]: Makefile and Kconfig. * [TOMOYO 18/18]: Optional modifications against -mm kernel. -- Tetsuo Handa - To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to majordomo@vger.kernel.org More majordomo info at Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/258905/
crawl-002
refinedweb
410
60.61
Opened 7 years ago Closed 6 years ago #15049 closed enhancement (fixed) Some topological graph constructors Description (last modified by ) Some graphs which were missing in #9136. And I don't want to miss another occasion to say that I hate topological graphs. Theirs embeddings are the ugliest things on earth. Nobody should study topological graphs. It has to be bad for karma. - Horton Graph : - Kittell Graph : - Markstrom Graph : - Sousselier Graph : - Poussin Graph : - Tutte Graph : - Wiener-Araya Graph : Anyway... And we are almost done with the graphs from #9136 (short of Tutte's fragment, which I doubt to be of any use independent from Tutte's graph which this patch implements). Another patch on Snarks will follow, today or tomorrow. Nathann Change History (20) comment:1 Changed 7 years ago by - Branch set to u/ncohen/15049 - Status changed from new to needs_review comment:2 Changed 7 years ago by comment:3 Changed 7 years ago by - Milestone changed from sage-5.12 to sage-6.0 comment:4 Changed 7 years ago by comment:5 Changed 7 years ago by I just updated the branch by merging the patch with 5.12.beta1, though the link toward the Markstrom graph was okay on my side O_o Nathann comment:6 Changed 7 years ago by Oh, and ... yeah, we don't have a is_hypohamiltonian method yet, but as the only way I know to code it is to call is_hamiltonian n+1 times, I'm not that eager to write it unless I really need it for small instances :-P Nathann comment:7 Changed 7 years ago by for markstrom, the link is ok, but I have tried to see the doc in the notebook, and it was wrongly formatted comment:8 Changed 7 years ago by HMmmmmm... The.... Ahem. Notebook.... Does not run anymore on my version of Sage O_o Nathann comment:9 Changed 7 years ago by there is the same kind of problem in the notebook with graphs.GrotzschGraph?? (namely the doc is not shown in a formatted way) I suspect that the ö of Grötsch and of Markström may be involved. comment:10 Changed 7 years ago by Hmmmmm... I can't run the notebook on my git version of Sage, and my mercurial version of Sage works fine with the Grotsch graph. This being said, if it comes from weird accents I guess that it counts as a notebook bug. Could you try writing a function in the notebook which uses a weird accent, and get its documentation next to see if it works ? Nathann comment:11 Changed 7 years ago by indeed, this happens also with the function def pomme(x): """ return the famous function pömme (`See there <>`_) EXAMPLES:: sage: pomme(4) 5 """ return x+1 and it works when replacing the ö by o. Should I open a ticket ? comment:12 Changed 7 years ago by there is a typo "Wikpedia" in Sousselier doc comment:13 Changed 7 years ago by Updated ! And yep, I think you should open a ticket but I have no idea where.. I don't even think that the notebook is actually part of Sage O_o Nathann P.S. : I rewrote the last commit, I did not add a new one. comment:14 Changed 7 years ago by - Reviewers set to Frédéric Chapoton - Status changed from needs_review to positive_review ok, good enough for me. comment:15 Changed 7 years ago by - Commit set to 6ad238b9de481c202c1acdb9703b7a9aa65e67b9 - Status changed from positive_review to needs_review Branch pushed to git repo; I updated commit sha1 and set ticket back to needs_review. New commits: comment:16 Changed 7 years ago by I just rebased it... I hope it was effective :-/ Nathann comment:17 Changed 6 years ago by - Commit changed from 6ad238b9de481c202c1acdb9703b7a9aa65e67b9 to 3025ccaaf3bb5ffef92298d4d9fc175287cd9d61 Branch pushed to git repo; I updated commit sha1. Last 10 new commits: comment:18 Changed 6 years ago by - Status changed from needs_review to positive_review ok, let me say "good to go" again.. comment:19 Changed 6 years ago by - Milestone changed from sage-6.0 to sage-6.1 comment:20 Changed 6 years ago by - Resolution set to fixed - Status changed from positive_review to closed there are some problems in the web links in By the way, it seems that we do not have a is_hypohamiltonian method yet.
https://trac.sagemath.org/ticket/15049
CC-MAIN-2020-16
refinedweb
722
67.59
Developers and businesses today are using more SaaS experiences than ever before. Many users of SaaS services quickly find themselves in a position where they need to customize and bring the features of these SaaS services into their line of businesses applications. The first place to look for extending a SaaS service is a PaaS service, like Azure App Service. With Azure App Service, simple yet important features like enterprise grade Authentication or an agile dev ops development cycle work out of the box. Azure, and in general at Microsoft, have tons of ways of integrating with other services; one of the most powerful ways is Azure App Service WebJobs. In this blog post, we'll explore using a WebJobs Extension to talk to Slack. Slack is a messaging app for teams which has an awesome integration story using their "Real Time Messaging" API or their incoming & outgoing webhooks. Using the WebJobs SDK, we can listen to outgoing and "slash command" webhooks from Slack to initiate processes inside my applications. We can also, from within the SDK, send messages directly into Slack using a Custom WebJobs Extension that I wrote in less than a day. Let's get to the code. Get the code for the sample If you want to follow along in the source code, I encourage you to fork and clone the azure-webjobs-sdk-extensions-slack GitHub repository. You can also learn how to get the NuGet for this sample from the GitHub repo. Using WebJobs to send Message to Slack WebHooks To send messages into Slack, it's just an HTTP call to the incoming webhook endpoint, after I've set up that endpoint from the Slack custom integrations menu for Inbound webhooks. Using the Azure WebJobs extension for Slack, we can easily format and send those messages to Slack from within the various automated tasks we've got going for our applications. In some of my teams, we've used Slack to help monitor questions from our various Stack Overflow tags and forums, as well as, customer feedback from User Voice. While there are lots of ways to send data into Slack from services such as IFTTT, whenever some custom code needs to be written, it can be arduous to find a place to host that code. Let's look at how easy it is to send a message to Slack from WebJobs. To get started using the Azure WebJobs Extension for Slack after we've added the reference to our project, we need to enable it in the WebJobs JobHost configuration. var config = new JobHostConfiguration(); var slackConfig = new SlackConfiguration(); // These are optional and will be applied if no other value is specified. slackConfig.WebHookUrl = ""; // IT IS A BAD THING TO HARDCODE YOUR WEBHOOKURL, USE THE APP SETTING "AzureWebJobsSlackWebHookKeyName" slackConfig.IconEmoji = ":taco:"; slackConfig.Username = "Destroy All Humans"; slackConfig.Channel = "#bots_only_no_hummies"; config.UseSlack(slackConfig); var host = new JobHost(config); // The following code ensures that the WebJob will be running continuously host.RunAndBlock(); Once we've enabled that, we can use the Slack binding within our WebJobs Functions. Getting started using the Slack binding in a function is really simple. All you need to do is add the Slack binding to a WebJob SDK function. public void SimpleSlackBinding([WebHookTrigger] Message m, [Slack(Text = "{Text}", IconEmoji = "{IconEmoji}")] SlackMessage message) In the above snippet, we've added a Slack binding which will create a SlackMessage with the global default settings and text and iconEmoji over-written with properites from the Message POCO which is generated by our trigger (in this case, a webhook, but it could be any trigger). The SlackMessage object that is provided is what will be sent to Slack. After the function has finished the, it will parse the content to a JSON body and POST it to your Slack webhook URL, that was specified earlier. Here's a sample with the full functionality exposed: public void FullSlackBinding([WebHookTrigger] Message m, [Slack(Channel = "{Channel}", IconEmoji = "{IconEmoji}", IsMarkdown = false, Text ="{Text}", Username = "{Username}", WebHookUrl = "{WebHookUrl}")] SlackMessage message, TextWriter log ) { // Further customize Slack Message here. i.e. add attachments, etc. // More info on the SlackMessage object on the GitHub project: // Continue to set/manipulate properties on the Slack Message, programatically message.Text += "WebJobs are Grrrreat!"; message.IconEmoji = ":troll:"; // For example, add attachments. See the Slack API docs for more info: message.Attachments.Add(new SlackAttachment { Fallback = "Required plain-text summary of the attachment.", Color = "#36a64f", pre class="prettyprint"text = "Optional text that appears above the attachment block", AuthorName = "Bobby Tables", AuthorLink = "", AuthorIcon = "", Title = "Slack API Documentation", TitleLink = "", Text = "Optional text that appears within the attachment", Fields = new List<SlackField> { new SlackField { Title = "Priority", Value = "High", Short = true }, new SlackField { Title = "Assigned", Value = "Bobby", Short = true } }, ImageUrl = "", ThumbUrl = "" }); } Using WebJobs to listen to Slack Webhooks Sending message to Slack is great, but one of the coolest scenarios is using Slack to initial workflows inside your application. To achieve this with WebJobs, we can use the WebHookTrigger binding. As we can see in the pre class="prettyprint"vious example, we can bind a WebHookTrigger which will output a POCO object for our service to use. public async Task SlackIniatedWebHook([WebHookTrigger] WebHookContext context In the code sample above, you can see that we're able to create a webhook in a simple fashion by adding the WebHookTrigger attribute. The path to access this webhook is styled like: https://{uid}:{pwd}@{site}/api/continuouswebjobs/{job}/passthrough/{*path}. To manually construct your webhook URL, you need to replace the following tokens: - uid : This is the user ID from your publishing credentials. You can download your publishing credentials from the portal as detailed in this blog post - pwd : This is the password from your publising credentials - site : Your SCM site (e.g. myapp.scm.azurewebsites.net) - job : The name of your Continuous WebJob - path : This is the route identifying the specific webhook function to invoke. By convention, this is {ClassName}/{MethodName}, but can be overridden/specified explicitly via the WebHookTriggerattribute. Let's say we want to have our webhook listened on slack/webhook. We can do this by passing the path as part of the attribute. public async Task SlackIniatedWebHook([WebHookTrigger("slack/webhook")] WebHookContext context The full documentation for the WebHookTrigger can be found on the WebJobs SDK Extensions GitHub Repo. On the GitHub, you can learn the ins and outs of the WebHooks Trigger. We'll expand on this sample in the next section where we bring together incoming and outgoing Slack webhooks. Bringing it all together: Slack Slash Commands Let us take a look at what a more end to end situation might look like. We can use a slash command to call a WebJob via the WebHooksTrigger and then kickoff a workflow which we manage via Azure Storage Queues. The the workflow can then respond to the reply url that the slash command provides. Something to keep in mind is that currently the reply url is only valid for about 5 minutes, so if our job is going to run longer than that, we should just use a traditional incoming webhook. In this example, we'll have a slash command which accepts two integers, one which dictates the number of work items and another which is the amount of work to be done. Let's start with the WebHookTrigger. We want to have the WebHookTrigger listen on slack/webhook and we want to output a set of new Queue messages via a Queue attribtue. public async Task SlackIniatedWebHook([WebHookTrigger("slack/webhook")] WebHookContext context, [Queue("SlackWork")] ICollector<SlackWork> messages ) With our function parameters and attributes set up, let's think about the busines logic inside the function. We want to read the two integers in from the command text and create the number of queue work items we've been told to create. We'll create a helper POCO class which repre class="prettyprint"sents the work to be done. public class SlackWork { public int id { get; set; } public string username { get; set; } public int work { get; set; } public string replyUrl { get; set; } } We will also create a helper function for parsing Slack since it uses a x-url-form-urlencoded body, and WebJobs doesn't yet auto-parse that into a POCO for us. private bool TryParseSlackBody(string body, out NameValueCollection nvc) { body = body.Replace('\n', '&'); body = body.Replace("\r", ""); nvc = System.Web.HttpUtility.ParseQueryString(body); return nvc.Count > 0; } Now that we have those, we can write our function to parse the command text, handle error cases, and create the queue work items. public async Task SlackIniatedWebHook([WebHookTrigger("slack/webhook")] WebHookContext context, [Queue("SlackWork")] ICollector<SlackWork> messages ) { // Try and parse the Slack Message Body with simple helper method NameValueCollection nvc; if(TryParseSlackBody(await context.Request.Content.ReadAsStringAsync(), out nvc)) { Regex rgx = new Regex("(\\d+) (\\d+)"); Match match = rgx.Match(nvc["text"]); int count; int work; if(int.TryParse(match.Groups[1].Value, out count) && int.TryParse(match.Groups[2].Value, out work)) { for (int i = 0; i < count; i++) { messages.Add(new SlackWork { id = i, work = work, replyUrl = nvc["response_url"], username = nvc["user_name"] }); } // All good, quickly send an affirmative response context.Response = new Httpre class="prettyprint"sponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Message received! Processing ...") }; } else { // Not good, quick send a negative response context.Response = new Httpre class="prettyprint"sponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Incorrect format - please pass two numbers along - i.e. /cmd 2 30") }; // We can stop here for the failure case return; } } else { // Not good, quick send a negative response context.Response = new Httpre class="prettyprint"sponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("Something went wrong. :(") }; // We can stop here for the failure case return; } } Now for processing the work items, we need to have a QueueTrigger which will launch on new Queue items. Our function will sleep for the amount of "work" passed to it (plus some randomness factor we'll add), if the work to be done is greater than 10, we'll change the Slack emoji to :tada:. We can create the text for the Slack message via the function parameters and attribtues. public void ProcessSlackWork([QueueTrigger("SlackWork")] SlackWork work, [Slack(WebHookUrl = "{replyUrl}", Text = "Item: {id} finished processing {work} seconds of work.", IconEmoji = ":sleepy:", Channel = "@{username}")] SlackMessage slack, TextWriter log ) { log.WriteLine($"Processing id: {work.id} - working for {work.work} seconds"); if(work.work > 10) { slack.IconEmoji = ":tada:"; } int sleepFor = (work.work + (int)(.2 * work.work * (new Random()).NextDouble())) * 1000; log.WriteLine($"Processing id: {work.id} - actually working for {sleepFor} seconds, because of some made up, factor of error"); Thread.Sleep(sleepFor); } We can test this locally by running the WebJob and hitting localhost:3000/slack/webhook. You can pass a sample body that looks something like below: token=gIkuvaNzQIHg97ATvDxqgjtO team_id=T0001 team_domain=example channel_id=C2147483705 channel_name=test user_id=U2147483697 user_name=Steve command=/cmd text=3 30 response_url= Next, we deploy the WebJob to an Azure App Service. To do this, we can follow the steps for deploying a WebJob to Azure via Visual Studio on Azure.com. Finally, let's add the slash command. Go to the Slack apps directory and click on "configure" in the top right. From here, you need to select your Slack team, and then navigate to "Custom Integrations". From this menu, you can navigate to "Slash Commands" and click on "Add Configuration". Follow the steps on the page and add a URL with the pattern described in the section above. You can use whatever /command keyword you'd like to. Now you can call your WebJob by calling your command with two integers representing the amount of work to be done and how long to work: /cmd 3 30. Learn more To learn more, check out the following links:
https://azure.microsoft.com/ru-ru/blog/using-the-azure-webjobs-sdk-to-create-custom-slack-extensions/
CC-MAIN-2019-43
refinedweb
1,952
54.42
Convert Specific Worksheet Cells to Image This section aims at providing a detail solution for developers on how to convert specific worksheet cells to image via this .NET Excel component Spire.XLS for .NET in C#, VB.NET. This Excel library helps us quickly convert certain excel cells to different image formats such as jpeg, png, bmp, tiff, gif, ico, emf, exif etc. When we convert worksheet to image, Spire.XLS for .NET provides us a method: Spire.Xls.Worksheet.SaveToImage(int firstRow, int firstColumn, int lastRow, int lastColumn); As we see, there are four parameters passed in this method. These four parameters determine the certain range of cells. After deciding the cell range, we can successfully convert cells to image. Now, let us see the whole task step by step. Step 1: Create a template Excel Workbook in MS Excel I create a new Excel file in MS Excel and add some data which have different formats in the first sheet, here is a screenshot of created file. Step 2: Download and Install Spire.XLS for .NET Spire.XLS for .NET is an Excel Api which enables users to quickly generate, read, edit and manipulate Excel files on .NET Platform. Here you can download Spire.XLS for .NET and install it on your development computer. After installing it, Spire.XLS for .NET will run in evaluation mode which is the same when you install other Spire components. This evaluation mode has no time limit. Step 3: Create a project and Add References We can create a new project of Console Application either in C# or VB.NET. I create in C#, but we can choose VB.NET too. In this project, we need to add references in our project. Apart from adding System.Drawing, we will use Spire.XLS for .NET, so we also have to add Spire.Xls.dll, Spire.Common.dll and Spire.License.dll in our download Bin folder of Spire.Xls. Here we can see the default path: "..\Spire.XLS\Bin\NET4.0\Spire.XLS.dll" Step 4: Convert Specific Worksheet Cells to Image In this step, first we can initialize a new object of the class Spire.Xls.Workbook, then, load the template Excel file. Since I want to convert cells in the first sheet to image, I need get the first worksheet data in Excel file. You also can get other worksheet data. Finally specify cell range and save the cells in the range as image file. Spire.XLS for .NET supports 12 image formats: Bmp, Emf, Equals, Exif, Gif, Icon, Jpeg, MemoryBmp, Png, ReferenceEquals, Tiff and Wmf. using System.Drawing; using System.Drawing.Imaging; using Spire.Xls; using Spire.Xls.Converter; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Initialize a new Workbook object Workbook workbook = new Workbook(); //Open Template Excel file workbook.LoadFromFile(@"..\excel to image.xlsx"); //Get the first wirksheet in Excel file Worksheet sheet =); } } } Imports System.Drawing Imports System.Drawing.Imaging Imports Spire.Xls Imports Spire.Xls.Converter Namespace ConsoleApplication1 Class Program Private Shared Sub Main(args As String()) 'Initialize a new Workbook object Dim workbook As New Workbook() 'Open Template Excel file workbook.LoadFromFile("..\excel to image.xlsx") 'Get the first wirksheet in Excel file Dim sheet As Worksheet =) End Sub End Class End Namespace Result Task After executing above code, cells in the first worksheet named "Sheet1" has been converted to three images. They are named "image1.png", "image2.jpeg" and "image3.bmp". You can see them as below: In this section, I have introduced how we can convert specific cells to image by using Spire.XLS for .NET. I sincerely hope it can help you and give you some insight. Spire.XLS for .NET offers fast speed, high efficiency and reliability to satisfy development application requirements. As you see above, the results do show that Spire.XLS for .NET benefit customers from years of research. We appreciate any kind of queries, comments and suggestions at E-iceblue Forum. We promise a quick reply within minutes or hours as we can.
https://www.e-iceblue.com/tag/excel-to-image.html
CC-MAIN-2021-17
refinedweb
675
68.36
Resolving Network Bottlenecks Typical causes for network bottlenecks are an overloaded server, an overloaded network, or a loss of network integrity. The following techniques can help to address some of these problems. If communicating over Token Ring, FDDI or switched Ethernet networks, attempt to balance network traffic by distributing client connections across multiple network adapters. When using multiple network adapters, make sure that the network adapters are distributed among the PCI buses. For example, if you have four network adapters with three PCI buses, one 64-bit and two 32-bit, allocate two network adapters to the 64-bit bus and one adapter to each 32-bit bus. Splitting the adapters across multiple Ethernet segments is an effective way to eliminate an overloaded network if the physical environment is switched Ethernet, and all adapters are on the same physical segment. For more information about adding network adapters, see "Adding Network Adapters" later in this chapter. Use adapters with the highest bandwidth available for best performance. Note that increasing bandwidth increases the number of transmissions that are taking place and in turn makes more work for your system, including more interrupts being generated. Remove unused network adapters to reduce overhead. Use adapters that support task offloading capabilities (checksum offloading, IPSEC offloading, and large send offloading). If your network uses multiple protocols, place each protocol on a different adapter. Make sure to use the most efficient protocols, especially ones that minimize broadcasts. Notice that reducing the number of protocols installed can increase performance. High rates of interrupts from network adapters can reduce performance. Using network adapters that batch interrupts by means of interrupt moderation can improve this performance problem, provided the adapter driver supports this capability. Another option is to bind interrupts arising from network adapters to a particular processor to improve performance. When using Interrupt Filter to bind a network adapter to a set of processors. For more information about processor affinity and Interrupt Filter, see "Measuring Multiprocessor System Activity" in this book. For more information about Interrupt Filter, see online Help on the Windows 2000 Resource Kit companion CD. Divide your network into multiple subnets or segments, attaching the server to each segment with a separate adapter. This reduces congestion at the server by spreading server requests. Although binding order is relevant on the client computer, there is no reason to reorder server bindings because the server accepts incoming connections based on the protocol used by the client computer. Use offline folders to work on network applications without being connected to a network. Offline folders make use of client-side caching, thereby reducing network traffic. Adding Network Adapters You need to disable some bindings to allow network adapters in the same computer on the same network segment to operate correctly when using NetBEUI. The reason for this is that, if you have two adapters on the same segment and install NetBEUI, the computer sees duplicate computer names due to the resulting NetBIOS name conflict, generates an error, and fails to start system services correctly. This also occurs on bridged or switched networks. In this case you also see the Event ID 2505 error in the event log, indicating a duplicate name on the network. The error might appear in the event log as either of the following messages: Event ID : 2505 The server could not bind to the transport/device/netbt_ adapter_driver because another computer on the network has the same name. The server could not start. Event ID : 2505 The server could not bind to the transport/device/nbf_ adapter_driver because another computer on the network has the same name. The server could not start. This problem does not affect routable protocols such as TCP/IP or AppleTalk because when you install or reconfigure them, you have to choose a network adapter, and this automatically disables the protocol's bindings to other adapters. In addition, the operating system treats NetBT as a namespace and need not be disabled. You can manually configure multiple network adapters in a computer by disabling NetBEUI bindings to network adapters other than the one you want to use for the NetBEUI protocol. To do this, disable the following bindings: Server to NetBEUI protocol to adapter_driver to adapter Workstation to NetBEUI protocol to adapter_driver to adapter NetBEUI protocol to adapter_driver to adapter NetBIOS interface to NetBEUI protocol to adapter_driver to adapter When you have disabled all of these bindings, network operations can proceed. In addition, if all clients have equal network access to any of the network adapters on the multihomed computer, and all of the client and server network adapters are on the same subnet, you can help to distribute the client connections between the server network adapters by adding the RandomAdapter registry entry in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet \Services\Netbt\Parameters . In this way, each network adapter will still respond to the name query, but each network adapter will choose the IP address randomly from all the network adapters on the server. This helps to distribute network sessions among the network adapters, but does not necessarily balance the load because network traffic might vary greatly between the sessions. .gif).
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc938651(v=technet.10)?redirectedfrom=MSDN
CC-MAIN-2020-05
refinedweb
855
50.16
1232/aws-unused-elastic-ip-charges Elastic IP According to the answer from Shibashis you will be charged: $0.005 x 24hr x 30 days = $3.60 / months / per Elastic IP address not associated with $0.005 x 24hr x 30 days = $3.60 / months / per Elastic IP address not associated with DynamicURL You may consider other option that does not require for an assignment of an Elastic IP. There is a service called DynamicURL that change IP Address on A of your domain dynamically.... Some services are free. You need only to set NAME SERVER of your domain. Following are the example script to run each time an instance is started: Wget wget -q --read-timeout=0.0 --waitretry=5 --tries=400 \\ --background... php <?php file_get_contents('...'); ?> Python #!/usr/bin/python import urllib page = urllib.urlopen("..."); page.close(); Perl #!/usr/bin/perl my $uri = '...'; use IO::Socket; my ($domain, $path) = $uri =~ m{^https://([^/]*)(.*)}; $path = '/' unless length $path; my $sock = IO::Socket::INET->new( Proto => 'tcp', PeerAddr => $domain, PeerPort => '80', ) or die "can't connect to $domain\n"; my $CRLF = "\x{0d}\x{0a}"; print $sock "GET $path HTTP/1.0$CRLF$CRLF"; close($sock); If you are behind proxy and your real IP is set in the header X-Forwarded-For you need to add &proxy=1 at the end of the DynamicURL. Depends! Every instance comes with its own ...READ MORE A public IP address is assigned to ...READ MORE Yes, you can use Auto Scaling without ...READ MORE There are two ways in which instances ...READ MORE Choose Option A. The best way of ...READ MORE IP address is used to communicate with ...READ MORE yes once you store it in (AWS) ...READ MORE The error message has nothing to do ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/1232/aws-unused-elastic-ip-charges
CC-MAIN-2021-04
refinedweb
302
77.64
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video. Testing React Components with Enzyme25:35 with Jared Schaab Enzyme is an open source JavaScript library developed by Airbnb engineering. In this workshop, you will use Mocha and Enzyme to test your React components. - 0:00 [MUSIC] - 0:04 Before react, unit testing of using your web application was extremely cumbersome. - 0:09 Now with the emergence of react, we are able to write our views in JavaScript. - 0:13 This makes setting up and running unit tests much simpler. - 0:17 Hi, I'm Jared Schaab, a guest teacher for Treehouse. - 0:20 In this video, - 0:21 we'll be going over how to set up unit tests that target your react components. - 0:26 To accomplish this, we'll be making use of mocha, babel and enzyme. - 0:30 After, we'll wrap up with a discussion on how to structure your tests within your - 0:34 project and - 0:35 some debugging options for when a failing test needs more investigation. - 0:39 In this video, we'll be using a GitHub profile widget that is designed to show - 0:43 a person's GitHub profile and their most popular repositories. - 0:47 I do assume that you are already familiar with MPM, react, ES6 and babel. - 0:52 If not, feel free to check out the links provided in the teacher's notes. - 0:55 Now before we start running our unit tests, - 0:57 we need something that knows how to run them. - 0:59 Micha is a fully featured JavaScript test framework for - 1:02 running our tests on Node.js and in the browser. - 1:05 Just a note that as a personal preference, I'll be using chai.js's expect assertion - 1:10 library instead of the built-in Node.js assertion library. - 1:13 So, let us begin by installing mocha and chai. - 1:27 To start off, we're going to write a very simple test just to get the feel for - 1:31 how mocha works. - 1:34 Under our source folder, we are gonna add a new file called simpleTest.spec.js. - 1:48 Now that we have our simple test, - 1:50 there are a couple of things that I would like to draw your attention to. - 1:54 The first being the general structure of the tests. - 1:57 Within a test file, you typically have a single root described function. - 2:03 And within it, you nest your it functions. - 2:08 Now you might be asking yourself, well, what is describing? - 2:10 What is it? - 2:11 What are the purposes or what is the purpose of these functions? - 2:15 Well, you can think of the described function as a test suite - 2:18 where you're describing what is under test. - 2:21 You'll see that as we get farther along, this is typically our react component. - 2:27 The it function is a description of our tests. - 2:31 So in this specific case, - 2:33 we are saying that our add function should add positive numbers. - 2:37 Now to run this test, we have two options. - 2:40 We can open up the command line and we can utilize the mocha cli, which as we'll see, - 2:45 when we get a little farther along can become extremely verbose. - 2:50 The second thing we can do is we can add a alias within the script section - 2:55 of our package.json and I prefer to use this method, - 2:59 because it allows us, as I said to alias our command and - 3:03 we can actually reuse commands within other aliased commands. - 3:07 So, let's hop over to our package.json and set it up. - 3:15 So here, we'll add a "test" alias and - 3:20 here we will write mocha and I am telling mocha to - 3:25 look under our source folder and a new folder under that for - 3:31 any file that has the extension spec.js. - 3:36 Now so instead of typing this out every single time - 3:40 that we wanna run a test, we can simply run mpm run tests. - 3:45 So, let's go over to our command line and execute as test. - 3:53 Success. - 3:54 Now that we have seen how to use mocha and we have simple tests, - 3:58 we can move on to more real world scenarios. - 4:01 Assuming that you're running your react components using JSX syntax, - 4:05 babel should be setup in your project already. - 4:07 Babel not only allows you to transpile your react components to JavaScript, - 4:11 it also allows you to use the latest JavaScript features today. - 4:16 Now before you get all futuristic with our JavaScript in our tests, - 4:20 one thing to note is that out of the box, mocha is only is only ES5 aware. - 4:25 So, we need to tell mocha how to read the ES6 syntax within our test. - 4:31 To do this, we are going to install babel register, so - 4:34 that mocha can use this to transpile our tests on the fly. - 4:53 Excellent. - 4:54 So, we need to tell mocha how to use babel register. - 4:57 To do this, - 4:58 we're gonna add the compilers flag to our test command in our package.json. - 5:07 So here, we're simply gonna pass it, compilers and - 5:14 we're gonna give it js:babel-register. - 5:19 Save that. - 5:21 So now we can go back over to our simpleTest.spec.js and - 5:26 we can actually update this to use a new ES6 feature like say, - 5:32 plentas or arrow functions. - 5:41 We can even do that up here. - 5:53 So let's pop back over to our command line and try, and run these tests again. - 6:05 Voila, we now have passing unit tests with ES6 syntax. - 6:10 Now that we have mocha and babble setup, let's dive in and - 6:13 start testing our components. - 6:15 When testing our react components, - 6:18 we're gonna make use of a test utility library written by airbnb called enzyme. - 6:24 This simplifies the testing of our react components. - 6:27 It allows you to target three test cases. - 6:29 Testing your component in isolation, testing the lifecycle functions of your - 6:34 component and testing the rendered HTML of your component. - 6:37 It provides a familiar jQuery-like API for manipulation and traversal. - 6:42 One thing I will mention is that enzyme has a peer dependency on react - 6:46 add-ons test util, so we'll be installing that as well. - 7:09 Now that we have enzyme installed, - 7:11 the first API we're gonna take a look at is the shallow rendering API. - 7:14 It is useful for testing components in isolation without worrying about the side - 7:18 effects produced by any of its child components. - 7:21 The shallow a function returns to us a shallow wrapper object - 7:24 that allows us to query the rendered output. - 7:27 Let's start by taking a look at our repositories component. - 7:32 Where we're gonna be focusing our testing efforts is on this piece of - 7:36 functionality here. - 7:38 What is happening is we are actually sorting our repositories by the number of - 7:41 stars that they have and then selecting the top number of - 7:46 repositories specified by this top prop. - 7:51 So, the first thing we'll do is add a repositories spec.js - 8:04 We will then import React, - 8:09 enzyme and expect. - 8:19 From there, we're also gonna need to import our repositories component. - 8:37 Now, we're gonna setup our route described function. - 9:01 And we're gonna create some test data here, - 9:04 because we'll need to test the list of repositories. - 9:13 So here, I created a list of repos with varying number of stars. - 9:24 And now, we'll write our first test. - 9:30 So our first test, we're gonna validate that the rendered number of - 9:36 repositories that is specified by the top prop is actually what we expect. - 9:43 Now one thing you're gonna notice here on line 43 is we are using - 9:48 this wrapper.find and we're looking for the repository. - 9:53 Now, here's one of the really neat things. - 9:54 Using our shallow wrapper, - 9:56 we can query the rendered output in several different ways. - 9:58 In this case, we're actually using a repository component. - 10:04 So to make sure this works, we're gonna have to go back up and - 10:08 import the repository component. - 10:19 And that should give us that there. - 10:22 All right, so let's save that, and let's go back to our command line and - 10:27 run the test and see what happens. - 10:37 Excellent, we get two passing tests, the add test from earlier and - 10:41 our repository test that we just added. - 10:44 Now, another cool thing that we can do with our shallow wrapper is we can - 10:49 actually validate the props that are passed into the component. - 10:53 So let's go back to our test and add a test that accomplishes that. - 11:05 So what we're doing here is on line 48 is we are sorting our test data in a way - 11:12 that we would expect our repositories to be sorted in the component. - 11:20 Once we've mounted our repository component, - 11:24 we are then finding all the repositories on line 51. - 11:28 We're finding all the repository components that have been rendered by - 11:32 the repositories component. - 11:35 And from there, we are just iterating over each of those components and - 11:40 validating that the prop that has been passed to the repository - 11:45 equals the equivalent property on our cast data. - 11:50 So now that we've added that, let's hop over to the command line and - 11:54 run that again. - 12:00 Fantastic, so now we've just validated that our repositories - 12:05 component displays the correct number of top repositories. - 12:10 And we've also validated that it sorts them properly. - 12:14 The next API we'll test out is the full DOM rendering with the Mount API. - 12:18 Mount is useful for testing components with lifecycle events or - 12:21 that interact with DOM APIs. - 12:23 So one thing we'll have to do is either run our tests inside the browser, or - 12:28 we can utilize a library called JS DOM to implement a headless browser - 12:32 in JavaScript. - 12:33 For the purposes of this workshop, we will be using JS DOM. - 12:37 So let's go to our command line and install JS DOM. - 12:47 Excellent, so now let's go over to our project, and - 12:50 we're gonna add a JavaScript file, which is our headless browser implementation. - 12:56 So in our project, we are gonna add a new folder - 13:01 called scripts, and underneath there, - 13:05 we're gonna add a file called mocha_runner.js. - 13:13 So here's our headless browser implementation. - 13:16 Now what we need to do is we need to instruct mocha to use this file. - 13:21 So we're gonna head over to our package.json. - 13:24 And we are gonna update our test command. - 13:29 So, what we're gonna do is we're gonna remove compilers, - 13:34 the compilers flag, and we're gonna add the require flag. - 13:45 So the first question you might be asking yourself is, - 13:48 well, what did we do that would allow us to remove our compilers flag? - 13:52 So how is mocha gonna understand our new fancy es6 syntax? - 13:58 Well, if we go back over to the mocha_runner file, we'll notice at - 14:02 the bottom, we're requiring the babel-core/register here on line 20. - 14:07 And this does the same thing as including the babel register - 14:12 as a part of the compiler's flag. - 14:14 So now what will happen is our test files will continue to get - 14:17 transpiled on the fly. - 14:19 So let's go ahead and add our first test for - 14:25 the GitHub widget component, and we'll do a save here and make sure that sticks. - 14:31 So if we look at our GitHub widget component, - 14:36 you will see that we are on line 34, we are using componentdidMount which is - 14:40 one of the lifecycle events that react allows you to tap into. - 14:45 So let's go ahead under our source, our source folder, - 14:49 and let's add a GithubWidget.spec.js. - 15:47 Okay, so one thing we're gonna notice here is that the way - 15:52 we use the mount API is fairly similar to the shallow API. - 15:58 But instead of working with a shallow wrapper, - 16:01 we'll be working with the react wrapper. - 16:04 For our first test, - 16:06 all we're gonna validate is that we are rendering all of our sub-components. - 16:12 So if we go back to our GitHub widget really briefly, we'll notice that - 16:18 as part of our GitHub widget component, we're rendering a UserDetails, - 16:23 UserStats, our repositories, and our footer. - 16:29 So in our test, we're gonna validate that all these things are showing up. - 16:35 Now to make this test work, we're also gonna have to import our other components. - 17:18 Okay, now that we have all our sub-components imported, - 17:23 let's go over to our command line and run this test. - 17:33 Excellent, so we can see here that our GitHub widget did render all of our - 17:38 sub-components that we expected. - 17:41 So, as I mentioned, another thing that the mount API allows us to do is to unit - 17:46 test our lifecycle methods. - 17:48 To do this, we will utilize a library called sinon, - 17:51 which will allow us to create spies, stubs, or marks. - 17:55 For simplicity's sake, I'm just gonna show how to create - 18:00 a spy on one of our lifecycle events and validate that it fired. - 18:05 So let's install sinon. - 18:19 Perfect, sinon is installed, and - 18:21 we'll go back over to our project, and we will import. - 18:33 Okay, we've imported, now let's add our next test. - 18:39 Okay, so we can see here on line 28, we're creating a spy on - 18:44 our componentDidMount function that is part of the GitHub widget. - 18:50 We are then mounting our GitHub widget, and - 18:54 then we are then validating that the componentDidMount was called once. - 19:01 So we can go back over to, we'll save first, - 19:04 we'll go back over to our command line and we'll run this test. - 19:13 Awesome, finally, we have the render API. - 19:17 What the render API allows us to do is to test the static HTML that - 19:22 the component renders. - 19:24 Render under the hood uses Cheerio, - 19:27 which is a third party, like a JQuery Lite DOM manipulation library. - 19:32 And what we get back a Cheerio wrapper, and - 19:35 what we're gonna see is that we will use that Cheerio wrapper in the same - 19:40 way that we use a shallow wrapper or a react wrapper. - 19:46 So let's just hop right in, we're gonna look at our user image component, and - 19:49 we're gonna write a test. - 19:51 So let's open up our userImage component, and we can see that it's nothing fancy. - 19:56 We have a div and we return an image, and - 20:01 on that div, we have a class of gh-widget-photo. - 20:05 So as we've done before, under our src folder, - 20:09 let's create a Userimage.spec.js file. - 20:26 We'll import our UserImage component. - 20:55 Okay, so we're gonna see here that what we're testing with our UserImage - 21:00 component is that our root div element should have the gh-widget-photo class. - 21:07 And as I mentioned previously, we can see here on line 11 that we are using - 21:12 the render function in the same manner that we used the mountain shallow. - 21:18 We give it our component, which returns to us a wrapper. - 21:21 And then we utilize that wrapper to query the output. - 21:27 So, as I said, we're looking our root div, and we're getting the class on it, - 21:32 and we're making sure it is equal to the gh-widget-photo. - 21:36 So, let's say that, go over to our command line, and run this test. - 21:47 Success. - 21:48 So we can see here, we have our UserImage, - 21:50 should have a div element with a gh-widget-photo class. - 21:54 So that wraps up the three APIs that we have access to with Enzyme. - 22:00 So one thing you may be asking yourself is, - 22:03 when should I use each of these different APIs? - 22:06 So my rule of thumb for when you use these are to default to shallow. - 22:11 Shallow is going to accommodate the majority of the test cases that we - 22:15 wanna test against. - 22:18 If you have a staple component and you wanna test life cycle events, use mount. - 22:23 If you need to test a component that gets rendered on the server, or - 22:27 you have a component that just returns HTML, or, meaning, - 22:32 there's no nested components in it, you can use the render function. - 22:38 But before we wrap things up, - 22:40 I want to talk about where we should place our test files. - 22:44 If we hop over to our project very quickly, - 22:50 What you'll notice here is that I happen to put my spec files - 22:54 in the same folder as the rest of my components. - 22:58 Now you might be thinking that I did that as just more of a convenience thing, - 23:03 and you're actually partially correct. - 23:06 If we're look in our explorer here we can see that things get - 23:10 pretty crowded pretty quickly. - 23:12 What I don't like having to do is to waste time context switching and - 23:18 scrolling within my project. - 23:20 So, what I suggest doing is actually putting - 23:23 your spec files right next to the component under test. - 23:27 This allows us quick access to the tests. - 23:29 It gives us a quick indicator of whether something has been tested or not. - 23:33 And typically, when you're working on something, - 23:36 you're working on a specific feature. - 23:39 So, I would suggest putting your spec files besides a component under test. - 23:43 To wrap up, I wanted to give you a high level overview - 23:46 of some of the debugging options we have when our unit tests are passing. - 23:52 The first thing we can utilize, the old faithful is console.log. - 23:57 Both the shallow wrapper and the React wrapper provide to us a debug function - 24:01 which gives us a string representation of the rendered tree. - 24:06 So, what we could do, if we go over to our GithubWidget, - 24:10 assuming that this test was failing, what we could do is do a console.log. - 24:17 And we could do our wrapper.debug. - 24:21 And this would give us a little insight into what was being rendered. - 24:27 The next thing that we could do is we can actually utilize - 24:30 the built-in Node debugger. - 24:32 Now, to do that what we would actually do is we would head over to our package.json. - 24:42 And we would add the debug flag. - 24:47 And what this will allow us to do is put debugger statements within our test and - 24:51 have the debugger stop on those statements. - 24:54 And we'd have to interact with the debugger from the command line. - 24:58 Third, there's also a package called node-interceptor. - 25:02 I don't have time to go into how to set it up, but what node-interceptor allows you - 25:07 to do is it allows you to actually tap into the Chrome Dev Tools. - 25:13 Lastly, there are some IDEs, like WebStorm that actually have debuggers - 25:18 built-in that allow you to attach to breakpoints within the IDE. - 25:22 That wraps up unit testing our React components with Enzyme. - 25:26 I just wanted to say thank you very much for watching this video. - 25:29 And I hope you learned a lot. - 25:31 If you have any questions, again, feel free to leave those below.
https://teamtreehouse.com/library/testing-react-components-with-enzyme-3
CC-MAIN-2017-13
refinedweb
3,725
78.79
PHP: The Good Parts Book Review PHP has come a long way since its introduction 15 years ago. What began as a means for PHP creator Rasmus Lerdorf to display his resume to prospective employers visiting his personal website has blossomed into what many refer to as the Visual Basic of the web. As a result of its lengthy and highly successful history, numerous books have been written about it. How does O'Reilly's latest addition, PHP: The Good Parts, compare to this vast sea of PHP content? Read on to find out.What initially struck me about this book compared to the dozens of other PHP books I have read was how short and concise it is. Entire books have been written solely on the individual topics found in PHP: The Good Stuff. While I initially suspected the book was nothing more than a 'Learn PHP in a Day' clone, reading beyond the first two chapters proved otherwise. Yes, this book is a rapid review of the key aspects required to construct a PHP-driven website, but its combination of focused choices made and the lean presentation it packs delivers a potent punch compared to other condensed PHP books on the market. This book isn't just a collection of cut and paste snippets from other sources. Rather, it is written by an experienced PHP developer for those new to PHP and for skeptics like me who scoffed at PHP's original mishmash of business logic and presentation layer. Competition from other more elegant frameworks as well as the ire of seasoned PHP developers have pushed more manageable framework abstractions onto the language, though none of these are explored in detail in the book. Its intent is to highlight the key aspects of what makes PHP so compelling to a vast audience of web developers willing to overlook its shortcomings. The book starts off with the basics: data types, functions, strings and arrays. Objects are demonstrated in Chapter 6 and databases featuring MySQL make their mark in Chapter 7, followed by chapters covering email, PDF and report generation and PHP security (with special attention paid to the ever-prevalent cross-site scripting and SQL injection attacks). The final chapters cover PHP version 5.3 'Good Parts' such as namespaces, closures and the scary goto operator. The book concludes with a chapter covering regular expressions, SimpleXML, a sampling of PHP-capable IDE's (however, the choices of IDE's selected for the book was not as extensive or critical of their functionality and proposed value as I would have preferred) and suggested websites for interested readers to learn more. Commendably, the author includes an appendix on 'The Bad Parts', sharing the problems that PHP still plague developers with. Mad props to Peter for his courage to be honest with his audience. Overall, Peter MacIntyre does something with PHP: The Good Parts that other PHP books often fail to do. He gets readers excited about PHP by showing how easy and quick it is to use and how powerful its libraries can be. In fact, the book motivated me to write a PHP mashup for an Arduino project I am working on with my daughter. I was originally going to use Rails but decided that doing so would add way too much overhead for the simple web page generation functionality I needed. I whipped up a working PHP solution in no time, proving once again that it's always a good idea to be open to using the best tool for the job at hand. Title: PHP: The Good Parts Author: Peter MacIntyre Publisher: O'Reilly Media ISBN: 978-0-596-80437-4 Pages: 176 Cost: $29.99
http://www.drdobbs.com/tools/php-the-good-parts-book-review/228700382
CC-MAIN-2016-26
refinedweb
618
56.59
Answered by: genasm error message when adding DesignTimeAttributes.xmta to my project - This is weird. I have a Smart Device C# library that builds perfectly. When I add a DesignTimeAttributes.xmta to it and rebuild it I got the following error message: genasm.exe(1) : error There was an error finalizing type . Type 'MyNameSpace.MyClass, MyLibrary, Version=9.2.0.0, Culture=neutral, PublicKeyToken=null' was loaded in the ReflectionOnly context but the AssemblyBuilder was not created as AssemblyBuilderAccess.ReflectionOnly. My Namespace is MyNameSpace. My library is called MyLibrary. I have tried to reproduce it on a small project and I can't. I will keep trying to see if I can narrow it down. Thanks in advance for helping. Question Answers - All replies - Hi Frederic - thanks for reporting this issue. This error definitely seems possible from the genasm.exe sources. However we are unable to repro this issue in our labs. Can you send me the project and the xmta file that you used to successfully reproduce this error? Thanks... Hi Frederic - we have been able to repro this problem. This repro for this issue is simple and as follows: 1. Create a new Device Console Application project 2. In Program.cs, create a new public class deriving from List<Component> 3. Add a designtime attributes file to the project (could be a the default template) 4. Build. Can you please confirm that you indeed have a public class that derived from an instantiated generic type like the above? Unfortunately there the only workaround for this issue is to make the class deriving from the instantiated generic type non-public e.g. private or internal. Please let me know if this fixes the issue for you. If not I will help you find ways of working around it. Thanks... - - I have one particularly painful case where it would be great to be able to use generics.I've written a base list control, with designer support, in which I was intending on having a generic ListItem class parameter, allowing easy creation of custom list controls with a new ListItem type that can be created in the designer (collection editor). This allows all the scrolling / sizing / boilerplate code to be left in the list class, and the funky painting code / custom properties to be placed in ListItem implementations - with designer support.The problem is because I need my ListItem collection to be strongly typed (ie of the generic ListItem parameter, not of an interface or base type) so that the designer collection editor knows what type of ListItem to create at design time in the collection editor.Of course as soon I add the generic ListItem class parameter or collection property I can no longer compile. Does anyone know of another way to achieve this end? Is there any way to tell the collection editor to populate the collection with a specific class - not the reflected property type? We had the same problem and we dont want the users of our control to work with specific classes made up from generic ones. To made the genasm work you can simply generate the XML using the Class Diagram as you usually does, put that on a new project, generate ClassDiagram1.PocketPC.asmmeta.dll and rename it to NameOfYourAssembly.PocketPC.asmmeta.dll. That should work. Let me know if you need the code. - I've a similar problem, the error messagem is: "genasm.exe(1) : error There was an error initializing MyNamespace.MyControl. Type 'System.Data.SqlServerCe.SqlCeConnection, System.Data.SqlServerCe, Version=3.0.3600.0, Culture=neutral, PublicKeyToken=3be235df1c8d2ad3, Retargetable=Yes' was loaded in the ReflectionOnly context but the AssemblyBuilder was not created as AssemblyBuilderAccess.ReflectionOnly." What does it mean? How can I fix that? The problem is, you cant use generics and genasm. The workaround is, generate the DesignTimeAttributes.xmta using the Class Diagram as you would usually do, then, move that file to a new project and compile it, then rename it to [YourAssemblyName].PocketPC.asmmeta.dll and copy that to YourAssembly directory. If you want to automate that, just leave the DesignTimeAttributes file and set the CustomTool property to some dummy builder which does nothing and from the new project simply use the add existing file and a reference (link) to the original file, that way you can modify your class diagram directly from your original project and keep everything in sync. The final step is to use a build event and copy and rename the .asmmeta.dll to the proper name and folder. I hope this work for you, it have worked for us. Hi, Is it possible to have a patch released before the release of the service pack. When the ASP.net team did the new web project they required a VS 2005 patch to be installed before installing the project templates. This is kind of a major issue which I reported during the Beta. I dont understand how this problem was not detected during internal testing and why it was not fixed before launch. Kind Regards, Tarek mamadero Can you post a little more about your work-around? Which "dummy custom tool" did you use to stop VS trying to compile and include the DesignTimeAttributes.xmta in the original project as everything that I have tried results in an error. I have created a new project and added the original DesignTimeAttributes.xmta to the new project as a link. If I then exclude it from the original project then everything compiles and works fine, unfortunately however this means that the .xmta file is not included in any source control (links are not included as they are expected to be saved by the original project, but it is now excluded). Thanks Sorry, it the custom tool stuff didnt worked as expected. What I tried was, extending BaseCodeGeneratorWithSite or IVsSingleFileGenerator as specified in, to built a dummy Custom Tool, register that for COM and then change the property CustomTool of the XMTA file. Here's the code: usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingCustomToolGenerator; usingSystem.Runtime.InteropServices; usingMicrosoft.Win32; namespaceIntecmex.CustomToolGenerator { [Guid("D72D048D-FA0C-44f5-8287-B02B5CFDEB0F")] [ComVisible(true)] public class DummyCodeGenerator : IVsSingleFileGenerator//BaseCodeGeneratorWithSite {private static Guid csharpCategory = new Guid("{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}"); private static Guid vbCategory = new Guid("{164B10B9-B200-11D0-8C61-00A0C91E29D5}"); private static Guid customToolGuid = new Guid("{D72D048D-FA0C-44f5-8287-B02B5CFDEB0F}"); private const string customToolName = "DummyCodeGenerator"; private const string customToolDescripcion = "Does nothing, just fool the IDE to dont use a different tool"; private const string keyFormat = @"SOFTWARE\Microsoft\VisualStudio\{0}\Generators\{1}\{2}"; protected static void Register(Version vsVersion, Guid categoryGuid) {using(RegistryKey key = Registry.LocalMachine.CreateSubKey(String.Format(keyFormat, vsVersion,categoryGuid.ToString("B"),customToolName))) { key.SetValue("", customToolDescripcion); key.SetValue("CLSID",customToolGuid.ToString("B")); key.SetValue("GenerateDesignTimeSource",1); } }protected static void UnRegister(Version vsVersion,Guid categoryGuid) {Registry.LocalMachine.DeleteSubKey(String.Format(keyFormat, vsVersion,categoryGuid.ToString("B"),customToolName),false); } [ComRegisterFunction] public static void RegisterClass(Type t) { Register(new Version(8,0),csharpCategory); Register(new Version(8,0),vbCategory); } [ComUnregisterFunction] public static void UnRegisterClass(Type t) { UnRegister(new Version(8,0),csharpCategory); UnRegister(new Version(8,0),vbCategory); }//protected override byte[] GenerateCode(string inputFileName, string inputFileContent) //{ // return null; //} #regionIVsSingleFileGenerator Members public string GetDefaultExtension() {return "XMTA"; }public void Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, out IntPtr rgbOutputFileContents, out int pcbOutput, IVsGeneratorProgress pGenerateProgress) { rgbOutputFileContents =IntPtr.Zero; pcbOutput = 0;return; } #endregion } } Ok. So the thing is, VS was supposed to give the control to my IVsSingleFileGenerator, but didnt get up to that step for the same Genasm error. All this CustomTool design has been on the IDE since the 7.0 version. I tought the problem was the CustomTool for XMTA so I decided to create my own just to find out the problem is before that layer. So this means also .xsd (for the Datasets), .rpt and all the other custom tools will have the same problem. Hope this patch come soon. Well so the workaroun is: (I can e-mail you a solution with the two projects needed) You have your controls project with your .cs file and generate the custom attributes from there. You create a new project with and add as existing file (as link) the XMTA file. Then before compiling you will have to exclude the XMTA file from project 1 and the .asmmeta will be placed in the seconds project bin directory. You will probably want to do a Build Action to copy the file from projects two output folder to project 1 output folder. I know it's a pain in the *** to be excluding and reincluding (you have to add it again if you want to see or change the Custom Attributes of your properties from the Class Designer), but you still have source control for your XMTA file. If you reinclude your XMTA each time you have to modify an attribute, the file will automatically be Checked, after that you could exclude the xmta, compile both projects and then do a check in and the link will detected the checked out file and add that to the list of pending changes of the solution.... Thats the way it has been working for us that way, we tought about the possibility of doint the Cusom Tool and doesnt work... sorry for posting that out before trying it. Hope this helps. I have a related but somewhat different problem with the inclusion of the XMTA file. We included this file to be able to use the GUI designer to create custom controls. The project is a C#, CF 2.0, SmartDevice for Windows CE 5.0. Anyway, I don't have any trouble compiling the project until I use delayed signing. Removing the XMTA file allows me to compile and delay sign with no apparent effect. However, it is a major pain to remove this file each time a build is required. Is my situation related to those above or have I tapped a new compiler issue? Thanks, Drew Hi, I wont to make this problem as you described. But - it dosen't work for me. I explain. 1. I added new project to my solution ( namespace: Sente.NetCL, main component library projet in solution: sente.netcl.cf): sente.netcl.cf.xmta 2. I added the sente.netcl.cf.xmta file to sente.netcl.cf project, an then exceluded from project 3. I included (linked) sente.netcl.cf.xmta file to sente.netcl.cf.xmta project (this new project) 4. After buiding, I get sentenetcl.cf.xmta.Packet.asmmet.dll 5. I renamed this into sente.netcl.cf.Packet.asmmet.dll And ... Designer still dosen't see the atributes parameters. If I added simple control descendad TextBox to sente.netcl.cf.xmta project with one property "MyProperty" (completly different namespace), and added property description to the same file, and used the component from sente.netcl.cf.xmta project - all works great ! Why ? That, what doesn't work, is moment, when I must rename *.asmmet.dll file. Designer don't see proerty description if it is in renamed file. What I do wrong ? Regards Qubeczek Sorry for ripping up an old thread, but the error has popped up again in Visual Studio 8 Beta 2 with Sql Ce 3.5. I had to delete the xmta file to be able to rebuild. Here is the error I got: Error 1 genasm.exe(1) : error There was an error initializing MyProject.SqlMgr.rsExecuteQuery. And here is the code in SqlMgr: Private Shared cmd As New SqlCeCommand() Public Shared Function rsExecuteQuery(ByRef cn As SqlCeConnection, ByVal strSql As String, Optional ByVal RsOptions As ResultSetOptions = ResultSetOptions.Scrollable Or ResultSetOptions.Updatable) As SqlCeResultSet cmd.CommandText = strSql cmd.Connection = cn Return cmd.ExecuteResultSet(RsOptions) End Function I don't use generics but I suspect that the SqlCeResult is. - I'd just like to echo that we're having a lot of problems with this (when using projects configured for Delayed Signing) as well. It makes our company's release process a pain as right now for a workaround we have to manually edit the .csproj files with Notepad and remove the references to the .xmta before building release versions of our software (Note: this is VS2005 Team Suite edition). Just thought I'd bump the request for (re)fixing this problem :-) Thanks! - Problem is back in VS 2008 when upgrading a project from NETCF 2.0 to NETCF 3.5. Setting BuildAction of the .xmta file to Content lets the project build but prevents generation of the .asmmeta.dll file for the project as thaoula mentioned. Has anyone found a way around this yet? Creating a new NETCF 3.5 project from scratch doesn't seem to have the problem, only when the target framework is upgraded from 2.0. - If anyone cares to reproduce the problem: <1>create a new smart device project that targets NETCF 3.5. <2>Add reference to System.Data and System.Data.SqlServerCe to the project. <3>Create a new class. <4>Add a method that has a System.Data.SqlServerCe type (SqlCeConnect, SqlCEParameter, etc) in its parameter list or as its return type. <5>Right click the Form1.vb and select "View class diagram" <6>Right click the diagram element for Form1 and select Properties. <7>Add "DesktopCompatible(true)" as custom attribute. (This causes the DesigntimeAttributes.xtma file to be generated.) <8>Try to build the project, you will get the genasm error. <9>Now try changing the System.Data.SqlServerCe type to something not from that namespace, build, and it will work. Makes no sense at all. MS's workaround here: does not work unless you want to use only 2.0 libraries (in which case why not build a project that targets NETCF 2.0). Had same problem here - with VS2008 . BUT: the fix is to set the build action of the xmta file to "Content" - it works! - Proposed as answer by Santosh Nag THE GAME Wednesday, August 5, 2009 6:21 AM Hi, All. I'm also having this issue when creating a control library to .NET CF with VS2008, with a little twist in the error message I've got: genasm.exe(1) : There was an error finalizing type . Object reference not set to an instance of an object. Changing the build action to Content does not help beacuse the BuildAsmeta Target expects that the XMTA file to be in the None category, and so it doesn't generate the necessary assembly. Running the genasm by hand also gives the same error. The only workaround that I was able to was to move the classes that inherits from and generic colection to another assembly and keep isolated the controls that requires design time attibutes. Not the best solution but it works. It doesn't matter if it's a 2.0 or a 3.5 Target, as I built my project aiming the 3.5 from start. Even after five years MS didn't solve this issue... it's amazing. Has anyone reported this issue on Microsoft Connect? PJ on Development Hello, another workaround for this problem is ->Create a new project ->remove all .cs file (empty project) ->Add the .xmta file with all properties description in this empty project, with Build Action property in CONTENT ->Compile the empty project with just xmta file, after that will be generated two files "EmptyProjectName.dll" and "EmptyProjectName.PocketPC.asmmeta.dll" ->Rename the EmptyProjectName.PocketPC.asmmeta.dll file to your REAL PROJECT NAME (RealProjectName.PocketPC.asmmeta.dll" and copy it to your RealProjectAssembly output directory. This steps is another workaround to this Visual Studio problem. Just to remember, this problem is incompatibillity between genasm.exe and generics or collections returns. mauricio_scoelho1
https://social.msdn.microsoft.com/Forums/en-US/887362ed-4ab1-4671-a485-e86321f6bb62/genasm-error-message-when-adding-designtimeattributesxmta-to-my-project?forum=windowsmobiledev
CC-MAIN-2018-39
refinedweb
2,616
58.58
. Accidentally committing the wrong item from the completion list can be really annoying now, since it can result in importing a namespace. This is annoying for a few reasons: a) it's not immediately obvious that a namespace has been imported b) if the bad type is manually backspaced, the import is not removed c) if Undo is used to remove the namespace, the text editor scrolls so that the caret it right at the bottom of the screen. Perhaps we could make the namespace importing more explicit, e.g. insert a fully qualified name and then offer a tooltip "press alt-enter to convert to using"? We are still adding random using statements to peoples source code. Can we fix the implementation so it does not eagerly add useless using statements to the source? cc'ing alex so he can provide a repro no we don't - grab a master build. btw. I would like to have use cases where the import thing did that.
https://bugzilla.xamarin.com/13/13101/bug.html
CC-MAIN-2021-39
refinedweb
166
67.99
xr. For instance, the library is by default set up to send/receive JSON (with the associated headers and parser/dumper already set up), but if you wanted to use something like XML, it’s easy enough to override that with a few lines. It’s lightweight, has no dependencies (other than having either Promise in the global namespace or provided via xr.config), and adds pretty much no overhead over the standard XHR API. Install npm install xr --save Quickstart const res = await xr.get('/api/items', {take: 5}); console.log(res.data); const res = await xr.post('/api/item', {name: 'hello'}); console.log('new item', res.data); Extended syntax: xr({ method: xr.Methods.GET, url: '/api/items', params: {take: 5}, events: { [xr.Events.PROGRESS]: (xhr, xhrProgressEvent) => { console.log("xhr", xhr); console.log("progress", xhrProgressEvent); } } }); Custom promise: xr.get('/url', {}, { promise: fn => new myPromiseClass(fn) }); Raw mode (data is not dumped/loaded): xr.put('/url', 'some data', { raw: true }); Custom dump/load: xr.post('/url', {'some': 'data'}, { dump: data => msgpack.encode(data), load: data => msgpack.decode(data) }); Global configuration One thing that I’ve always found irritating with libraries it that if you want to override the defaults, you have to do it per-request, or wrap the libraries. With XR, this is simple, as you can globally configure the module for your project. xr.configure({ promise: fn => new myPromise(fn) }) API is simple, for now consult source. Features - Returns ES6 promises. - Has query parameter generation. - Supports events. Alias Methods You can do some quick aliases to requests, for instance: xr.get('/my-url') Requirements There must be a polyfill or browser that supports at least the standard ES6 promise API (xr will use whatever’s there). License See LICENSE
https://devhub.io/repos/radiosilence-xr
CC-MAIN-2020-24
refinedweb
291
61.53
Hey everyone, In this tutorial, i'm going to show you create a simple rest call that connects to Wia. If you haven’t already, you need to install the python language to complete this tutorial. Version 3.x.x Follow the download instructions for your operating system Next is to install the python package manager pip. Pip allows us to get the Wia python library which provides functionality to help connect to Wia with python. pip For windows, open power-shell and run pip install wia in the power-shell terminal. pip install wia For Mac/Linux open a terminal and run pip install wia in the terminal. Create a new folder(Name is irrelevant) in a location of your choosing (e.g. Documents folder) Add the file that you want to upload to Wia into the folder In your favourite text editor, create a new file and call it rest_call_to_wia.py rest_call_to_wia.py from wia import Wia wia = Wia() wia.access_token = 'your-device_secret_key' result = wia.Event.publish(name='rest-call', data='test') Replace your-device-secret-key with a Device Secret key from Wia, if you haven't got one, details on how to get yourself setup with Wia can be found here your-device-secret-key Save the file For windows, open powershell cd into the folder where your code lives run python rest_call_to_wia.py in the powershell terminal python rest_call_to_wia.py For Mac/Linux, Open a terminal run python rest_call_to_wia.py in the terminal Head to your Wia dashboard and in your Device section and click on the Debugger tab view the Event coming through. Device Debugger That's it for this tutorial! Check out our other tutorials, new ones are being added all the time.
https://community.wia.io/d/48-how-to-do-a-rest-call-to-wia-using-python
CC-MAIN-2019-39
refinedweb
290
55.03
Selection of text in a math zone obeys some special rules concerning built-up math objects, such as fractions and integrals. First some background on how these objects are stored helps to clarify the rules. In memory, math objects start with a special 16-bit character and end with a different 16-bit character. In RichEdit, the start character is U+FDD0 and the end character is U+FDEF. An argument of an object ends with a special separator character (U+FDEE for RichEdit) when followed by another argument and it ends with the end-of-object character if the argument is the last one of the object. This math object structure is also discussed in my post on math find/replace. The math object delimiter characters belong to the special Unicode range U+FDD0..U+FDEF, which is defined for internal use only. That is, these characters can be used in memory, but should not be used in files. Selection of text in a math zone works the same way it does in normal text as long as one of these three math-object delimiter characters isn’t selected. As soon as one is selected, the whole object is automatically selected. For example, if you type Shift+→ at the end of the numerator of a fraction, you attempt to select the numerator’s delimiter. This causes the whole fraction to be selected. Similarly if you type Shift+→ at the start of a math object or Shift+← at the end of a math object, the whole object is selected. The math object is also. You can select from outside a math zone part way into a math zone unless the math zone consists of a single math object. So if normal text precedes E = mc2, you can select that text along with, for example, E. As such the math zone isn’t treated as a single math object. This is possible because math zones are identified by a character format effect like bold rather than by start and end delimiter characters. Glad to see you are back from your vacation! 🙂 It would be good it you could explain in more detail in a future post why OOXML could not use MathML. I read your earlier post, but did not find it convincing. What we need are some examples from real-life docs which clearly demonstrate the need for OOXML to use a variant of MathML. Bare assertion is simply not enough if you want OOXML to become an ISO/IEC standard. This policy sounds all very nice and natural, and your answer at the MathUI workshop was just as much, but I am under the thought that there must be something more tricky somewhere. Have you been comparing this to other tools? Do you have experiment results that make it work ? thanks! paul It is nice to learn how RichEdit handles text selection internally. In my own math tool I used basically the same algorithm. Hopefully I’m not violating any Microsoft patents now… The memory representation is slightly different: I used U+000F..U+001E for start of object, U+000E for end of object, and U+000A (new line) as argument separator. The argument separator can be selected or even deleted without selecting the entire object. Re John’s question on why OOXML can’t use MathML, the basic reason is that Word allows the user to insert things into math zones that cannot be expressed as MathML. Such things include revision marks, footnotes, comments, and images. In the current MathML Working Group we have been attempting to figure out reasonable ways to generalize MathML to handle these things and might come up with appropriate modifications for MathML 3.0. When we created the new math facility, we were limited to MathML 2.0. Nevertheless, using an XSLT to translate OMML to MathML is fine for most purposes, since revision marks, footnotes, comments, images, etc., can either be discarded or can be avoided. For examples of real life documents, note that revision marks are a standard way of recording changes made by various coauthors. They are heavily used in the preparation of legal documents. But it doesn’t seem reasonable to include them in MathML. Instead I think they could be included in a property entity that belongs to a different namespace. For this to work, MathML needs to allow some kind of embedded namespaces. There are other needs for embedded namespaces in MathML and it’s a hot topic in the MathML WG.
https://blogs.msdn.microsoft.com/murrays/2007/06/30/math-selection/
CC-MAIN-2017-34
refinedweb
756
63.19
YO gUYS Please help me how to open a webpage in C++ cURL is the library which is used to do HTTP/FTP and similar protocols. There is a decent binding cURLpp for C++ which would be best for what you want. PS: C++ language as such do not have such functionality. IMO C and C++ are poor languages for doing web stuff. It will be a lot simpler to use a language that is suited for that kind of programming. I love python for this: I was parsing HTML code just after 2 weeks of learning Python, If it's on Windows, just use Win32 api (1 line of code with Shell , or 3 with COM...) I found this snippet a while ago. #include <windows.h> int main() { ShellExecute(NULL, "open", "", NULL, NULL, SW_SHOWNORMAL); } Thank u for helping me out. very good and Very clear! int main() { ShellExecute(NULL, "open", "", NULL, NULL, SW_SHOWNORMAL); } Works very well for me. Came across it the other day! Yea, that was posted 4 years ago in this
https://www.daniweb.com/programming/software-development/threads/198702/how-to-open-a-webpage-in-c
CC-MAIN-2016-50
refinedweb
174
91
Originally posted at Towards Data Science on Medium Data exploration is an important aspect of the Machine Learning pipeline. Before we decide which model to train and how many to train, we must have an idea of what our data contains. The Pandas library is equipped with a number of useful functions for this very purpose and value_counts is one of them. This function returns the count of unique items in a pandas dataframe. However, most of the time, we end up using value_counts with the default parameters. So in this short article, I’ll show you how to achieve more by altering the default parameters. value_counts() The value_counts() method returns a Series containing the counts of unique values. This means, for any column in a dataframe, this method returns the count of unique entries in that column. Syntax Series.value_counts() Parameters Basic usage Let’s see the basic usage of this method by on a dataset. I’ll be using the Titanic dataset for the demo. I have also published an accompanying notebook on Kaggle, incase you want to get directly to the codes. Importing the dataset Let’s begin by importing the necessary libraries and the dataset. This is a fundamental step in every data analysis process. # Importing necessary libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # Reading in the data train = pd.read_csv('../input/titanic/train.csv') Explore the first few rows of the dataset train.head() Calculating the number of null values train.isnull().sum() Thus, the Age, Cabin and Embarked columns have null values. With this, we have a bare idea of what are dataset looks like. Let’s now see how we can use value_counts() in five different ways to explore this data further. 1. value_counts() with default parameters Let’s call the value_counts() on the Embarked column of the dataset. This will return the count of unique occurrences in this column. train['Embarked'].value_counts() ------------------------------------------------------------------- S 644 C 168 Q 77 The function returns the count of all unique values in the given index in descending order without any null values. We can quickly see that the maximum people embarked from Southampton, followed by Cherbourg and then Queenstown. 2. value_counts() with relative frequencies of the unique values. Sometimes, getting a percentage is a better criterion then the count. By setting normalize=True, the object returned will contain the relative frequencies of the unique values. The normalizeparameter is set to False by default. train['Embarked'].value_counts(normalize=True) ------------------------------------------------------------------- S 0.724409 C 0.188976 Q 0.086614 Knowing that 72% of people embarked from Southampton is a better metric than saying 644 people embarked from Southampton. 3. value_counts() in ascending order The series returned by value_counts() is in descending order by default. We can reverse the case by setting the ascending parameter to True . train['Embarked'].value_counts(ascending=True) ------------------------------------------------------------------- Q 77 C 168 S 644 4. value_counts() displaying the NaN values By default, the count of null values is excluded from the result. But, the same can be displayed easily by setting the dropna parameter to False . train['Embarked'].value_counts(dropna=False) ------------------------------------------------------------------- S 644 C 168 Q 77 NaN 2 We can easily see that there are two null values in the column. 5. value_counts() to bin continuous data into discrete intervals This is one of my favorite uses of the value_counts() function and an underutilized one too. value_counts() can be used to bin continuous data into discrete intervals with the help of the bin parameter. This option works only with numerical data. It is similar to the pd.cut function. Let’s see how it works using the Fare column. # applying value_counts on a numerical column without the bin parameter train['Fare'].value_counts() This doesn’t convey much information as the output contains a lot of categories for every value of Fare. Instead, let’s group them into seven bins. train['Fare'].value_counts(bins=7) Binning makes it easy to understand the idea being conveyed. We can easily see that most of the people out of the total population paid less than 73.19 for their ticket. Also, we can see that having five bins serves our purpose since no passenger falls into the last two bins. Thus, we can see that value_counts() is a handy tool, and we can do some interesting analysis with this single line of code.
https://parulpandey.com/2020/08/02/getting-more-value-from-the-pandas-value_counts/
CC-MAIN-2022-21
refinedweb
738
57.67
A lot of tools are built to run in browsers today, as we spend most of our time there. Read on to learn how you can build a Chrome extension, the Github Gist Downloader, with React. An extension is a software program that customizes the browsing experience. Using an extension, a user can customize browser functionalities to their needs. Extensions can be created using HTML, CSS and JavaScript. We'll be creating an extension for Chrome that will enable us to download code snippets we created on GitHub Gists. You can find a screenshot of the extension in action below: To follow this tutorial, a basic understanding of JavaScript and React is required. Please ensure that you have at least Node version 6 installed before you begin. We'll be using the following to create our extension: In this step, we'll create the project folder and install the dependencies needed for the project. Create a folder called gist-download. In the folder, create a file named package.json and copy the following code into it: { "name": "Gist-downloader", "version": "0.1.0", "description": "Download code snippets on gists", "main": "src/js/main.js", "scripts": { "build": "parcel build src/js/main.js -d src/build/ -o main.js", "watch": "parcel watch src/js/main.js -d src/build/ -o main.js" }, "dependencies": { "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "parcel-bundler": "^1.6.2", "prettier": "^1.14.3", "react": "^16.2.0", "react-dom": "^16.2.0" } } To install the dependencies, run $ yarn install or $ npm install in a terminal in the root folder of the project. The next step is to create a manifest.json file in the root folder of your project. All Chrome extensions are required to have a manifest file. The manifest file simply describes the package's contents. Copy the following code into the manifest.json file: { "manifest_version": 2, "name": "Gist file downloader", "description": "An extension that can be used for downloading gist files.", "version": "1.0", "browser_action": { "default_icon": "icon.png" }, "permissions": [ "activeTab" ], "content_scripts": [ { "matches": ["*"], "js": ["src/build/main.js"], "run_at": "document_end" } ] } Note: All static files referenced here can be found in the demo repository here. Chrome manifests are expected to have a manifest_version of 2. The permissions property is an array of permissions our extension needs to run. The extension will need access to the current active tab. The content_scripts array contains an object detailing the domains ( matches) the extension should run on—the main js file. And the run_at property tells Chrome when it should run the extension. You can read more about the properties that are available on the manifest file here. The final folder structure should look like this: gist-downloader/ src/ js/ components/ download-button.js utils/ index.js main.js Inside your project folder, create the src folder to hold the project files. Inside the src folder, create a js folder. Finally, create a file called main.js in the src/js folder. This file will be the main entry file for the project. Copy the following code into the main.js file. In the main.js file, we'll search for the .file_actions element, which resides in the header of each Gist file. We'll then render the application, which will be a simple download button as one of the file actions. import React from "react"; import ReactDOM from "react-dom"; class App extends React.Component { render() { return <h1>The App</h1> // TODO: create a download button component and render here } } window.onload = () => { const fileActions = [ ...document.body.querySelectorAll(".file .file-actions .BtnGroup") ]; fileActions.forEach(action => { const containerEl = document.createElement("span"); action.prepend(containerEl); ReactDOM.render(<App />, containerEl); }); }; The extension waits until the DOM content is loaded before in renders the application in the DOM. Using the document.querySelectorAll method, we'll get all elements with the .BtnGroup class existing within an element with a class file. This is to ensure the element selected is the one intended. Using a forEach method, the fileActions array is looped through and within the callback function, a span element is created and prepended to the action element. Finally, the app is rendered within span element. In the next step, we'll create the download button and walk through the steps of creating a file and downloading it. Gists are snippets, files, parts of files, and full applications shared with other people. They are basically repositories that can be cloned or forked. You'll find a screenshot of a Gist below: In this tutorial, we'll be adding an extra action button to the file actions header. Create a folder named component in the src/js directory and then a file named download-button.js within the components folder. In the download-button.js component, we'll create a button that, when clicked, will get the contents of the Gist and then curate a file with those contents. Finally, a download will be triggered for the created file. Open the download-button.js file and copy the following code into it: import React, { Fragment, Component } from "react"; import { download } from "../utils"; class DownloadButton extends Component { constructor() { super(); this.onClick = this.onClick.bind(this); } onClick() { const fileTextArea = this.codeTextArea.querySelector('textarea'); const fileContent = fileTextArea.value; const fileName = this.codeTextArea.querySelector(".gist-blob-name").innerText; download(fileName, fileContent); } get codeTextArea() { return this.button.parentElement.parentElement.parentElement .parentElement.parentElement; } render() { return ( <Fragment> <button className="btn btn-sm copy-pretty tooltipped tooltipped-n BtnGroup-item" aria-label="Download the file" onClick={this.onClick} ref={ref => (this.button = ref)} > Download file </button> </Fragment> ); } } export default DownloadButton; In the component, the render method returns a button element. The reference to the element is obtained and a click event listener is set up. When the button is clicked, the codeTextArea getter method returns a textarea containing the textual contents of the Gist. The chained parentElement is a crude way of ensuring that the textarea returned contains the Gist content requested for download. Next, the value of the textarea is assigned to the fileContent variable, and the name of the file is obtained from the text of an element with the class name gist-blob-name. Finally the download function is called, with the fileName and fileContent as arguments. Next, we'll create an utils/index.js containing the download function. In the src/js directory, create a folder named utils and create an index.js file within the utils folder. Open the index.js file and copy the code below into it: export const download = (filename, text) => { const element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); }; First, we create an anchor element. Then we create the href attribute, encoding the text parameter as a UTF-8 character using the encodeURIComponent function. A download attribute is then set on the anchor element. The download attribute is required on an anchor element to trigger a download. The filename param is then set as the value of the download attribute. The element is hidden by setting the display to none before appending it to the document body. A click event is then triggered on the element as the element is removed from the DOM. Now that the download button component has been created, let's go back to the main.js file and render it there. Open the main.js file and update it to include the DownloadButton element. class App extends React.Component { render() { return <DownloadButton />; } } In the next step, we'll learn how to build the extension and add it to Chrome. In this section, we'll build our newly created extension and load it on the browser, seeing it in action for the first time. Open a terminal in the root folder of the project and run the following command to build the application: $ npm build This command should create a build folder in the src directory with the main.js file within it. In your Chrome browser: The extension should show up in your extensions list. When you visit any Gist page you'll see the download button show up, similar to the screenshot below: Congratulations!! You've successfully created a Chrome extension. A click on the "download file" button should trigger a download for the named file. You can find the complete code on Github. Want to learn more about React? Check out our All Things React page that has a wide range of info and pointers to React.
https://www.telerik.com/blogs/how-to-create-a-gist-download-chrome-extension-using-react
CC-MAIN-2021-39
refinedweb
1,431
52.05
What. What is a Component in Angular?'] }) Role of App Module] }) What is Data Binding? Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below: - When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”. - When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”. - When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”. What is a Service in Angular? Services are substitutable objects wired together. Also, it organizes and shares code across your app. For logic that is not associated with a specific view, and that we want to share across components, we create a service class. The @Injectable() decorator immediately precedes the service class definition. This decorator provides the metadata. And, it allows other providers to inject as dependencies into our class. First, we create a service and provide it to the root. example.service.ts import { Injectable } from '@angular/core'; import { Example } from './example'; import { data } from './mock-data'; @Injectable({ providedIn: 'root', }) export class ExampleService { constructor() { } getData(): Example[] { return data; } } Components should not fetch data directly. Else, they should present data accessing to a service. Here’s how we can add the service in our component: home.component.ts import { Component, OnInit } from '@angular/core'; import { Example } from '../example'; import { ExampleService } from '../example.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { data: Example[]; constructor(private exampleService: ExampleService) { } ngOnInit() { this.getData(); } getData(): void { this.exampleService.getData() .subscribe(data => this.data = data); } } So, from the above example, we can see that it is easy to add service in a component. First, we inject the service in the constructor. After that, we add a method to fetch data in ngOnInit(). Finally, we subscribe to the service to use methods for fetching data. Routing Routing means navigating between pages. The angular router installed from the @angular/router package. It provides a complete routing library. They have multiple router outlets, different path matching strategies, and easy access to route parameters. It enables developers to build Single Page Applications with multiple views. And, it allows navigation between these views. The router-outlet is a directive used from the router library where the router is inserted in the component and gets matched based on the current browser’s URL. <ion-router-outlet></ion-router-outlet> So, this was a short overview of the basics of angular. We can dive further into each part of the angular. Further in the series of Angular Basics, visit the second blog for Components and data binding. Also, you can visit Angular Docs to study more in details. Thanks!
https://blog.knoldus.com/basics-of-angular-part-1/
CC-MAIN-2022-27
refinedweb
498
51.95
This is post no. 7 in the mini series "10 exciting things to know about XAF". You can find the announcement of the series here. As you know if you've had a look at our XAF pages or tried the product yourself, there's a layer in XAF that allows you to develop applications for the Windows Forms and the ASP.NET UI platforms at the same time. All your code can live in the UI independent module and XAF takes care of the UI specific representation. Of course there are lots of cases where certain UI specific changes need to be made, but this is also easy to do within the solution structure, because it includes projects that specifically target each of the supported platforms. Reaching this degree of UI independence we have was an important target for XAF from the beginning. Of course there will always be platforms that people use at the same time -- i.e. it makes sense sometimes to have a version of an application that runs on ASP.NET and another one that uses Windows Forms --, but we also make our product and the code you write on the UI independent level a much safer investment. The world around UI technology evolves pretty quickly these days. As an example, it's not too long ago that Windows development was focused on Win32. For many use cases, Windows Forms abstracted enough from that old world to make things a bit easier for developers, but WPF is really the first UI platform that doesn't inherit an API that is, in parts, more than 15 years old. Still, from a Microsoft developer's perspective, the time that passed while Windows Forms was the primary platform of choice for client development was already considerably shorter than the ActiveX period that came before it (or the Delphi period, if your that way inclined). Personally I do believe that WPF is going to be very significant for an extended period of time, but if we have a chance of abstracting our business development efforts from these uncertainties, why not take it? Regardless of what your thoughts are on WPF, Windows Forms, Silverlight, ASP.NET, UI specific software factories, AJAX, the whole old web vs client discussion.... wouldn't it be great not to have to consider these things anymore? Perhaps we can't promise that all these issues will be entirely irrelevant to your development forever. No, we certainly can't promise that. But what we're trying to do is, once again, to save you significant effort by doing a lot of your work for you. Abstraction from the UI doesn't come for free. It has a price in two different areas: (1) abstraction and (2) working with a least common denominator as a feature set. To an extent it is possible to make abstraction comfortable to use, and it's also possible to enlarge the common feature set by making the abstracted technology more intelligent, basically leveling the playing field by filling in gaps where necessary. Of course this latter approach also means that any new UI platform will be harder to target, depending on the gaps it has. It is, and will always remain, a fight for the perfect compromise. In real world applications there are several different scenarios where it makes sense to have UI abstraction: There are classes in the DevExpress.ExpressApp.Editors namespace that allow you to access common functionality of UI elements without actually introducing UI dependencies into your code. The MainDemo included in our XAF distribution contains a few controller examples (in the Module project) that use these classes to provide common functionality -- clearing fields in a detail view is one such example. I didn't put it many links in this post, since I believe this is more about the general consideration of whether or not, and when, UI independence makes sense. As I said before in another post -- in the end it's your choice. XAF also lets you create projects specific to one of the supported UI platforms, if that's what you prefer. My personal belief is that UI abstraction is moving from a convenience to a necessity these days, and that belief is well reflected in the way XAF works. Hi Oliver. Is possible to have an example of how to use UI indepent code to show a Modal Dialog in win forms and ASP.NET ? Is that possible?, i know that ASP.NET is a bit different in this kind of things. Nice post, phisolosophycal, but refreshing. Thanks. Pingback from Abstraction » XAF - 7 - Take advantage of the UI abstraction Pingback from 10 exciting things to know about XAF - eXpress App Framework Team
http://community.devexpress.com/blogs/eaf/archive/2008/05/28/xaf-7-take-advantage-of-the-ui-abstraction.aspx
crawl-002
refinedweb
789
60.45
On Sat, 2002-11-09 at 14:09, Marcus Brinkmann wrote: > Certainly not. There is no point in sbin if it is i every users path. > It is our believe that the distinction between sbin and bin is useful. Who is 'our' in this case. The FHS committee? My point was that if we can reasonably show that on a GNU/Hurd system that most (say 90-95%?) of the commands in sbin would be reasonable for a power user to use there is probably value in just having that in the general users path. You don't want namespace collisions between bin and sbin anyway, so there shouldn't be too much of a worry. It's not like you're protecting newbie's since I would expect them to not ever see the command line anyway. Tks, Jeff Bailey -- When you get to the heart, use a knife and fork. - From instructions on how to eat an artichoke. Attachment: signature.asc Description: This is a digitally signed message part
https://lists.debian.org/debian-hurd/2002/11/msg00066.html
CC-MAIN-2017-17
refinedweb
171
83.36
[ ] Sean Busbey commented on ACCUMULO-1965: --------------------------------------- bq. Then, if they still fail, it could be an illegal argument exception or a typed exception (but never just a runtime exception) . And an illegal argument exception should be fine because that's the only real argument to create table. I agree that it should be an IllegalArgumentException. bq. but it seems like we should have a table name check utility available to users in the client api. AFAICT, we all agree on this point. How about going with a static method on TableOperationsHelper? As an aside, do we have table name restrictions documented somewhere? Other than Constants.VALID_TABLE_REGEX, I don't see anything and that's not in the public API. Namespaces have a note in the javadocs for the create method on NamespaceOperations. > Invalid table names (& namespaces) should have dedicated error codes > -------------------------------------------------------------------- > > Key: ACCUMULO-1965 > URL: > Project: Accumulo > Issue Type: Bug > Components: client > Reporter: John Vines > > To improve the client API, we should minimize the number of exceptions that require String parsing to determine the exception type. Table naming errors is one of them. -- This message was sent by Atlassian JIRA (v6.1#6144)
http://mail-archives.apache.org/mod_mbox/accumulo-notifications/201312.mbox/%3CJIRA.12682775.1386196431949.79322.1386266796179@arcas%3E
CC-MAIN-2017-04
refinedweb
193
66.54
A simple example of using multiple processes would be two processes (workers) that are executed separately. In the following example, two processes are started: countUp()counts 1 up, every second. countDown()counts 1 down, every second. import multiprocessing import time from random import randint def countUp(): i = 0 while i <= 3: print('Up:\t{}'.format(i)) time.sleep(randint(1, 3)) # sleep 1, 2 or 3 seconds i += 1 def countDown(): i = 3 while i >= 0: print('Down:\t{}'.format(i)) time.sleep(randint(1, 3)) # sleep 1, 2 or 3 seconds i -= 1 if __name__ == '__main__': # Initiate the workers. workerUp = multiprocessing.Process(target=countUp) workerDown = multiprocessing.Process(target=countDown) # Start the workers. workerUp.start() workerDown.start() # Join the workers. This will block in the main (parent) process # until the workers are complete. workerUp.join() workerDown.join() The output is as follows: Up: 0 Down: 3 Up: 1 Up: 2 Down: 2 Up: 3 Down: 1 Down: 0
https://riptutorial.com/python/example/12408/running-two-simple-processes
CC-MAIN-2020-40
refinedweb
158
50.84
Instead of using @RenderPage try UserSearchDisplayModel user = grid.Rows[grid.SelectedIndex].Value; @Html.Partial("_AdminUserDetails", user) Works for me. I do not experience the behavior you are seeing regarding the ResetDataSource action and the GetNearestAirport function not appearing in the Metadata Service Document. I have not heard of anyone having that issue. Will chat with the OData team this week about it. In regards to the overriding of the Metadata Service Document, I do not believe there is any way at this time to change it. Allowing ch Your overlay.Format.BitsPerPixel / 8 will be 1 (because it's a gif), but you're trying to copy it to something that is not a gif, probably BGRA (32 bit). Thus you got a huge difference in size (4x). .WritePixels should take in the stride value of the destination buffer, but you past it the stride value of the overlay (this can cause weird problems as well). And finally, even if it went 1 How to achieve the LongListSelector jump list in a wp8.1 windows runtime app Jumplists im afraid. In Silverlights contacts access is pretty fast but in XAML apps its a little bit slower (much more slower) so i was thinking in a way to make it work on XAML. @sibbl: Jumplists and your posts combined its a good way. When you want to remove items in a 1-many collection from the database you have to mark each item for delete, e.g. like so: foreach (var book in record.Books) { context.Books.Remove(book); } context.SaveChanges(); It's a nuisance sometimes. When you Clear a collection navigation property, EF errs on the side of caution and tries to only break the association without deleting the items, i.e. The easiest way is to use the JSON to class pasting functionality of Visual Studio: First of all, convert your JS object to a JSON string (e.g. with this tool). Copy the JSON output into clipboard and go into some class in Visual Studio. Use Edit > Paste Special > Paste JSON As Classes. You should get the following output generated: public class Rootobject { public string kind { get; Please see the documentation on modifying ServiceStack's built-in metadata templates: /meta It was a version problem after all. It turns out if you're updating Selenium via nuget, you need to be aware of which project the package manager console is pointing at. I'd managed to update my main project to Selenium 2.44 but my test project was still on version 2.40. Because the third parameter indicates the number of elements to clear, you are passing the size of the entire array. You only need Array.Clear(compartmentno, i, 1), as it seems like there is one element you wish to clear. It would be helpful if you could explain more about what this code is supposed to do. Also, instead of using six associated arrays, consider creating a class to store your info Okay, thanks to the tip of Piyush I figured out a rough way (needs optimisation badly, but works generally): 1) Store your original list in a variable (oldList got passed from a different class) Subcategory OriginalList = new Subcategory(); OriginalList = oldList; 2) Generate a dictionary containing all to-be-updated categories and products 'prod' is the base tree, and you will go recu You can use HttpClient using (var client = new HttpClient()) { var resp = await client.PostAsJsonAsync(" host/Login.aspx/Login", new { username = "", var str = await resp.Content.ReadAsStringAsync(); } First of all, let's fix this to use parameters: //I'm less worried about this query, as m and are likely integers. // I still don't approve of the string concatenation, but I'll leave it alone for now String q6 = "select date from lot LIMIT " + m + "," + n + ""; MySqlCommand c6 = new MySqlCommand(q6, cn); DateTime d = (DateTime)c6.ExecuteScalar(); //This should work just fine. //but parameter You will either need to create a custom trace listener that knows how to log to your table/stored procedure or modify the logging table/stored procedure to be in a format that Enterprise Library expects. Here is a sample database trace listener for SQL Server. It could be a good starting point for you if you decide to create a custom trace listener. Also, since you are using Oracle you will nee You can't mix arbitrary Expression instances with compile-time expression trees. What you can do is construct a new expression tree with specific nodes replaced, so you can have i => i + marker and then construct a new tree with the marker node replaced by your runtime expression. This requires writing an appropriate ExpressionVisitor: public static class ExpressionExtensions { public static You need to use Thread.Sleep() to avoid busy waiting or, better yet, just use a System.Timers.Timer (or one of its cousins) to wake up when you want. You also need to start your service in OnStart() instead of trying to do all its work there; that means scheduling an event handler (e.g. via Timer) or starting a new thread so that OnStart() can return on its original thread. The Windows Service sys The SignalR .NET client supports up to 3 transports: WebSockets (.NET 4.5 only) Version 2.2.0 of the SignalR client will also support the WebSocket transport in universal Windows apps. Server-sent events Long polling There is also the default auto transport that will try to use the best transport available. For example, it will initially try to start a connection using WebSockets, but if that This is an opinionated question and well, here is an opinionated answer... That is way too much abstraction and interfacing for something so simple. I would simply have immutable vector types of what I need. Even if the Vector3 changes constantly, you are doing this: ObjectA.Vector3 = SomeTransformationFunction(ObjectA.Vector3); Vector3 could totally be an immutable type here. I am having a Interesting question! As pointed out by starlight54, this approach is called a linked list, in particular a doubly linked list. Although I think that strictly speaking, in a linked list the references to other nodes are part of the nodes themselves. In db terms: the database record itself has foreign keys to the next and previous nodes (i.e. a doubly linked list). But that doesn't really matter fo I got the answer. It was very simple. Updated code, foreach (DataRow dr in dt.Rows) { lstweeks.Add( { new GetData{week = dr["WK"].ToString()} ); } I haven't used iTextSharp before, but in the examples I've seen online, they don't use all of the many writers you have. I'm suspecting that one of those is stripping out the HTML. Can you try a simpler path from StringBuilder to the html parser? htmlparser.Parse(new StringReader(sb.ToString())); These two pages seem to have had the same issue, but said they found a resolution. Their code is s Yeah, it's a common easy mistake. The <xsl:copy> only copy the element itself, it's equivalent to <xsl:element. You need to explicitely copy attributes nodes. For example, just switch your default template by : <xsl:template <xsl:copy> <xsl:copy-of <xsl:apply-templates/> </xsl:copy> </xsl:t Tuples are just generic objects. However you use the tuple, just imagine that you created a class with that many Items of the appropriate type. For instance, Tuple< string, int, int> will give you myObj.Item1 as a string, and Items 2 and 3 as integer. You can use it like this: new Tuple<string, int, int>("Steve", 15, 22) In the case of a list: var myList = new List<Tuple<doub use a service (helper) classes to share common code between controllers: public class ReportService() { public void SetReportValues(string pReportName, Dictionary<string, object> pParameters) { HttpContext.Current.Session["ReportName"] = pReportName; HttpContext.Current.Session["ReportParameters"] = pParameters; } } ReportsController: public void Report(ReportWrapper Not sure what format you want to store it as, or what you want to do with it after, but... Edit: Added an if check for length to avoid index out of bounds condition. Also corrected syntax- SubString() => Substring() int count = 0; foreach(var row in table){ string temp = row.ID.ToString(); count += (temp.Length > 5)? Convert.ToInt32(temp.Substring(temp.Length-5, 4)) : Convert.ToInt32( It is reasonable the error you get, because RemoveAll returns the number of removed stocks. This is an integer. Then you try to assign this to the variable called ticker, which holds a list of objects of type Stock. That you probably want is to remove all the Stocks that their TickerSymbol is gm and then write the Stocks that they have been left in ticker to the console. In order to do so, you co SqlHelper is obsolete. It was replaced by the Database object from MS Enterprise Library, but this is also obsolete. What functionality are you trying to extrude from it? You might be better off building your own abstraction layer using the Enterprise Library as a starting point. No, StartWith isn't buggy, and works as expected. Try the minimal code below. Reduce your code to the minimum amount to reprouce the problem. Does this happen everytime? Does it happen with more than one candidate string? Or only that string? Something else is going on sorry, the following writes Doesn't start static void Main(string[] args) { string cleanUrl = "123.123.123.123 From what you are showing, the ListBox l is not initialized, thus .Clear() on the collection is throwing a NullReferenceException. Instantiate the ListBox to fix the problem: ListBox l = new ListBox(); By the way, I tested this, not theorizing. When looking for information on this I came across this post describing unit tests with C# and Selendroid. YMMV. I am not sure how much correct the following approach is but that is what worked for me. Using the service credentials token you can access the GoogleMailSettingsService as follows bool success = credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result; OAuth2Parameters parameter = new OAuth2Parameters() { AccessToken = credential.Token.AccessToken }; GOAuth2Requ This worked out great for me. Thank you for the help, everyone. XmlSerializer serializer = new XmlSerializer(typeof(UserReportPreviewListDto[])); TextWriter WriteFileStream = new StreamWriter("serializer.xml"); serializer.Serialize(WriteFileStream, results); WriteFileStream.Close(); Learned something awesome today that'll help out a ton in the future, I have no doubt. Thanks again! Foreach is achieved with a list view like ListBox, ListView, etc. the simplest form is the ItemsControl class (no scrolling, etc.). The list is passed to the view using the ItemsSource property. The repeated code block is usually defined in the ItemTemplate template. Have a look at this answer: Try this (untested; but probably enough for what you need to do): <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="INSTALLFOLDER" Name="Wixdemoapplication" /> </Directory> Otherwise, can do some other fun stuff, like: Add this custom action to Product.wxs: <CustomAction Id="SpawnBrowseFolderDialog" BinaryKey="CustomActions" DllEntry="SpawnBrowseFolderDialog" Okay, just a few minutes after posting I've realized I was going at it from the wrong angle. Instead of assigning a "Tapped" event to the StackPanel, there's a generic ItemClick event for the ListBox, which can access the bound object via e.ClickedItem (plus casting). Honestly it's easier to do this in a traditional manner rather than with Linq, since the transformation method required for each element in the sequence requires knowledge of all previous elements. So, you could do something like this: public static IEnumerable<List<T>> Partition<T>(IEnumerable<T> list, Func<T, long> getValue, long maxSum) { long sum You can retrieve boolean Animator parameters by using the Animator.GetBool() method. Animator animator; void Start() { animator = GetComponent<Animator>(); } void Update() { var attacking = animator.GetBool("Attacking"); } 1) Add a service reference to your project. 2) See generated classes with object browser. 3) Use generated service client var webServiceSoapClient = new Q26998366_ConsumeAsmx.Dixon.WebServiceSoapClient ("WebServiceSoap"); foreach (Dixon.User user in webServiceSoapClient.Data()) { Console.WriteLine(String.Format("Name: {0} Pass: {1} Salt: {2} " , user.username, user.password, use below is code which solved my problem i used ComboBox.DefaultStandalone property instead of ComboBox.Default LinearGradientColorTable linGrBrush = new LinearGradientColorTable( Color.DarkGray, Color.DarkGray); Office2007Renderer renderer = GlobalManager.Renderer as Office2007Renderer; if (renderer == null) return; Office2007ColorTable table = You aren't removing the item from the control: if (dialogResult == DialogResult.Yes) { File.Delete(item); checkedListBox1.Items.Remove(item); } Best to put some Try...Catch blocks around such operations.
http://www.w3hello.com/category/csharp/1915/1
CC-MAIN-2018-17
refinedweb
2,069
57.06
inspectdb¶¶ The ogrinspect management command will inspect the given OGR-compatible DataSource (e.g., a shapefile) and will output a GeoDjango model with the given model name. There’s a detailed example of using ogrinspect in the tutorial. Use a comma separated list of OGR field names to add the blank=True keyword option to the field definition. Set with true to apply to all applicable fields. Use a comma separated list of OGR float fields to generate DecimalField instead of the default FloatField. Set to true to apply to all OGR float fields. Specifies the model attribute name to use for the geometry field. Defaults to 'geom'. The key for specifying which layer in the OGR DataSource source to use. Defaults to 0 (the first layer). May be an integer or a string identifier for the Layer. When inspecting databases, layer is generally the table name you want to inspect. Automatically generate a mapping dictionary for use with LayerMapping. When generating the geometry field, treat it as a geometry collection. For example, if this setting is enabled then a MultiPolygonField will be placed in the generated model rather than PolygonField. Generates a __str__() method on the model that returns the given field name. Suppresses the from django.contrib.gis.db import models import statement. Use a comma separated list of OGR field names to add the null=True keyword option to the field definition. Set with true to apply to all applicable fields. The SRID to use for the geometry field. If not set, ogrinspect attempts to automatically determine of the SRID of the data source.
https://django.readthedocs.io/en/latest/ref/contrib/gis/commands.html
CC-MAIN-2021-49
refinedweb
267
60.01
Hi, Could anyone give a working example of an embedded, animated plot in a Tkinter application, where animated=True is used together with canvas background copying to make efficient animated plots in Tkinter together with other widgets? I cannot make it work myself, see below. I am working on a prototype, where have some Tkinter widgets to control what is plotted. What I want to plot is something which progress in time depending on the state of the widgets, and it is potentially a lot of graphs and details on the canvas, but only minor changes between updates. So I would rather avoid redrawing the whole canvas. I would therefore like to use the trick with copying the backgorund, static canvas from frame to frame to a buffer, and only draw the animated artists on top of it as is discussed in and also examplified in Now, the example does not embed the matplotlib canvas in a Tkinter root class, which I need if I want to add other Tk widgets on the same window I have therefore tried to modify the animation by merging in the embbedding in Tk example: The closest I have gotten to something, which works is this: import matplotlib matplotlib.use('TkAgg') import Tkinter import sys import pylab as p import numpy as npy import time root = Tkinter.Tk() fig = matplotlib.figure.Figure() ax = fig.add_subplot(111) canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, root) canvas.get_tk_widget().grid() # create the initial line x = npy.arange(0,2*npy.pi,0.01) ax.grid(True) # canvas.show() #If I add this, it does not show anything? line, = ax.plot(x, npy.sin(x), animated=True, lw=2) def run(*args): background = canvas.copy_from_bbox(ax.bbox) # for profiling tstart = time.time() while 1: # restore the clean slate background canvas.restore_region(background) # update the data line.set_ydata(npy.sin(x+run.cnt/10.0)) # just draw the animated artist ax.draw_artist(line) # just redraw the axes rectangle canvas.blit(ax.bbox) if run.cnt==1000: # print the timing info and quit print 'FPS:' , 1000/(time.time()-tstart) sys.exit() run.cnt += 1 run.cnt = 0 manager = p.get_current_fig_manager() manager.window.after(100, run) p.show() # If I outcomment this, the graph does not animate Now, this does show an efficient animated plot embedded in a Tk application, but I cannot make it work witout instatiating the other annoying backgroud window, whcih pops up when the p.show() is done. However, if i uncomment it, I never get a visible window. As I have understood the cookbook, one should draw the canvas before copying it to the background and before drawing the animated Artists. However, if I do that it does not work either. I must admit, that I do not fully grasp waht is goin on in the lines, where the current figure manager is associated woth the run method. Another problem with the naimation is that it is not possible to close it nicely. Any help would be appreciated. Kim On 5/5/2010 6:53 AM, Kim Hansen wrote: > Could anyone give a working example of an embedded, animated plot in a > Tkinter application, where animated=True is used together with canvas > background copying to make efficient animated plots in Tkinter > together with other widgets? First see the embedding_in_tk.py example. Then, for a simple example, you can see TSPlot here: You can stick it in any frame. For a more complex example see diagram_cl hth, Alan Isaac
http://sourceforge.net/p/matplotlib/mailman/matplotlib-users/thread/4BE17619.8050307@gmail.com/
CC-MAIN-2014-15
refinedweb
581
57.06
Java Reference In-Depth Information In order to read an individual record, we shall defi ne a method called readRecord that reads in the surname, fi rst name(s) and examination mark for an individual student. Before looking at the code, it is probably useful to look ahead and see what the intended output should look like. In order that the JFileChooser object may be viewed as well, the screenshot in Fig. 4.5 shows the screen layout after one fi le has been opened and then the 'Open File' button has been clicked on by the user. Fig. 4.5 A JFileChooser object being used to select a fi l e The code for this application is shown below. If the reader wishes to create a serial fi le for testing this program, this may be done very easily by using any text editor to enter the required three fi elds for each of a series of students (each fi eld being followed by a carriage return). import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.util.*; public class UseFileChooser extends JFrame implements ActionListener Search WWH :: Custom Search
http://what-when-how.com/Tutorial/topic-547t9a4dbp/An-Introduction-to-Network-Programming-with-Java-124.html
CC-MAIN-2019-04
refinedweb
195
53.14
A minor pet peeve for me when programming Perl is the degree to which I wind up repeating code for things that I use over and over again. At the subroutine level, it's my $self = shift. At the file level, a prime example is use strict and use warnings, but it includes importing utility modules like Carp and Scalar::Util as well. I was hopeful when I heard about TheDamian's Toolkit, but was then disappointed to see that it uses config files in PERL5LIB -- which works fine for my own programs but is not necessarily easily shared with others or with end users of things. I decided to pick up and dust off an old idea of mine -- a module that bundles other modules into a toolset that imports all my "usual" stuff in one shot. In essence, I want this: use My::Tools; # turns strict on # turns warnings on # makes all my usual imports available [download] This is now possible with a new module I wrote called ToolSet. (The alpha version is now on CPAN.) For example: package My::Tools; use base 'ToolSet'; # handles the import() ToolSet->set_strict(1); ToolSet->set_warnings(1); ToolSet->export( 'Carp' => undef, # all the Carp defaults 'Scalar::Util' => 'refaddr blessed weaken', 'List::Util' => 'first reduce' ); 1; # return true [download] One of the more interesting discoveries I made along the way is how to get strict and warnings to be "contagious": use My::Tools; $var = 1; # causes a compile error because we're using strict [download] The breakthrough came from reading the source for strict and reading about $^H in perlvar. I realized that all I had to do was call strict's import sub without creating a new BEGIN block during ToolSet's own import routine: # simple example of strict contagion sub import { require strict; strict->import; } [download] This applies the strictures when the BEGIN block for use My::Tools finishes -- i.e. to the code that called use My::Tools. The same principle applied for warnings. The rest so far is just using eval to import the defined export modules into the calling package. In subsequent versions, I'll look to add the equivalent of @EXPORT_OK and @EXPORT_TAGS. I'd also like to add lazy exporting -- where a stub is installed that, when called, will require a module and replace the stub with the real function. I hope some people may find this useful. As always, I'd appreciate any feedback or ideas. Update: As another example of how this might be used, imagine a Perl6::Now ToolSet, that turned on strict and loaded all of the relevant Perl6::* modules. ; __END__ [download] # use File::Find; [download] sub foo { my $var=shift; } [download] But in passing it may be worthwile to remind a cheap alternative that would yield the absolute maximum of portability: editor macros or templates. And Perl isn't the only language I use templates for. I also have them for C, awk, FORTRAN, and Pascal. Not to mention tons of (retired) templates for all kinds of projects. Looks interesting. One minor point: I most commonly use Class ();. Before I read the full docs, I guessed that ... Class => '' ... would give me that, by symmetry with the other available options: Toolset->export( Class => 'sub1 sub2', Class => '' Class => [qw/sub1 sub2/], Class => [], ); [download] I'd suggest making it so, and leaving undef as the only way to get use Class;. I think I'd rarely use this for applications, where cut and paste can happily replace repeated typing, and where there are benefits to having the modules and pragmas in use clear to see. But for command-line invocations I can definitely imagine using this - when testing my work application, I often need 100-200 characters on the CLI just to get all the modules and initialisation I need, before I get to the one method call I'm trying to test. Hugo I really like this idea. I had a dream years ago of a 'caution' pragma. So you could say use caution; [download] instead of use warnings; use strict; [download] It seems like such a pragma could be implemented nicely using your idea. Kudos. Part of what you say is a good idea, but part seems somewhat... well, wasteful. I have a toolkit-type module that I import to give some commonly-used functions, like a sub that implements s/^\s+|\s+$//g;. But for stuff like use strict; use warnings; use Carp;, what's wrong with using a template (or macro, or whatnot) in your editor? It makes it much easier for future maintainers to see what's going on, rather than making them dig into another module just to find out that it repackages common pragmas and modules. Besides, my shortcut for such things ('ns'+Ctrl-Space) is much faster than even typing 'use My::Tools;'. I guess I don't see why you'd want common template-esque things packaged into a module. I'd like to use this on a distro destined for CPAN which numbers 47 modules and counting. One of those modules is a base class for almost all the others, supplying new(), etc. A typical module begins: package Restaurant::People; use strict; use warnings; use base qw( Restaurant::Util::Class ); use Carp; use Scalar::Util qw( blessed dualvar ); [download] Now, say I have other classes which inherit from Restaurant::People: Customer, Chef, Server, Busser, Manager, etc. The ultimate in laziness would be this, if I turned Restaurant::Util::Class into a ToolSet-enabled superclass: package Restaurant::People::Cook; use base qw( Restaurant::People ); [download] However, it doesn't look like I can get away with that -- the code needs to look like this instead, correct? package Restaurant::People::Cook; use base qw( Restaurant::People ); use Restaurant::Util::ToolSet; [download] That's still going to save a bunch of space. I always need strict and warnings, nearly always need Carp, and often need Scalar::Util, so I'll just throw 'em all in the ToolSet. Sweet! Regarding the Alpha status: I didn't see a warning anywhere in the docs. Is the interface stable? Without any explicit notice, I infer that distributions are in Beta if the version is less than 1.0. Cool. That's one of the applications for which I thought it might be useful. I don't think that use base will work because it doesn't call import. You could do it in two steps, though: package Restaurant::People::Cook; use Restaurant::People; # A ToolSet module our @ISA = qw( Restaurant::People ); [download] I suppose I could add a method to ToolSet that adds the ToolSet module to the caller's @ISA. Then you'd get the imports and set up a subclass. ToolSet->set_base(1); [download] The other approach would be to explicitly set base modules, so it doesn't necessarily have to be the ToolSet module: ToolSet->set_base('Restaurant::People'); [download] Any preference? If someone writes this: package BunnyBurgers::PRFlack; use base qw( Restaurant::People ); [download] ... they won't be expecting to have have a whole bunch of extra functions pulled into their namespace, or changes in pragma behavior. Now it's true that all of a sudden all of the imports I brought in via Restaurant::Util::ToolSet to Restaurant::People are available as methods, so $pr_flack->can('dualvar'). But that happens anyway -- $nearly_any_object->can('carp') -- and at least subclassers don't have to worry about surprise namespace polution in their actual module code. For the time being, I've settled on starting all the modules like this: package Restaurant::People::Cook; use Restaurant::Util::Toolset; use base qw( Restaurant::People ); [download] There will only be one ToolSet in the entire distro, and it will bring in strict, warnings, Carp, Scalar::Util, and a global RESTAURANT_DEBUG constant. Restaurant::Util::Toolset class won't be public, so it will be possible to modify it, but I'm expecting to keep it stable. That should cause minimum confusion. The only people who need to know what's in Restaurant::Util::Toolset are people who are hacking/debugging modules which use it. So, to answer your question, I wouldn't really use either one of those. Multiple inheritance of ToolSet-enabled modules would just get too messy. I'm quite happy with what we've got now. By compressing several lines at the top of the file into one, a bunch of meaningful, frequently edited code now appears in the the first screenful, so when I type "gg" in vim, I'm right in the game. I was wondering if this would come up. My hope was that people would create and publish their toolsets underneath the ToolSet namespace similar to the way that people release Bundles today. Lots Some Very few None Results (222 votes), past polls
http://www.perlmonks.org/index.pl?node_id=502654
CC-MAIN-2016-07
refinedweb
1,467
58.52
It has taken me a while to get into java 5 annotations. The reason partly was how late java 5 distributions arrived to the macosx platform (and it's still not the default version). About six months ago this stopped being an issue for me as i am now developing on ubuntu. I can't say enough wonderful things about ubuntu but we'll save that discussion for another blog entry. I tried out writing my own annotation. The scenario in question was the idea of modeling a method as an action. So metadata about a method might include the caption for the action, the mnemonic character to bind to that action and more such metadata. Essentially, the idea is to invoke the method when the action is performed from the UI. Here's a simple example of how an annotation might be bound to some methods in a ficticious class, Waiter: public class Waiter { private String _name; public Waiter(String name) { _name = name; } public void aplainmethod() { System.out.println("this is a plain method"); } @CommandAt( mnemonic='g', caption="Greet Customer", parameterCaptions={"Enter Name: ", "Specify Greeting: "} ) public String greet(String name, String greeting) { String msg = _name + " says: " + "Hello " + name + ": " + greeting; System.out.println(msg); return msg; } public String toString() { return _name; } } There's no denying the elegance of the solution. I particularly like the ability to place information about the method right next to it, though this may prove unwieldy. Aspects for example place code about methods somewhere else and use selectors to bind the code dynamically to methods based on some criteria. That's much more powerful. The reason I'm inclined to prefer aspects is simply that the the meta-stuff is a block of code, whereas annotations are declarative in nature. This is just a feeling at the moment but I think the reason I prefer the former case is that in order to arrive at a solution we're not employing any new concepts: the concept of a block of code existed in Java. Things are more self-similar, more minimalistic. Also, one might wonder how far one can describe meta-work declaratively. I think that's essentially the difference between annotations and aspects: aspects are meta-code whereas annotations are meta-data. I recently went through the short exercise of developing a basic issue manager (similar to bugzilla or scarab). The most fascinating aspect of the exercise was discovering a piece of metadata about methods: its owner. That is, the person who is assigned a bug is the bug owner and only him/her should be allowed to invoke the 'accept()' method to signal that they've taken ownership of the bug. Similarly, only the person who opened the bug should be allowed to verify and close the bug, not the developer responsible for fixing it. So I decided to model accept() and close() as methods on the same object (Issue) but to specify the owner of the method to relate who (what logged-in user) is allowed to invoke them (from the ui of course). For better or for worse, this is what I came up with: static { ComplexType type = ComplexType.forClass(Issue.class); type.command("Accept", AssignedState.class).setOwner(type.field("assignedTo")); type.command("Fix", AcceptedState.class).setOwner(type.field("assignedTo")); type.command("RejectFix", FixedState.class).setOwner(type.field("openedBy")); type.command("Close", FixedState.class).setOwner(type.field("openedBy")); } So the way you should read/interpret the code is: For Issues: for the command "Accept" in AssignedState, set the owner to the value of the assigneTo property (that is call getAssignedTo() when you need to know). etc.. Sure enough, that did the trick. Now when I assign a bug to a user, only that user can accept it (what I'm not showing you is the framework that produces the ui from the model objects). My main question at the moment, is: would it be possible to define such meta data using annotations? I don't have the answer yet. This bit of code is declarative in nature so we should be ok. The only complication might arise from the limitation that annotation property values can only be of type: primitive, String, Class, enum, annotation, or an array thereof. In the above case, the owner is of type Field (not java.lang.reflect.Field, but another Field). There are other issues to consider as well, and they're not necessarily insurmountable. I don't yet have extensive experience with annotations to say for sure, but I have a feeling that it would be nice to be able to traverse from an annotation to its associated programming element; in this case: to go from the CommandAt annotation to its associated method. Looking at the javadocs for java.lang.annotation.Annotation, this relationship does not appear to be defined. I find it would be very interesting to also discuss this whole issue of metastuff from the point of view of aspects. Maybe it's just me but having to weave in aspects into bytecode seems to be a hurdle high enough to block mass adoption of this powerful technology. My feeling on this point at the moment is that aspects have not yet reached their peak; that we will have to wait for a manifestation of aspects implemented for a scripting/non-compiled environment before that can happen. Indeed there already appears to exist a working prototype implementation of aspects for ruby. Little bit off topic. Should you propose in Java dev team one important shortcut ".field" for Field access (similar to .class)? In your case it mean to avoid string constants (where you can make misstype which are resolved only at runtime) and write just: assignedTo.field Posted by: pavelt on November 28, 2005 at 08:38 AM i like your suggestion. technically since this blog was on the java.net front page today, there should be folks who work for sun reading it as well. thanks. Posted by: eitan on November 28, 2005 at 04:16 PM
http://weblogs.java.net/blog/eitan/archive/2005/11/still_thinking_1.html
crawl-002
refinedweb
1,004
52.7
Expose Your C/C++ Program's Internal API with a Quick SWIG My previous installment, "Add Embedded Scripting to Your C++ Application," showed how you can use the C Scripting Language (CSL) to move your application from a strictly GUI- or command line-based system to one that fully embraces end-user programmability. In the spirit of a Zen koan, this article looks at an example of the "opposite" of adding scripting to your application: making your application's internal API callable from within Perl scripts. Fortunately, you can do this without resorting to obscure Interface Definition Languages (IDLs), CORBA, COM, RPC, stubs, or any of those legacy framework generators. The Simplified Wrapper and Interface Generator (SWIG) is a software development tool that connects programs written in C and C++ with a variety of scripting languages. SWIG is used with different types of languages, including all your favorites: Perl, PHP, Python, Tcl, Ruby, and most recently Lua. The list of supported languages even includes non-scripting languages such as C#, Common Lisp variants, Scheme, Java, Modula-3, and Objective Caml. However, SWIG is most commonly used to create high-level interpreted or compiled programming environments, user interfaces, and as a tool for testing and prototyping C/C++ software. SWIG also can export its parse tree in the form of XML and Lisp s-expressions. You can freely use, distribute, and modify SWIG for commercial and non-commercial use. The Simplified Wrapper and Interface Generator SWIG opens up a lot more possibilities than just API automation. Lok briefly at some these before digging into the details of making SWIG work for you: - Building more powerful C/C++ programs: By using SWIG, you can get rid of that clunky main() function and replace it with a scripting interpreter to control the application. This opens your app and makes it programmable. You immediately get a scripting interface allowing users and developers to modify the app without having to modify low-level C/C++ code. With some design forethought, you can eliminate the need for a custom macro language, config files, or another embedded scripting engine. - Rapid prototyping and QA automation: SWIG allows C/C++ programs to be placed in a scripting environment that can be used for testing and debugging. For example, you might test a library with a collection of scripts or use the scripting interpreter as an interactive debugger. Because SWIG requires no modifications to the underlying C/C++ code, you can use it even if the final product does not rely on scripting. - Integrating diverse systems: We all know that scripting languages work fairly well for controlling and gluing together loosely-coupled software components. By turning different C/C++ programs into scripting language extension modules, you can create new and never before possible apps. For example, game developers could write gameplay logic in Perl and yet still integrate advanced math and physics libraries from C++. Your First SWIG: A Probability Library Suppose you want to expose the functions in a Probability Library for use with a Perl script. The probability functions compute factorials, permutations, and probably a lot of other boring stuff. To show off a bit, you wrap the legendary Win32 API's MessageBox() function from the venerable user32.lib as well. Written in C, it looks like stats.c in Listing 1. Listing 1. stats.c double pi = 3.14159; //not used yet int factorial(int n) { if (n <= 1) return 1; else return n*factorial(n-1); } int permutation(n,r) { return factorial(n) / factorial(n-r); } #include <windows.h> int ShowAMessage(long hWnd, char *lpText, char *lpCaption, unsigned int uType) { //WIN32 API call return MessageBox(hWnd, lpText, lpCaption, uType); } Next, in lieu of an obfuscatory IDL, COM, CORBA, or other type specification of interfaces, you use (gasp!) the slightly enhanced header file (stats.i) shown in Listing 2. Listing 2. stats.i Enhanced Header File /* stats.i */ %module stats %{ /* Put header files here or function declarations like below */ extern double pi; extern int factorial(int n); extern int permutation(int n,int r); extern int ShowAMessage(long hWnd, char *lpText, char *lpCaption, unsigned int uType); %} extern double pi; extern int factorial(int n); extern int permutation(int n,int r); extern int ShowAMessage(long hWnd, char *lpText, char *lpCaption, unsigned int uType); Before you go any further, you need to install some form of SWIG. If you are working from a Windows or Mac platform, you probably want to start with some precompiled binaries from the SourceForge site. SWIG for Win32 (or SWIGWIN) doesn't come with a fancy installer: you simply unzip it and set some environment variables. You can retarget SWIG to the Cygwin or MinGW Unix-for-Windows environments by recompiling the system. I use Cygwin Perl for most workaday Perl scripting, but because you likely will be integrating with Visual Studio C++-built Win32 apps, I chose to try the nsPerl 5.005_03 that the docs recommended. For nsPerl, my environment is as follows: set PERL5_INCLUDE=D:\nsPerl5.005_03\lib\CORE set PERL5_LIB=D:\nsPerl5.005_03\lib\CORE\perl.lib Next, you need to discover which compiler flags your nsPerl was built with to produce linkable code later: perl -MExtUtils::Embed -e ccopts -Od -MD -DNDEBUG -DWIN32 -D_CONSOLE -DNO_STRICT - IF:/nsPerl/netsite/nsPerl/WINNT/lib/nsPerl5.005_03\lib\ MSWin32-x86/CORE Now, you can invoke the SWIGWIN generator to produce the stats_wrap.c wrapper based on the stats.i interface file (from Listing 2): swig -perl5 stats.i Lastly, you compile and link both your original code and the wrapper code in one step, using the ccopts discovered above: cl -Od -MD -DNDEBUG -DWIN32 -D_CONSOLE -DNO_STRICT stats.c stats_wrap.c /link user32.lib d:\nsPerl5.005_03\lib\MSWin32-x86\ CORE\perl.lib /DLL /out:stats.dll Calling Your C Functions from Perl Now, step back and look at what you've actually produced so far. Based on your two input files (stats.c and stats.i), you have churned out the following: - stats_wrap.c: Perl-callable function stubs, which call through to stats.c - stats.dll: a DLL loadable by Perl - stats.pm: a Perl module, which painlessly imports the stats.dll for your Perl apps (see Listing 3) Listing 3. Generated stats.pm File # This file was automatically generated by SWIG: package stats; require Exporter; require DynaLoader; @ISA = qw(Exporter DynaLoader); package stats; bootstrap stats; package stats; @EXPORT = qw( ); 1; Now, you finally can have some fun and call your "new" stats library from Perl. Construct the simple Perl program in Listing 4, which should be obvious to any coder: Listing 4. A Simple Perl Program for Our Stats Library use stats; $answer = stats::factorial(5); stats::ShowAMessage(0,"5! is $answer","SWIG Testing",0); The output is the dialog box shown below! Give Your C/C++ Program's Internal API Full Exposure What I've demonstrated thus far (I hope) is a relatively quick and painless way of exposing your C/C++ program's internal API to the machinations of any scripting language. Although I chose to use Perl, you could easily generate corresponding modules for Python, Java, and Lua in just a few minutes more. SWIG covers the vast majority of C++ classes and language features: references, pointers to members, multiple inheritance, overloaded functions and operators, smart pointers, STL data types, namespaces, and much more. The only known hole currently is the wrapping of nested classes, but the nearly all C/C++ programs are eminently "SWIGable.". wheloltabotly PumeSonee Phobereurce 2954035Posted by TizefaTaNaday on 06/14/2013 04:49pm BeldPeedlibia airjordanxiforsale.holidaygiving.org Mopilsspusapy cheapairjordanfusionshoes.holidaygiving.org EmpockeceReply wheloltabotly PumeSonee Phobereurce 2093782Posted by TizefaTaNaday on 05/16/2013 03:46pm LotaELodo UnabbedaMew PerInegeMagReply Reproduction Cartier Designer watches allow the woman's to apperceive during which by yourself you will become your ex Mr. PerfectPosted by poeriepah on 03/07/2013 11:40am After i jogging opportunity along with my cousin I came to be encourage with this top quality brand. Like the rr, Cartier as well as any various other high end brand name on the planet. As well as my mate tells me that it's not only our hope and also much more folks globally. Added buyers use a desire A day they're going to individual this specific high-class One particular. Not merely quite producer by themselves and also the standing up that patterns. Nevertheless, you it's a evening dream if you ask me and much more frequent consumers. As a result, initially it is extremely challenging will individual this unique top end until eventually my partner and i have the Duplicate Cartier Timepieces. Your mood My spouse and i research the internet, I've found an internet getting, and i also uncover this kind of notice is indeed layout and chic. And also the shocking would it be gives a quantity of sequence, you might select the shade you desire in addition to virtually any Processing Cartier Designer watches have their own special style. The design type in addition to the refreshing design forces you to incredible within it. Probably the most essential is this fact just inside affordable tagging. Hence, it can be unquestionably will choose the notion. Prior to I actually receive this particular Look-alike Cartier Designer watches, I never at any time get one factor online; mainly because My spouse and i reckon that on the web purchasing is just not protected. Look-alike Cartier Timepieces, My partner and i level I became drastically wrong. Your on the internet getting is absolutely comfort and ease for bait and we're in a position to determine the actual pleasant one particular. Copy Cartier Designer watches make our desire become a reality by just it is kind fashion in addition to high-end. These kinds of Look-alike Cartier Designer watches is actually well-designed together with mess with, you can view reality fashion inside and you'll enjoy the excellent top quality. Once the view is just not don't use anything but pertaining to seeing enough time, the actual Look-alike Cartier Designer watches with the staff of style style and design, that may provides you with the refreshing design you will need for this style planet. Plus the perform within the to line of Copy Cartier Wrist watches, many people is able to see the particular performance into it. The specific Identical Cartier Watches moves pertaining to plenty of quite a while; you can see the record as well as the standing on the idea. In a lot of observe creating company, the actual Copy Cartier Designer watches is now your key about it. and its increased reputation is definitely check their finest to satisfy men and women requirement, together with attain their very own luxurious wonderland. Perhaps I came to be blessed to possess this opportunity to non-public this kind of high-class Replica Cartier Wrist watches in this affordable. Nonetheless it may be trustworthy for those; many individuals might personal your thing in addition to good quality Identical Cartier Wrist watches, exactly like many of us private this particular magnificent. [url=]best cheap watches[/url]|Reply SWIG Interfaces for 3rd party dll - Testing - with no source codePosted by hiradhu on 03/09/2006 01:54am Hi, The article is good. I have been working on using SWIG with 3rd party dlls where no source will be given. I was able to do it successfully but still needs some minimal programming or understanding capability of libs & dlls. Can u pls highlight if u have any easy method of using 3rd party dlls along with SWIG for testing purpose? Where to go for helpPosted by Victor Volkman on 03/09/2006 08:05am I only know the most basic usage of SWIG. Please sign up for this mailing list to get your questions answered
http://www.codeguru.com/csharp/.net/net_asp/scripting/article.php/c11103/Expose-Your-CC-Programs-Internal-API-with-a-Quick-SWIG.htm
CC-MAIN-2015-32
refinedweb
1,976
52.19
Going back to the original post: On Sun, Jan 20, 2019 at 6:43 PM James Lu <jamtlu at gmail.com> wrote: > Backtick expressions work exactly like lambdas, except that they are bound > to the instance they are created in every time that class is used to create > one. ?!? bound every time that instance is used to create one -- I have no idea what that means, or why it's useful. As I understand it, Python has expressions and statements -- expressions evaluate to a value that can be referenced in various ways, statements can do other stuff. A lambda is an expression -- it evaluates to an function object, which can then be bound to a name, stored in a container, passed to another function, etc. Is this proposal somehow different? does a backtick expression evaluate to a function? It seems from other parts of this thread that is does somethign different with namespaces and globals and locals, or ??? To illustrate, this “percent” property is bound to the instance, not to the > class. > class Example: > percent = property(`self.v*self.v2/100`) > I do not understand this -- "property" is a decorator, or even more generally, a class which, when called, creates a "property" instance, that follows the descriptor protocol: As it is currently written, property expects a "getter" method as it's first argument. So the above would be written as: @property def percent(self): return self.v * self.v2/100 or, without the decoration: def percent(self): return self.v * self.v2/100 percent = property(percent) or, with a lambda: percent = property(lambda self: self.v * self.v2 / 100)) In any case, property expects a callable as it's first argument that will take an instance as its first argument. So there is no place for "binding to an instance". As far as I can tell, other than saving the six characters of lambda, the other thing that this does is provide some implicit argument calling -- how does that work exactly? in the above example, remember that "self" is a convention, so your backtick example could jsut as easily be: class Example: percent = property(`thing.v * thing.v2 / 100`) so when the function object is created, how does it know what arguments it takes? In this case, there is only one name used in the expression, so I guess we could assume that that's an argument, but what if it were: class Example: percent = property(`thing.v * thing.v2 / x`) Now we have both "self" and "x" as names to be resolved -- and the function will be called with an instance as the first argument -- so is that first argument "thing" or "x", and what namespace is the other one to be looked for? You do try to explain this here: Any variable names that exist when the backtick expression is created are > bound to the expression, what is "the expression"? -- as a rule expressions can't be bound to. and the reference to the expression is stored within the expression. it sure sounds like you are using the same work in two ways here... > Names that do not exist when the expression is created must be passed in > as parameters. so if I have a block of code like: a = 5 bt = `a + b` Then bt will be a function that takes one positional argument, so this is the equivalent of: bt = lambda b: a + b Which means that if I go and add a "b" above that line of code later on, suddenly the meaning of this expression changes? that sure seems fragile to me! or is it? bt = lambda b, a=a: a + b that is, the function gets the VALUE of a at teh time the function is created? Such names can also be passed in as keyword arguments. Backtick expressions > are created when their scope is created. > no it getting really, really confusing if there are more than a couple names involved: a = 5 b = 7 bt = `c * d / a + b *e *f / d * f` so c, d, e, and f are not defined, so the function needs 4 parameters? are they positional? in what order? if keyword, what is the default? This seems like a LOT of magic -- and for what? just to save typing? -CHB Use Cases > > This can be used anywhere a lambda would feel “heavy” or long. Here are a > few use cases where using a backtick expression would allow code to be > significantly mote readable: > > If/else chains that would be switch statements. > Creating decorators. > Passing in logging hooks. > Writing design-by-contract contracts. (See icontract on GitHub for an > example of what DBC looks like in Python.) > Tests and assertions. > We're really going to need to examples for these -- I can imagine examples where the code would be shorter, but NOT more readable! -CHB -- Christopher Barker, PhD Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-ideas/2019-January/054932.html
CC-MAIN-2022-33
refinedweb
834
70.73
After falling as much as 35% from late October levels, Bitcoin (BTC) is likely on the cusp of a dramatic + or – 50% move. BTC has price memory around 6,500, and a break below should take the market to 2018 lows around 3,000. A bounce could result in a 10,000 price print. I built a Random Forest model using data going back to 2010 to predict future prices over the coming 3, 6, 9, and 12 months. Predicted prices are: [table id=40 /] In my view, the use cases of BTC remain speculation and criminal activity. Despite this emotion, up is the more likely near-term path, especially if 6,500 can hold. Speculator markets can continue unabated for a long time. The code for this post can be found at my GitHub under post 66. Random Forest Model Given the size of the dataset (a few thousand rows), I opted to build a Random Forest (RF) model as opposed to a neural network. The RF model uses daily BTC data since 2010. Model features are described below: [table id=37 /] I employed a standard Random Forest regressor model from scikit-learn. The core code is below. This model was done four times, for each timeframe. from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score, GridSearchCV from sklearn.preprocessing import MinMaxScaler labels = np.array(dfr['price']) features= dfr.drop(['price','data'], axis = 1) feature_list = list(features.columns) features = np.array(features) train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25, random_state = 42) print('Training Features Shape:', train_features.shape) print('Training Labels Shape:', train_labels.shape) print('Testing Features Shape:', test_features.shape) print('Testing Labels Shape:', test_labels.shape) print('Training Features Shape:', train_features.shape) print('Training Labels Shape:', train_labels.shape) print('Testing Features Shape:', test_features.shape) print('Testing Labels Shape:', test_labels.shape) #Test dft = pd.read_csv(path/'Bitcoin - rftest.csv') dft= dft.drop(['data','price'], axis = 1) predictions = pd.DataFrame(rf.predict(dft)) predictions I evaluated feature importance using the following code: fi = rf.feature_importances_ pd.DataFrame({'Variable':feature_list, 'Importance':rf.feature_importances_}).sort_values('Importance', ascending=False) features=feature_list importances = rf.feature_importances_ indices = np.argsort(importances) plt.title('Feature Importances') plt.barh(range(len(indices)), importances[indices], color='b', align='center') plt.yticks(range(len(indices)), [features[i] for i in indices]) plt.xlabel('Relative Importance') plt.show() Perhaps unsurprisingly, Transactions, Total Bitcoins, and Wallets are the most important features determining BTC’s price. Price Memory BTC has price memory around 6,500, and a break below should take the market to 2018 lows around 3,000. A bounce could result in a 10,000 price print. - From 2/4/118 -2/6/18, BTC fell as much as 27% to 6,048 before bouncing and closing at 7,754, then rising as much as 91% to 11,573 - Over 127 days from 6/13/18 – 10/17/18, BTC traded below 6,500 69 times and closed below than above that level 46 times - On 5/10/19, BTC made a high just short of 6,500. The next day it gapped up above and did not look back for several months - Today, BTC traded down to around 6,530 before bouncing up over 7,200 Core Views of Bitcoin In my view, the use cases of BTC remain speculation and criminal activity. I wrote more about it here in May. Speculator markets can continue unabated for a long time. [table id=39 /].
https://www.complexityeverywhere.com/bitcoin-thanksgiving/
CC-MAIN-2021-10
refinedweb
580
60.92
26 January 2011 10:10 [Source: ICIS news] SINGAPORE (ICIS)--Here is Wednesday’s end-of-day ?xml:namespace> CRUDE: Mar WTI $86.71/bbl, up 52 cents/bbl; Mar Brent $96.43/bbl up $1.18/bbl Crude futures rebounded ahead of the release of a US Federal Reserve statement. The Fed was expected to stay on track on its plan to buy $600bn bonds. NAPHTHA: $855-856/tonne CFR Japan, up $1.50-3.50/tonne BENZENE: $1,125-1,130/tonne FOB Prices firmed in the afternoon with a deal for March loading heard at $1,130/tonne FOB TOLUENE: $955-970/tonne FOB Prices firmed in line with increases in benzene and crude futures on Wednesday. A deal was heard from the morning for March at $960/tonne FOB Korea, while bids for second-half February and March loading were heard at $955/tonne and $958-962/tonne FOB Korea. ETHYLENE: $1,250-1,270/tonne CFR NE Asia, stable Some end-users in China were heard to have received selling indications for second half-February arrival parcels at $1,270-1,280/tonne CFR NE Asia, but buying ideas ranged from below $1,200/tonne to $1,250/tonne CFR NE Asia levels. PROPYLENE: $1,360-1,370/tonne, steady Selling ideas remained in the high $1,300/tonne CFR NE Asia levels for second half-February arrival parcels, while buying ideas from end-users mainly hovered at $1,350-1,360
http://www.icis.com/Articles/2011/01/26/9429362/evening-snapshot---asia-markets-summary.html
CC-MAIN-2013-48
refinedweb
247
70.84
Opened 10 years ago Last modified 8 years ago #12238 new Bug ModelAdmin ignores dynamic fields of ModelForm Description (last modified by ) If a ModelForm is created and then modified to programatically add fields (say, in __init__), ModelAdmin ignores these fields when rendering the form. If one of these fields is added to the ModelForm's Meta, the field shows up just fine. I would expect the field to display without the coaxing in Meta.fields. - Create a ModelForm - Add it to ModelAdmin - View Form - Update ModelForm's __init__to include self.fields['xyz'] = forms.CharField(max_length=255, initial='keke') - View Form (note no change) - Update ModelForm's Meta.fieldsto include "xyz" - View Form (note the change) Attachments (1) Change History (11) comment:1 Changed 10 years ago by comment:2 Changed 10 years ago by comment:3 Changed 10 years ago by (reformat description, also it hasn't a patch until it has a patch) comment:4 Changed 9 years ago by I think the declared_fieldsets too satic too. Why not using a callable that people can override? I can provide a patch if needed. Changed 9 years ago by Attempt to use dynamic fieldsets generation comment:5 Changed 9 years ago by The patch I sent seems to work quite oki, but if I add a field dynamicaly, even if it's in the form object, the new value is not saved: def dynamic_fieldsets(self, request, obj=None, **kwargs): general_fields = list(self.general_fields) perms = PagePermission(request.user) if perms.check('freeze'): general_fields.append('freeze_date') return [ [_('General'), { 'fields': general_fields, 'classes': ('module-general',), }], (_('Options'), { 'fields': self.normal_fields, 'classes': ('module-options',), }), ] My freeze field is added properly in the admin interface, but the value is not saved. But in the other hand if I do things like that: def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ general_fields = list(self.general_fields) perms = PagePermission(request.user) # some ugly business to remove freeze_date # from the field list general_module = { 'fields': list(self.general_fields), 'classes': ('module-general',), } default_fieldsets = list(self.fieldsets) if not perms.check('freeze'): general_module['fields'].remove('freeze_date') default_fieldsets[0][1] = general_module The latest version works, but it feels like a very hackish way to do things. Can somebody explain me what's wrong here? Does Django have a more elegant way to do this? comment:6 Changed 9 years ago by comment:7 Changed 8 years ago by comment:8 Changed 8 years ago by @anonymous 6.Update ModelForm's Meta.fields to include "xyz" - howto? my Meta has no attr 'fields' while runtime in init I have the same problem - trying to add dynamic field to ModelForm comment:9 Changed 7 years ago by Change UI/UX from NULL to False. comment:10 Changed 7 years ago by Change Easy pickings from NULL to False. I've solved this in the meantime by updating contrib/admin/options.py in: Seems to be a harmless fix, possible to get this applied upstream?
https://code.djangoproject.com/ticket/12238
CC-MAIN-2019-30
refinedweb
499
55.74
How would i go about calling python code in another file? Id liek to seperate my program out a little more, but i would occasionally need to pass information from one file to aother. Is this a bad idea? How would i go about calling python code in another file? Id liek to seperate my program out a little more, but i would occasionally need to pass information from one file to aother. Is this a bad idea? well you could either use "import" to import almost anything you need, but since you're looking for more of a way to seperate out what you are making, you might try using execfile(). execfile() is very similar to include() in PHP, you just give it the file's path and it includes it. Last edited by thmnetwork; May 31st, 2005 at 02:09 PM. Reason: Misc. Editing well I guess it depends on what you're wanting to do. with "import" you get to play with the namespace a little more than with execfile. the import method I'm referring to would require you to write an extention package (which isn't really that hard) but allow you to give shorter names to certain classes at import-time. using import also uses less characters than execfile() would so I consider it "cleaner looking" On the other hand, if you're looking for just some simple way to seperate code out into different files just so you don't have to look at it all all at once, execfile() seems like a more direct solution than writing a whole package for what's just you instantiating classes and such. if you have a module in say FOO full of functions and you have a program BAR. you can easily call functions from FOO. simplyif you have a module in say FOO full of functions and you have a program BAR. you can easily call functions from FOO. simplyOriginally Posted by Civ247not hard. I do it all the time.not hard. I do it all the time.Code:from FOO import function "In theory, there is no difference between theory and practice. But, in practice, there is." unless you make an effort to change it's environment, it inheirts your own, so you should be able reference any variables you had hitherto created/redefined. it will also be able to update variables for value-checking after the execfile() something also occurred to me, you could do it by using system (part of the "os" module) which would "really" execute the script (as if oyu had typed it on the command line). I just thought I'd mention it for completeness, I wouldn't really use it to develop an application with, unless you had a really weird situation. Last edited by thmnetwork; May 31st, 2005 at 03:47 PM. Reason: added the bit about system()
http://forums.devshed.com/python-programming/259699-call-code-form-file-last-post.html
CC-MAIN-2014-52
refinedweb
482
71.04
Best order to vaccum, analyze, create indexes, etc.. ? (1) By ddevienne on 2020-04-03 15:28:49 [link] [source] Hi. I'm converting large scientific proprietary files into SQLite databases. Many blobs in two large tables, with structured meta-data in these and other tables. That's already working, but I wonder what's the optimum order for doing it. Here's how I do it currently: START TRANSACTION foreach table CREATE TABLE ... -- ROWID tables for millions of rows, GB of data INSERT INTO ... CREATE INDEX COMMIT VACUUM ANALYZE I've already turned OFF journaling, since the DB is not "online", not activated FKs (which are expressed in the table definitions), used a largish page-size (16K) and page-cache (32MB) to maximize import performance, etc... I have a few small tables, and two very large tables, and all inserts are interleaved, that's why I vaccum (an expensive operation) post-commit, to defragment the DB, and maximize read speed when the DBs are put "online" (data served over WebSocket using a custom protocol). I have several UNIQUE constraints in my table definitions, and I wonder whether I should remove those, and do explicit CREATE UNIQUE INDEX DDLs post-insert? (but pre-commit?). I also wonder whether the CREATE (non-UNIQUE) INDEX should be pre-VACCUM, or post-VACCUM? I suspect indexes wouldn't be fragmented if created post-VACCUM, thus saving that much IO from the VACCUM? Finally, I wonder if I can somehow parallelize inserts into my main two BIG tables? Perhaps inserting into two separate DBs, and do a CTAS from one DB to the next once both are complete, since similar to the CREATE INDEX case, this would implicitly defragment the table pages, no? Is CTAS optimized to do direct page copies? Or must it decode all records from the source, recode them into the destination, rebuilding the B-TREE from scratch? I'm basically asking for advice/guidance on the most performant way to do the above, which hopefully is clear enough. TIA, --DD (2) By Richard Hipp (drh) on 2020-04-03 15:40:11 in reply to 1 [link] [source] In terms of performance, you could take out all UNIQUE and PRIMARY KEY constraints from the table definitions and transform those into CREATE UNIQUE INDEXs that you run at the same time as your other CREATE INDEXes (as you suggest). And you could run the CREATE INDEXes after VACUUM, but do so before ANALYZE (again, as you already suggest). Other than those tweaks, I think what you are doing is optimal. (3) By ddevienne on 2020-04-03 16:33:31 in reply to 2 [link] [source] Thanks Richard. I'll do as you suggest for all indexes, UNIQUE or NOT. My PRIMARY KEYs are all either INTEGER AUTOINCREMENT as rowid aliases, or implicit rowid, so those can't be externalized. But what about the idea of inserting into two separate DB files? Those INSERTs can then be done in parallel (in different threads), non-interleaved, so probably don't require a VACCUM step, no? Is CTAS from an attached DB to another DB optimized to do page-level copies? Resulting in a non-fragmented continuous span of pages for the copied table? (4) By David Raymond (dvdraymond) on 2020-04-03 17:24:36 in reply to 3 [source] Apologies if I'm brain farting on something basic, but what is "CTAS" again? Create Table As Select? (5) By ddevienne on 2020-04-03 17:45:59 in reply to 4 [link] [source] Yes. (6) By Keith Medcalf (kmedcalf) on 2020-04-03 19:25:56 in reply to 1 [link] [source] Are you doing in-order inserts on this watch / phone? (32 MB is a big cache on an Apple Watch but pretty itty bitty on a computer) (7) By ddevienne on 2020-04-06 09:32:15 in reply to 6 [link] [source] Are you doing in-order inserts [...]? I guess I am, since these are rowid tables, with AUTOINCREMENT PKs. Or are talking about the Natural Key (NKs), using UNIQUE indexes? (those will be added later, post inserts, as discussed in this thread) (32 MB is [...] pretty itty bitty on a computer) OK, sure. (took me a while to understand your comment, cutting through the sarcasm :)) I could afford more for sure, being on desktop as you guessed, but 64MB didn't show any improvements over 32MB, so I didn't both going any higher. Do you have evident Keith that even larger cache sizes benefit multi-GB inserts? (8) By Keith Medcalf (kmedcalf) on 2020-04-06 14:16:38 in reply to 7 [link] [source] If the inserts are all in-order it will not make a lot of difference since not a lot of pages will be required to keep the entire changeset in the application LRU cache. I found the sweet spot where the management overhead of cache pages outweighs the benefit derived from that cache at somewhere around a quarter of a million pages. YMMV.
https://sqlite.org/forum/info/41d907af3b2eb280
CC-MAIN-2022-33
refinedweb
842
60.24
How To Use Lambda Expressions in Python They may look scary at first but they’re pretty simple Lambda expressions always freaked me out. I’m not sure why… I think the name — honoring Alonzo Church’s introduction of lambda calculus—makes them sound complex or too “mathy”. Or, maybe it’s because I had not come across a good use case to learn why they are necessary. The term anonymous function/expression also used to throw me off. Does it behave differently than a normal def function? What are the pros/cons of them? How do lambdas fit in? How I Came to Understand Lambdas It wasn’t until I revisited some JavaScript and began implementing arrow functions that lambdas clicked in my head. It helped my learning to throw out the anonymous aspect of lambdas and start to understand them as a condensed syntax for writing simple functions. Let’s take a quick look at a traditional function converted to a lambda expression. # traditionally defined function to multiply a number by itself def traditional_square(n): return n ** 2# lambda function to multiply a number by itself lambda_square = lambda n: n ** 2print(traditional_square(5)) # 25 print(lambda_square(5)) # 25 All we’ve done is re-arranged some of the components and cleaned up unnecessary syntax. Instead of using def to define a function, the word lambda is used, which is immediately followed by the parameter list. Additionally, the return keyword is omitted, further condensing the syntax. Lastly, while the definition is anonymous, we store it to the variable lambda_square, effectively naming it. Similarities and Differences Between Functions and Lambdas Now that we’ve cleared up the basic syntax of lambdas by relating them to traditional function definitions, let’s go over some of the key similarities and differences between the two. - Both functions and lambdas may accept zero, one, or many parameters. In a lambda expression, simply list your parameters after the lambdakeyword, separated by commas. - Lambdas are technically expressions, thus they can only contain other expressions within their body. This should help make sense of why lambdas do not use the returnkeyword. - Only functions can have multiple lines. Technically, a lambda can be written across multiple lines using a backslash ( \); however, the essence of the bullet is that only functions can have multiple statements, effectively doing more than one thing. Lambdas are limited to a single expression in the body. When Do I Use Lambdas? There are three opportunities to begin weaving lambda expressions into your programming practice. Refactoring “one-liner” functions to lambda notation This is the lowest hanging fruit and a good way to get comfortable with the syntax. For functions that are already single statements or can be reduced to a single statement, try to rewrite them as a lambda expression, similar to what I showed above. 2. The .sort() list method There’s nothing special about .sort() compared to other methods that accept lambda expressions; this has just been a common use case in my experience. In a list of primitive values — think integers or strings — the list will naturally be sorted by value. scores = [54,36,75,85,13,46]scores.sort()print(scores) # [13,36,46,54,75,85] But what about complex data types such as tuples, dictionaries, or classes? You can use lambda expressions to specify how you’d like to perform the sort. scores = [("Jade",21),("Rab",110),("Sylvando",39),("Erik",19)]scores.sort(key=lambda t: t[1]) # sort by 2nd value in tupleprint(scores) """ [ ("Erik",19), ("Jade",21), ("Sylvando,39), ("Rab",110)) ] In the example above, we define the key to sort by as the result of our lambda expression. Each item in the list is set to t and the value in t[1] is used to order the tuples. 3. The filter() function Similar to .sort(), this function takes a function as the first argument. The second argument is an iterable such as a list. Taking the same list of tuples from above, we can create a filtered iterator. scores = [("Jade",21),("Rab",110),("Sylvando",39),("Erik",19)]result = filter(lambda t: t[1] > 25, scores)print(list(result)) # [("Rab",110),("Sylvando",39)] There are a few nuances with the filter() function that I want to clarify. The result of the function is stored in a variable result because unlike the .sort() method, filter() does not modify the original data. The need to create a list is because a filter object is returned that points to the filtered version of the iterator. If we try to print without creating a list, the output will be something like <filter object at 0x7f3fb03ce7d0>. Conclusion I hope this introduction to lambda expressions helps take away some of the fear and apprehension. If you have other examples of simple lambdas that helped you get over the hump then please share them!
https://medium.com/better-programming/how-to-use-lambda-expressions-in-python-a96330b513d4?source=post_page-----a96330b513d4----------------------
CC-MAIN-2020-05
refinedweb
812
54.32
I wrote a tiny program to get a rough estimate of the heap size (I know I could probably have just googled it, but this seemed more fun and I thought it would be a quick simple thing). This is the whole program: #include <stdio.h> #include <stdlib.h> void main() { unsigned long long alloc_size = 1024; unsigned long long total = 0; unsigned int i = 0; void* p = 0; while(alloc_size >= 16) { p = malloc(alloc_size); if (p) { total += alloc_size; i++; printf("%u)\tAllocated %llu bytes\tTotal so far %llu\n", i, alloc_size, total); alloc_size *= 2; } else { alloc_size /= 2; } } printf("Total alloctions: %llu bytes in %u allocations", total, i); } I ran this, and was surprised by 2 things: 42) Allocated 65536 bytes Total so far 28337044480 43) Allocated 16384 bytes Total so far 28337060864 44) Allocated 16384 bytes Total so far 28337077248 45) Allocated 16384 bytes Total so far 28337093632 46) Allocated 16384 bytes Total so far 28337110016 47) Allocated 32768 bytes Total so far 28337142784 48) Allocated 8192 bytes Total so far 28337150976 49) Allocated 8192 bytes Total so far 28337159168 50) Allocated 16384 bytes Total so far 28337175552 51) Allocated 32768 bytes Total so far 28337208320 52) Allocated 65536 bytes Total so far 28337273856 53) Allocated 131072 bytes Total so far 28337404928 54) Allocated 262144 bytes Total so far 28337667072 55) Allocated 16384 bytes Total so far 28337683456 56) Allocated 8192 bytes Total so far 28337691648 57) Allocated 4096 bytes Total so far 28337695744 As you can see, this is after it already reached the peak allocation size and is on it's way down. Between allocations #42 and #43, it would have tried to allocate 32768 bytes and failed. Same after each of allocations #43 - #45. So how did it suddenly manage it at #47? You can see the same thing at #50 - #54. And this is only a sample. This same behavior happened multiple times in the total of 272 allocations in this particular run. I hope this was not to long, but I am really confused and would be glad for any light shed on this. EDIT I should add that this is on a Win7 64bit machine with mingw-w64 64bit gcc compiler, no compiler flags On Windows, a memory allocation (commit) will succeed if there is enough paging file space to back it. The amount of space available in the paging file can change due to actions by other processes reserving and releasing memory. On Windows, malloc is a thin wrapper around HeapAlloc, which is built on VirtualAlloc. VirtualAlloc will allow you to reserve and/or commit memory. Reserving means setting aside a range of the process's virtual address space. A reservation succeeds if the range of virtual addresses is available. It doesn't mean that memory is available, just that those addresses won't be used for anything else. Committing means setting aside spacing in the paging file. A commit succeeds if the paging file has enough free space to back the commit. Accessing reserved but not-yet-committed memory is an error and will probably crash. Accessing committed memory may trigger page faults, which the system handles by mapping those pages to actual RAM. If necessary, some RAM will be copied out to the paging file (which is guaranteed to have enough space because the commit succeeded), and then that RAM is re-purposed for the access that originally triggered the page fault. Thus accessing committed memory always succeeds. Windows Heaps use VirtualAlloc (and related functions) under the hood. Internally, a heap starts with an initial reservation, only part of which is committed. A HeapAlloc can fail if: (1) it exhausts its initial reservation or (2) it can't commit more pages because there isn't enough free space in the paging file. When it succeeds, HeapAlloc returns pointers to committed memory, so accessing memory from a successful HeapAlloc always succeeds. Since malloc is just a thin wrapper on HeapAlloc, the preceding paragraph applies to malloc as well. There's an extra wrinkle in that HeapAlloc handles large allocations separately. I'm not sure if these come from its initial reservation or if they're distinct blocks. The behavior of baruch's program suggests that it's running into the limit of available memory in the paging file. The available space in the paging file normally varies as other processes go about their business, so it's not surprising to seem some allocations fail and others succeed as you're near this limit. Also, the system might adjust the size of the paging file based on perceived demand, policy, and available disk space. So if you hit the limit once, but try again later, you might find that the limit is higher. When you call malloc, what actually happens is that you're allocating virtual memory. Once you try to access that memory, it triggers the OS (kernel) to allocate the actual, physical memory and map the actual memory address onto that virtual address (your pointer). Most, if not all, modern systems will gladly return a pointer even though the memory is, at the time you call malloc not available. Or at least: not available in its required form (ie as a contiguous block of memory). malloc has to return a pointer to a contiguous block of memory (if not, pointer arithmetic wouldn't be possible). So say you have 2gigs of memory available, it's very likely that that memory won't be available as a contiguous block, whereas allocating 2 gigs in chunks will work perfectly fine. This can, in part, explain why you see memory being allocated in larger chunks, then all of a sudden, you're allocating the same amount of memory as 2 chunks (because of your dividing the size by 2). Now, at no particular point are you actually writing to that memory. What you need to understand is that, unless you access this allocated virtual memory, it needn't be mapped to physical memory. Some systems, like Linux, will not allocate physical memory until you actually access the malloc'ed block. When this happens, it triggers the kernel to actually go in and allocate physical memory. That physical memory address is than mapped onto the virtual address. This is called optimistic allocation. Because most (if not all) modern system use optimistic allocation, they can allow processes to allocate more memory than is actually available at the time. What matters is that this memory is available by the time the process is actually starting to use it. Something you don't do. When you call free on malloc'ed memory that you've never used, all that you actually release is virtual memory. The physical memory remains untouched. If you have written to heap memory, and then call free, it's likely that block of memory is not always returned to the system directly (that's not really the job of free). Next time you call malloc, it's very possible that the newly allocated memory will be taken from the block you just free'd. But these are implementation details that would take us too far. In cases like this, I like to use silly analogies using real-world situations: malloc isn't like planting a flag in a chunk of memory so that nothing else, in any way shape or form is allowed to access that memory. It's more like booking a reservation in a restaurant. Restaurants often over-book, because they expect people not to show up, or to cancel. 99.99% of the time, when you arrive at the restaurant, there will be a table available for you. (the restaurant allocated the table optimistically). If you don't show up (ie you don't access the memory), the table is available for other people to use. If you did arrive, sat down and ate your dinner (write to memory), you free the table by paying the bill and leaving. What the restaurant owner does with the table is not your concern. They might have an outstanding reservation for someone else who will arrive 10 minutes after you left. If so, the restauranteurs allocated the same resource twice, but that didn't cause problems simply because the resource was free'd by the time it was needed elsewhere. This elaborate analogy is, essentially, how and why optimistic allocation works. Since the Operating System has the responsibility to manage the available memory for the user, you cannot expect a linear behaviour of the quantity of memory available at the moment you call your malloc. Between two steps, OS can free an amount of memory doing a swap to the Hard Disk or to another area of the RAM Memory, even if you don't call free explcitly. That's why you expect a failure but malloc is executed with success. Short answer: OS can free the available memory even if you do not call it.
http://m.dlxedu.com/m/askdetail/3/6b79ab5064077e160e9d2c538bbf0613.html
CC-MAIN-2018-39
refinedweb
1,492
59.33
McDonald's Corp (Symbol: MCD). So this week we highlight one interesting put contract, and one interesting call contract, from the September expiration for MCD. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $145 strike, which has a bid at the time of this writing of $2.04. Collecting that bid as the premium represents a 1.4% return against the $145 commitment, or a 5.8% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Turning to the other side of the option chain, we highlight one call contract of particular interest for the September expiration, for shareholders of McDonald's Corp (Symbol: MCD) looking to boost their income beyond the stock's 2.5% annualized dividend yield. Selling the covered call at the $155 strike and collecting the premium based on the $2.86 $155 would be lost if the stock rises there and is called away, but MCD shares would have to climb 2% from current levels for that to happen, meaning that in the scenario where the stock is called, the shareholder has earned a 3.8% return from this trading level, in addition to any dividends collected before the stock was called. Top YieldBoost MCD.
http://www.nasdaq.com/article/one-put-one-call-option-to-know-about-for-mcdonalds1-cm805208
CC-MAIN-2017-43
refinedweb
209
62.98
In part one of two book excerpts on JSP Overview from JavaServer Pages, 2nd Edition, understand the problem with Servlets as well as the anatomy of a JSP page. JSP is the latest Java technology for web application development and is based on the servlet technology introduced in the previous chapter. While servlets are great in many ways, they are generally reserved for programmers. In this chapter, we look at the problems that JSP technology solves, the anatomy of a JSP page, the relationship between servlets and JSP, and how the server processes a JSP page. In any web application, a program on the server processes requests and generates responses. In a simple one-page application, such as an online bulletin board, you don't need to be overly concerned about the design of this piece of code; all logic can be lumped together in a single program. However, when the application grows into something bigger (spanning multiple pages, using external resources such as databases, with more options and support for more types of clients), it's a different story. The way your site is designed is critical to how well it can be adapted to new requirements and continue to evolve. The good news is that JSP technology can be used as an important part in all kinds of web applications, from the simplest to the most complex. Therefore, this chapter also introduces the primary concepts in the design model recommended for web applications and the different roles played by JSP and other Java technologies in this model. In many Java servlet-based applications, processing the request and generating the response are both handled by a single servlet class. Example 3-1 shows how a servlet class often looks. Example 3-1: A typical servlet class public class OrderServlet extends HttpServlet { public void doGet((HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter( ); if (isOrderInfoValid(request)) { saveOrderInfo(request); out.println("<html>"); out.println(" <head>"); out.println(" <title>Order Confirmation</title>"); out.println(" </head>"); out.println(" <body>"); out.println(" <h1>Order Confirmation</h2>"); renderOrderInfo(request); out.println(" </body>"); out.println("</html>"); } ... If you're not a programmer, don't worry about all the details in this code. The point is that the servlet contains request processing and business logic (implemented by methods such as isOrderInfoValid( ) and saveOrderInfo( )), and also generates the response HTML code, embedded directly in the servlet code using println( ) calls. A more structured servlet application isolates different pieces of the processing in various reusable utility classes and may also use a separate class library for generating the actual HTML elements in the response. Even so, the pure servlet-based approach still has a few problems: Thorough Java programming knowledge is needed to develop and maintain all aspects of the application, since the processing code and the HTML elements are lumped together. Changing the look and feel of the application, or adding support for a new type of client (such as a WML client), requires the servlet code to be updated and recompiled. It's hard to take advantage of web-page development tools when designing the application interface. If such tools are used to develop the web page layout, the generated HTML must then be manually embedded into the servlet code, a process which is time consuming, error prone, and extremely boring. Adding JSP to the puzzle lets you solve these problems by separating the request processing and business logic code from the presentation, as illustrated in Figure 3-1. Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as in a regular web page, and add a few JSP elements to generate the dynamic parts of the page. The request processing can remain the domain of the servlet, and the business logic can be handled by JavaBeans and EJB components. Figure 3-1. Separation of request processing, business logic, and presentation As I mentioned before, separating the request processing and business logic from presentation makes it possible to divide the development tasks among people with different skills. Java programmers implement the request processing and business logic pieces, web page authors implement the user interface, and both groups can use best-of-breed development tools for the task at hand. The result is a much more productive development process. It also makes it possible to change different aspects of the application independently, such as changing the business rules without touching the user interface. This model has clear benefits even for a web-page author without programming skills, working alone. A page author can develop web applications with many dynamic features, using the JSP standard actions and the JSTL libraries, as well as Java components provided by open source projects and commercial companies. A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each request, as shown in Figure 3-2. Figure 3-2. Template text and JSP elements Everything in the page that isn't a JSP element is called template text. Template text can be any text: HTML, WML, XML, or even plain text. Since HTML is by far the most common web-page language in use today, most of the descriptions and examples in this book use HTML, but keep in mind that JSP has no dependency on HTML; it can be used with any markup language. Template text is always passed straight through to the browser. When a JSP page request is processed, the template text and dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser. In the next and last installment, get an introduction JSP processing and JSP application design with MVC. Hans Bergsten is the founder of Gefion Software and author of O'Reilly's JavaServer Pages, 3rd Edition. Return to ONJava.com.
http://oreillynet.com/lpt/a/2556
CC-MAIN-2013-20
refinedweb
985
50.77
Hello, I'm wondering if there is a way to use the built-in export function on multiple files. The formatting the built-in export uses is exactly what I'm looking for, just with multiple files. The tutorial in the scripting section creates a file that looks different and did not work for me. Is there a ruby file somewhere in the application data that performs this export? If so, I can write my own script that will iterate through a folder and perform the logic to create an export for each file. If there is anymore information I can provide, please let me know. Thank you!! asked 01 Sep '15, 17:54 ccp10 21●1●1●4 accept rate: 0% There is a Ruby file that implements the frame-by-frame export but it needs tweaking to work with video files that are not 29.97 FPS... and it might not be as up-to-date as the internal function. Here's a link to the file: export by frame script I'm not sure how comfortable you are with Java and Ruby, but if you just need a reference into the internal exporting routines, check out the GitHub page for the exporting class : exporting Java class Here's some sample Ruby code to make use of the exporting class: import org.datavyu.controllers.ExportDatabaseFileC; outfn1 = File.expand_path("~/Desktop/export.csv") outfn2 = File.expand_path("~/Desktop/export_by_frame.csv") exporter = ExportDatabaseFileC::new() exporter::exportAsCells(outfn1, $db) exporter::exportByFrame(outfn2, $db) import org.datavyu.controllers.ExportDatabaseFileC; outfn1 = File.expand_path("~/Desktop/export.csv") outfn2 = File.expand_path("~/Desktop/export_by_frame.csv") outfn1 = File.expand_path("~/Desktop/export.csv") outfn2 = File.expand_path("~/Desktop/export_by_frame.csv") exporter = ExportDatabaseFileC::new() exporter::exportAsCells(outfn1, $db) exporter::exportByFrame(outfn2, $db) If you wanted to run it over multiple files, you would just put the relevant parts inside a loop with a loadDB(). Again, I'm not sure how experienced you are with programming so if any of this doesn't make sense, don't hesitate to ask! answered 01 Sep '15, 20:24 Shohan Hasan ♦♦ 531●1●2●6 accept rate: 14% Shohan, Thank you so much for your reply! This is exactly what I was looking for, and I was able to get the script working immediately. I really appreciate your help! answered 02 Sep '15, 10:06 export ×25 file ×4 multiple ×4 question asked: 01 Sep '15, 17:54 question was seen: 3,574 times last updated: 02 Sep '15, 10:06? Scripts for better exports error when running scripts to print multiple files First time here? Check out the FAQ!
http://datavyu.org/support/questions/741/built-in-export-function-on-multiple-files
CC-MAIN-2018-30
refinedweb
434
55.95
Applications can access peripheral devices through file system functions, such as CreateFile. The file I/O operations are redirected to the stream interface. The following table shows descriptions and examples for the three device namespaces. Three letter prefix, followed by a number between 0 and 9, followed by a colon. "LPT2:" $bus mount point, followed by the bus name, bus number, device number, and function number. "\$bus\PCMCIA_0_0_0" $device mount point, followed by a three letter prefix representing the device, followed by a number. "\$device\COM7" In the example, COM7 is device 0, function 0 on PCMCIA bus 0. CreateFile can accept any of these names. Each name space returns handles with different properties. The namespaces containing mount points support more than 10 instances of a device with the same three letter prefix. For example, COM23 can represent serial port 23. The device file name prefix consists of three uppercase letters that identify which device file name corresponds to a particular stream interface. When you implement the stream interface, you designate the three-letter prefix. The prefix can be any three letters, although you should use a common prefix if your driver is the same class of device as other drivers. For example, drivers for serial devices, such as modems, could use the common prefix COM, even though other drivers might already be using that prefix. Your driver can distinguish itself from other drivers by using a different index. The prefix serves two purposes. First, the prefix identifies all possible device file names that can access the stream interface driver. Second, the prefix tells the operating system what entry-point file names to expect in the stream interface DLL. For example, to implement a device driver for a PC Card pager, you could choose PGR as the three-letter prefix, which in turn would dictate entry-point names, such as PGR_Init, PGR_IOControl, and so on. The prefix is stored in a registry value called Prefix, which is located within the key for the driver. Typically, the setup utility that installs a driver creates this registry value, along with other values that the driver needs. If the Prefix subkey does not exist, then there must be initialization and de-initialization entry points. The index differentiates similar devices that the stream interface manages. The index is the digit that follows the prefix. By default, Device Manager indexes logically from 1 through 9, with 1 corresponding to the first device file name. If you require a tenth device file name, use 0 as the index. If you must number your device file names starting at an index other than 1, specify a starting index in a registry value called Index within the registry key for your driver. This is often necessary if your stream interface driver serves a device that should use a common prefix, such as COM. For example, COM1:, COM2:, and COM3: usually correspond to built-in serial port hardware. If your driver is for a serial device, such as a packet-radio modem, it should appear as a COM port because modem software often assumes that modems are connected to COM ports. You could specify an Index value of 4 to differentiate your serial device from ones that are built into the hardware. If you specify Index, rather than letting Device Manager assign indexes, by default, your driver will support only one device because Device Manager can register only one device file name. If you need to specify Index but need more than one device file name, you have two options. The initialization function can register additional device file names with the ActivateDeviceEx function, or the setup utility can create additional sets of registry keys, each with a different index, when your driver is installed. Accesses to device drivers in the $device and $bus namespaces are automatically routed to the CreateFile entry point registered with RegisterAFSEx. Device handles allow direct requests to the bus driver. For example, a control panel application might want to unload a device driver or force the bus driver to re-enumerate its child devices. Calls to CreateFile implicitly call the device driver's XXX_Open (Device Manager) function. Device Manager can notify the driver that a particular handle will be used for device-level operations by adding a bit to the access rights mask passed into the driver's XXX_Init (Device Manager) function. This bit is added based on the namespace used to open the handle and cannot be one of the parameters to CreateFile. For reference, the driver can associate the access bit with the open data it returns from its XXX_Open function when processing other APIs. The following table shows how to obtain a device handle or a file handle. "COM7:" Returns a normal file handle to the device. This is the legacy naming convention. "\$device\COM7" Returns a normal file handle, which might be for a device that cannot be named using the legacy naming convention. "\$bus\PCMCIA_0_0_0" Returns a device handle to device 0, function 0 on PCMCIA bus 0. Although this handle can be manipulated using the same APIs as a normal file handle, the operations it enables might be different and access to these handles might be secured differently by the OS. All three device paths might be implemented by the same driver. Paths 1 and 2 are equivalent. Path 3 can be used for power management, but not for data traffic. The appropriate method for determining which devices support the new handle is to rely on advertised interfaces. A bus driver can advertise a specified GUID to indicate that the bus driver supports unloading and reloading drivers. A bus driver can also advertise another GUID to indicate that the bus driver supports power management on child devices. Similarly, a new GUID might indicate that Power Manager IOCTLs should use device handles.
http://msdn.microsoft.com/en-us/library/aa930218.aspx
crawl-002
refinedweb
972
53.81
- NAME - SYNOPSIS - DESCRIPTION - EXPORTED SYMBOLS - FUNCTIONS - FUNCTIONS YOUR FILESYSTEM MAY IMPLEMENT - - opendir - readdir - releasedir - fsyncdir - init - destroy - access - create - ftruncate - fgetattr - lock - utimens - bmap - ioctl - poll - write_buf - read_buf - flock - fallocate - EXAMPLES - AUTHOR - SEE ALSO NAME Fuse - write filesystems in Perl using FUSE SYNOPSIS use Fuse; my ($mountpoint) = ""; $mountpoint = shift(@ARGV) if @ARGV; Fuse::main(mountpoint=>$mountpoint, getattr=>"main::my_getattr", getdir=>"main::my_getdir", ...); DESCRIPTION This lets you implement filesystems in perl, through the FUSE (Filesystem in USErspace) kernel/lib interface. FUSE expects you to implement callbacks for the various functions.. EXPORTED SYMBOLS None by default. You can request all exportable symbols by using the tag ":all". You can request the extended attribute symbols by using the tag ":xattr". This will export XATTR_CREATE and XATTR_REPLACE. FUNCTIONS Fuse::main separated list of mount options to pass to the FUSE kernel module. At present, it allows the specification of the allow_other argument when mounting the new FUSE filesystem. To use this, you will also need 'user_allow_other' in /etc/fuse.conf as per the FUSE documention mountopts => "allow_other" or mountopts => "" - threaded => boolean This turns FUSE multithreading on and off. The default is 0, meaning your FUSE script will run in single-threaded mode. Note that single-threaded mode also means that you will not have to worry about reentrancy, though you will have to worry about recursive lookups. In single-threaded mode, FUSE holds a global lock on your filesystem, and will wait for one callback to return before calling another. This can lead to deadlocks, if your script makes any attempt to access files or directories in the filesystem it is providing. (This includes calling stat() on the mount-point, statfs() calls from the 'df' command, and so on and so forth.) It is worth paying a little attention and being careful about this. Enabling multithreading will cause FUSE to make multiple simultaneous calls into the various callback functions of your perl script. If you enable threaded mode, you can enjoy all the parallel execution and interactive response benefits of threads, and you get to enjoy all the benefits of race conditions and locking bugs, too. Please also ensure any other perl modules you're using are also thread-safe. (If enabled, this option will cause a warning if your perl interpreter was not built with USE_ITHREADS, or if you have failed to use threads or threads::shared.) - nullpath_ok => boolean This flag tells Fuse to not pass paths for functions that operate on file or directory handles. This will yield empty path parameters for functions including read, write, flush, release, fsync, readdir, releasedir, fsyncdir, truncate, fgetattr and lock. If you use this, you must return file/directory handles from open, opendir and create. Default is 0 (off). Only effective on Fuse 2.8 and up; with earlier versions, this does nothing. - utimens_as_array => boolean This flag causes timestamps passed via the utimens() call to be passed as arrays containing the time in seconds, and a second value containing the number of nanoseconds, instead of a floating point value. This allows for more precise times, as the normal floating point type used by Perl (double) loses accuracy starting at about tenths of a microsecond. - nopath => boolean Flag indicating that the path need not be calculated for the following operations: read, write, flush, release, fsync, readdir, releasedir, fsyncdir, ftruncate, fgetattr, lock, ioctl and poll Closely related to nullpath_ok, but if this flag is set then the path will not be calculated even if the file wasn't unlinked. However the path can still be defined if it needs to be calculated for some other reason. Only effective on Fuse 2.9 and up. - utime_omit_ok => boolean Flag indicating that the filesystem accepts special UTIME_NOW and UTIME_OMIT values in its utimensoperation. If you wish to use these constants, make sure to include the ':utime' flag when including the Fuse module, or the ':all' flag. Only effective on Fuse 2.9 and up. Fuse::fuse_get_context use Fuse "fuse_get_context"; my $caller_uid = fuse_get_context()->{"uid"}; my $caller_gid = fuse_get_context()->{"gid"}; my $caller_pid = fuse_get_context()->{"pid"}; Access context information about the current Fuse operation. Fuse::fuse_version Indicates the Fuse version in use; more accurately, indicates the version of the Fuse API in use at build time. If called in scalar context, the version will be returned as a decimal value; i.e., for Fuse API v2.6, will return "2.6". If called in array context, an array will be returned, containing the major, minor and micro version numbers of the Fuse API it was built against. Fuse::fuse_buf_size Computes the total size of a buffer vector. Applicable for read_buf and write_buf operations. Fuse::fuse_buf_copy Copies data from one buffer vector to another. Primarily useful if a buffer vector contains multiple, fragmented chunks or if it contains an FD buffer instead of a memory buffer. Applicable for write_buf. Fuse::notify_poll Only available if the Fuse module is built against libfuse 2.8 or later. Use fuse_version() to determine if this is the case. Calling this function with a pollhandle argument (as provided to the poll operation implementation) will send a notification to the caller poll()ing for I/O operation availability. If more than one pollhandle is provided for the same filehandle, only use the latest; you *can* send notifications to them all, but it is unnecessary and decreases performance.. Fuse::pollhandle_destroy Only available if the Fuse module is built against libfuse 2.8 or later. Use fuse_version() to determine if this is the case. This function destroys a poll handle (fed to your program through poll). When you are done with a poll handle, either because it has been replaced, or because a notification has been sent to it, pass it to this function to dispose of it safely.. FUNCTIONS YOUR FILESYSTEM MAY IMPLEMENT getattr); you wish to provide sub-second precision timestamps, they may be passed either as the fractional part of a floating-point value, or as a two-element array, passed as an array ref, with the first element containing the number of seconds since the epoch, and the second containing the number of nanoseconds. This provides complete time precision, as a floating point number starts losing precision at about a tenth of a microsecond. So if you really care about that sort of thing... readlink Arguments: link pathname. Returns a scalar: either a numeric constant, or a text string. This is called when dereferencing symbolic links, to learn the target. example rv: return "/proc/self/fd/stdin"; getdir Arguments: Containing directory name. Returns a list: 0 or more text strings (the filenames), followed by a numeric errno (usually 0). This is used to obtain directory listings. It's opendir(), readdir(), filldir() and closedir() all in one call. example rv: return ('.', 'a', 'b', 0); mknod Arguments: Filename, numeric modes, numeric device Returns an errno (0 upon success, as usual). This function is called for all non-directory, non-symlink nodes, not just devices. mkdir Arguments: New directory pathname, numeric modes. Returns an errno. Called to create a directory. unlink Arguments: Filename. Returns an errno. Called to remove a file, device, or symlink. rmdir Arguments: Pathname. Returns an errno. Called to remove a directory. symlink Arguments: Existing filename, symlink name. Returns an errno. Called to create a symbolic link. rename Arguments: old filename, new filename. Returns an errno. Called to rename a file, and/or move a file from one directory to another. link Arguments: Existing filename, hardlink name. Returns an errno. Called to create hard links. chmod Arguments: Pathname, numeric modes. Returns an errno. Called to change permissions on a file/directory/device/symlink. chown Arguments: Pathname, numeric uid, numeric gid. Returns an errno. Called to change ownership of a file/directory/device/symlink. truncate Arguments: Pathname, numeric offset. Returns an errno. Called to truncate a file, at the given offset. utime Arguments: Pathname, numeric actime, numeric modtime. Returns an errno. Called to change access/modification times for a file/directory/device/symlink. open Arguments: Pathname, numeric flags (which is an OR-ing of stuff like O_RDONLY and O_SYNC, constants you can import from POSIX), fileinfo hash reference. Returns an errno, a file handle (optional). No creation, or truncation flags (O_CREAT, O_EXCL, O_TRUNC) will be passed to open(). The fileinfo hash reference contains flags from the Fuse open call which may be modified by the module. The only fields presently supported are: direct_io (version 2.4 onwards) keep_cache (version 2.4 onwards) nonseekable (version 2.8 onwards) Your open() method needs only check if the operation is permitted for the given flags, and return 0 for success. Optionally a file handle may be returned, which will be passed to subsequent read, write, flush, fsync and release calls. read Arguments: Pathname, numeric requested size, numeric offset, file handle Returns a numeric errno, or a string scalar with up to $requestedsize bytes of data. Called in an attempt to fetch a portion of the file. write Arguments: Pathname, scalar buffer, numeric offset, file handle. You can use length($buffer) to find the buffersize. Returns length($buffer) if successful (number of bytes written). Called in an attempt to write (or overwrite) a portion of the file. Be prepared because $buffer could contain random binary data with NULs and all sorts of other wonderful stuff. statfs Arguments: none Returns any of the following: -ENOANO() or $namelen, $files, $files_free, $blocks, $blocks_avail, $blocksize or -ENOANO(), $namelen, $files, $files_free, $blocks, $blocks_avail, $blocksize flush Arguments: Pathname, file handle Returns an errno or 0 on success. Called to synchronise any cached data. This is called before the file is closed. It may be called multiple times before a file is closed. release Arguments: Pathname, numeric flags passed to open, file handle, flock_release flag (when built against FUSE 2.9 or later), lock owner ID (when built against FUSE 2.9 or later) Returns an errno or 0 on success. Called to indicate that there are no more references to the file. Called once for every file with the same pathname and flags as were passed to open. fsync Arguments: Pathname, numeric flags Returns an errno or 0 on success. Called to synchronise the file's contents. If flags is non-zero, only synchronise the user data. Otherwise synchronise the user and meta data. setxattr'; getxattr Arguments: Pathname, extended attribute's name Returns an errno, 0 if there was no value, or the extended attribute's value. Called to get the value of the named extended attribute. listxattr Arguments: Pathname Returns a list: 0 or more text strings (the extended attribute names), followed by a numeric errno (usually 0). removexattr Arguments: Pathname, extended attribute's name Returns an errno or 0 on success. Removes the named extended attribute (if present) from a file. opendir Arguments: Pathname of a directory Returns an errno, and a directory handle (optional) Called when opening a directory for reading. If special handling is required to open a directory, this operation can be implemented to handle that. readdir Arguments: Pathname of a directory, numeric offset, (optional) directory handle Returns a list of 0 or more entries, followed by a numeric errno (usually 0). The entries can be simple strings (filenames), or arrays containing an offset number, the filename, and optionally an array ref containing the stat values (as would be returned from getattr()). This is used to read entries from a directory. It can be used to return just entry names like getdir(), or can get a segment of the available entries, which requires using array refs and the 2- or 3-item form, with offset values starting from 1. If you wish to return the parameters to fill each entry's struct stat, but do not wish to do partial entry lists/entry counting, set the first element of each array to 0 always. Note that if this call is implemented, it overrides getdir() ALWAYS. releasedir Arguments: Pathname of a directory, (optional) directory handle Returns an errno or 0 on success Called when there are no more references to an opened directory. Called once for each pathname or handle passed to opendir(). Similar to release(), but for directories. Accepts a return value, but like release(), the response code will not propagate to any corresponding closedir() calls. fsyncdir Arguments: Pathname of a directory, numeric flags, (optional) directory handle Returns an errno or 0 on success. Called to synchronize any changes to a directory's contents. If flag is non-zero, only synchronize user data, otherwise synchronize user data and metadata. init Arguments: None. Returns (optionally) an SV to be passed as private_data via fuse_get_context(). destroy Arguments: (optional) private data SV returned from init(), if any. Returns nothing. access Arguments: Pathname, access mode flags Returns an errno or 0 on success. Determine if the user attempting to access the indicated file has access to perform the requested actions. The user ID can be determined by calling fuse_get_context(). See access(2) for more information. create Arguments: Pathname, create mask, open mode flags Returns errno or 0 on success, and (optional) file handle. Create a file with the path indicated, then open a handle for reading and/or writing with the supplied mode flags. Can also return a file handle like open() as part of the call. ftruncate Arguments: Pathname, numeric offset, (optional) file handle Returns errno or 0 on success Like truncate(), but on an opened file. fgetattr Arguments: Pathname, (optional) file handle Returns a list, very similar to the 'stat' function (see perlfunc). On error, simply return a single numeric scalar value (e.g. "return -ENOENT();"). Like getattr(), but on an opened file. lock Arguments: Pathname, numeric command code, hashref containing lock parameters, (optional) file handle Returns errno or 0 on success Used to lock or unlock regions of a file. Locking is handled locally, but this allows (especially for networked file systems) for protocol-level locking semantics to also be employed, if any are available. See the Fuse documentation for more explanation of lock(). The needed symbols for the lock constants can be obtained by importing Fcntl. utimens Arguments: Pathname, last accessed time, last modified time Returns errno or 0 on success Like utime(), but allows time resolution down to the nanosecond. By default, times are passed as "numeric" (internally these are typically represented as "double"), so the sub-second portion is represented as fractions of a second. If you want times passed as arrays instead of floating point values, for higher precision, you should pass the utimens_as_array option to Fuse::main. Note that if this call is implemented, it overrides utime() ALWAYS. bmap Arguments: Pathname, numeric blocksize, numeric block number Returns errno or 0 on success, and physical block number if successful Used to map a block number offset in a file to the physical block offset on the block device backing the file system. This is intended for filesystems that are stored on an actual block device, with the 'blkdev' option passed. ioctl Arguments: Pathname, ioctl command code, flags, data if ioctl op is a write, (optional) file handle Returns errno or 0 on success, and data if ioctl op is a read Used to handle ioctl() operations on files. See ioctl(2) for more information on the fine details of ioctl operation numbers. May need to h2ph system headers to get the necessary macros; keep in mind the macros are highly OS-dependent. Keep in mind that read and write are from the client perspective, so read from our end means data is going *out*, and write means data is coming *in*. It can be slightly confusing. poll Arguments: Pathname, poll handle ID (or undef if none), event mask, (optional) file handle Returns errno or 0 on success, and updated event mask on success Used to handle poll() operations on files. See poll(2) to learn more about event polling. Use IO::Poll to get the POLLIN, POLLOUT, and other symbols to describe the events which can happen on the filehandle. Save the poll handle ID to be passed to notify_poll and pollhandle_destroy functions, if it is not undef. Threading will likely be necessary for this operation to work. There is not an "out of band" data transfer channel provided as part of FUSE, so POLLPRI/POLLRDBAND/POLLWRBAND won't work. Poll handle is currently a read-only scalar; we are investigating a way to make this an object instead. write_buf Arguments: Pathname, offset, buffer vector, (optional) file handle. Write contents of buffer to an open file. Similar to the write method, but data is supplied in a generic buffer. Use fuse_buf_copy() to transfer data to the destination if necessary. read_buf Arguments: Pathname, size, offset, buffer vector, (optional) file handle. Store data from an open file in a buffer. Similar to the read method, but data is stored and returned in a generic buffer. No actual copying of data has to take place, the source file descriptor may simply be placed in the 'fd' member of the buffer access hash (and the 'flags' member OR'd with FUSE_BUF_IS_FD) for later retrieval. Also, if the FUSE_BUF_FD_SEEK constant is OR'd with 'flags', the 'pos' member should contain the offset (in bytes) to seek to in the file descriptor. If data is to be read, the read data should be placed in the 'mem' member of the buffer access hash, and the 'size' member should be updated if less data was read than requested. flock Arguments: pathname, (optional) file handle, unique lock owner ID, operation ID Perform BSD-style file locking operations. Operation ID will be one of LOCK_SH, LOCK_EX or LOCK_UN. Non-blocking lock requests will be indicated by having LOCK_NB OR'd into the value. For more information, see the flock(2) manpage. For the lock symbols, do: use Fcntl qw(flock); Locking is handled locally, but this allows (especially for networked file systems) for protocol-level locking semantics to also be employed, if any are available. fallocate Arguments: pathname, (optional) file handle, mode, offset, length Allocates space for an open file. This function ensures that required space is allocated for specified file. If this function returns success then any subsequent write request to specified range is guaranteed not to fail because of lack of space on the file system media. EXAMPLES There are a few example scripts in the examples/ subdirectory. These are: example.pl A simple "Hello world" type of script loopback.pl A filesystem loopback-device. like fusexmp from the main FUSE dist, it simply recurses file operations into the real filesystem. Unlike fusexmp, it only re-shares files under the /tmp/test directory. rmount.pl An NFS-workalike which tunnels through SSH. It requires an account on some ssh server (obviously), with public-key authentication enabled. (if you have to type in a password, you don't have this. man ssh_keygen.). Copy rmount_remote.pl to your home directory on the remote machine and make it executable. Then create a mountpoint subdir somewhere local, and run the example script: ./rmount.pl host /remote/dir /local/dir rmount_remote.pl A ripoff of loopback.pl meant to be used as a backend for rmount.pl. AUTHOR Mark Glines, <mark@glines.org> SEE ALSO perl, the FUSE documentation.
https://metacpan.org/pod/release/DPATES/Fuse-0.16/Fuse.pm
CC-MAIN-2015-18
refinedweb
3,183
57.37
In Golang, for every "thing", the medatata describing it is type. But there is also kind which sometimes you need to consult to get the real underlying type (if the kind is a pointer). To get a list of fields, you need to check if it is a struct or a pointer to a struct. Then, when getting a list of fields, you must check if a field is anonymous or not. That's why you need a recursion to get the field list, but in that recursion some field names can happen twice (because they are declared in different anonymous structs). Then to get/set a field by name, you need to check if the original is a struct or a pointer to a struct (again). If it is a struct you get the field value with ...FieldByName(fieldName) if it is a pointer it's ...Elem().FieldByName(fieldName), but (only) for values you can use reflect.Indirect(). For every field you have two metadata types describing it: reflect.Value and reflect.StructField. In Java, when you have a reference to Field, you have everything you need to get/set/describe that field. In short Java and Python reflection is much simpler than Golang reflection. At least, for me it is. But, since sometimes I really had to do this reflection thing, I decided to simplify it as much as possible and created go-reflector. You basically give him any value, and it gives you a simple API to work with fields, methods and tags. Example usage: import "github.com/tkrajina/go-reflector/reflector" p := Person{} // Initializing: obj := reflector.New(p) // Fields: obj.Field("Name").IsValid() val, err := obj.Field("Name").Get() err := obj.Field("Name").Set("Something") // Tags: jsonTag := obj.Field("Name").Tag("json") jsonTag := obj.Field("Name").TagExpanded("json") fieldTagsMap := obj.Field("Name").Tags() // Listing fields: fields := obj.FieldsAll() fields := obj.FieldsFlattened() fields := obj.Fields() doubleDeclaredFields := obj.FindDoubleFields() if len(doubleDeclaredFields) > 0 { fmt.Println("Detected multiple fields with same name:", doubleDeclaredFields) } // Calling methods: resp, err := obj.Method("Hi").Call("John", "Smith") if err != nil { fmt.Println("Cannot call method:", err.Error()) } if resp.IsError() { fmt.Println("Method returned an error:", resp.Error.Error()) } else { fmt.Println("Method call response:", resp.Result) } // Get all methods: for _, method := range obj.Methods() { fmt.Println("Method", method.Name(), "with input types", method.InTypes(), "and output types", method.OutTypes()) } Read the README here:.
http://tkrajina.blogspot.com/2016/05/
CC-MAIN-2017-34
refinedweb
402
62.95
getgrent, getgrnam, getgrnam_r, getgrgid, getgrgid_r, setgroupent, setgrent, endgrent— #include <grp.h>struct group * getgrent(void); struct group * getgrnam(const char *name); int getgrnam_r(const char *name, struct group *grp, char *buf, size_t bufsize, struct group **result); struct group * getgrgid(gid_t gid); int getgrgid_r(gid_t gid, struct group *grp, char *buf, size_t bufsize, struct group **result); int setgroupent(int stayopen); void setgrent(void); void endgrent(void); struct groupfound in the include file <grp.h>: struct group { char *gr_name; /* group name */ char *gr_passwd; /* group password */ gid_t gr_gid; /* group id */ char **gr_mem; /* group members */ }; programs structure pointed to by grp and store a pointer to that structure at the location pointed to by result. The structure is filled with an entry from the group database with a matching gid or name. Storage referenced by the group structure will be allocated from the memory provided with the buf parameter, which is bufsiz characters in size. The maximum size needed for this buffer can be determined with sysconf(_SC_GETGR_R_SIZE_MAX). getgrent() and getgrnam() also use the group.byname YP map and the function getgrgid() also uses the group.bygid YP map in addition to the group file, respecting the order of normal and YP entries in the group file. getgrent(), getgrnam(), and getgrgid() return a pointer to the group entry if successful; if end-of-file is reached or an error occurs a NULLpointer is returned. The setgroupent() function returns the value 1 if successful, otherwise 0. The endgrent() and setgrent() functions have no return value. The functions getgrgid_r() and getgrnam_r() update result to point to grp if a match is found or set it to NULLif no match is found or an error occurs. They return 0 on success, even if no match is found, or an error number if an error occurs; see ERRORS. getgruid_r() and getgrnam_r() functions may fail if: ERANGE] getgrent(), getgrgid(), getgrgid_r(), getgrnam(), and getgrnam_r() functions may also fail for any of the errors specified for fgets(3), getc(3), and strtoul(3). If YP is active, they may also fail due to errors caused by the YP subsystem. The setgroupent() function may fail for any of the errors specified for fopen(3). The endgrent(), getgrgid_r(), getgrnam_r(), and setgrent() functions do not set errno. getgrgid(), getgrgid_r(), getgrnam(), and getgrnam_r() are compliant with the IEEE Std 1003.1-2008 (“POSIX.1”) specification. The functions endgrent(), getgrent(), and setgrent() are compliant with the X/Open System Interfaces option of the IEEE Std 1003.1-2008 (“POSIX.1”) specification. YP support and the setgroupent() function are extensions to that specification. endgrent(), getgrent(), getgrnam(), getgrgid(), and setgrent() appeared in Version 7 AT&T UNIX. The setgroupent() function appeared in 4.3BSD-Reno. The historic function setgrfile(), which allowed the specification of alternate group databases, has been deprecated and is no longer available. possible.
https://man.openbsd.org/OpenBSD-6.1/getgrent.3
CC-MAIN-2018-39
refinedweb
468
52.9
msgget - get a message queue identifier #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int msgget ( key_t key, int msgflg )IPC_CREAT is nonzero). The presence in msgflg of the fields IPC_CREAT and IPC_EXCL plays the same role, with respect to the existence verified, and a check is made to see if it is marked for destruction. If successful, the return value will be the message queue identifier (a nonnegative integer), otherwise -1 with errno indicating the error. For a failing return, errno will be set to one among the following values:: Use of IPC_PRIVATE does not actually prohibit other processes from getting access to the allocated message queue. As for the files, there is currently no intrinsic way for a process to ensure exclusive access to a message queue. Asserting both IPC_CREAT and IPC_EXCL in msgflg only ensures (on success) that a new message queue will be created, it doesn't imply exclusive access to the message queue. SVr4, SVID. SVr4 does not document the EIDRM error code. ftok(3), ipc(5), msgctl(2), msgsnd(2), msgrcv(2) 9 pages link to msgget(2):
http://wiki.wlug.org.nz/msgget(2)
CC-MAIN-2015-27
refinedweb
188
55.34
Difference between revisions of "PEG:C++ Lesson 2 for Pascal Users" Revision as of 03:15, 20 November 2009 This lesson is brief and discusses the basic "mechanics" of C++. It's not going to teach you to code anything, but you need to know this anyway (some of you might have guessed by yourselves). C++ code consists of a sequence of statements to be evaluated one after another. For now all your programs will execute statements one-by-one from top to bottom between the opening brace { and the closing brace } following int main(). These are like the begin and end reserved words in Pascal. The last line of code, the final statement, should read return 0;. (This is not strictly necessary; the program will work without it. However, in larger and more complicated programs, it tells anyone reading the code that execution stops once it reaches that line.) All simple statements in C++ end with semicolons, just like in Pascal. (But in C++, even the final statement before } needs a semicolon. In C++, semicolons are statement terminators, unlike in Pascal, in which they are statement separators.) That code above int main() --- the #include <iostream> and using namespace std; --- those lines should remain in all C++ programs you write, for the time being. We will explain at a later time what they really mean. For now, think of them as being like uses crt;; they do not perform exactly the same function, but it's the same general idea. You need #include <iostream> in order to perform C++-style input/output. You may have noticed that the code following // was colored green when you pasted the previous lesson into Visual C++. In general, anything on a line following // is treated as a comment, but once you get to the next line it's not a comment anymore. There are also Pascal-style comments, which are also in green: /* starts a comment and */ ends it, just like { and } in Pascal (these comments can span multiple lines.) Execution of C++ code can be considered to progress generally toward evaluation, with everything else merely a side effect. Thus, statements like 3+5; are perfectly legal in C++; they can be evaluated, and the fact that they don't actually do anything is irrelevant. The statement cout << "Hello Fox" << endl; has a value too; explaining what this value is and how it is obtained will come later on. Even though this statement's purpose is to perform an action --- printing text to standard output --- the compiler sees it as a request to evaluate the statement, incidentally performing a sequence of steps along the way that happen to print out the text.
https://wcipeg.com/wiki/index.php?title=PEG:C%2B%2B_Lesson_2_for_Pascal_Users&diff=prev&oldid=120
CC-MAIN-2020-10
refinedweb
448
68.3
The Data Science Lab C# developers who want to wring more meaningful info from large sets of data should get cozy with the statistical computing language known as R. Let's get familiar with R in this new series. The R language, which is used for statistical computing, is one of the fastest-growing technologies among my colleagues who are C# programmers. I believe this is because of the increasing volume of data collected by software systems, and the need to analyze that data. A familiarity with R can be a valuable addition to your technical skill set. The R language is an open source GNU project and is free software. R was derived from a language called S (for "statistics") which was created at the Bell Laboratories in the 1970s. There are many excellent online tutorials for R but most of those tutorials assume you are a university student studying statistics. This article assumes you are a .NET developer who wants to get up to speed with R quickly. A good way to see where this article is headed is to take a look at an example interactive R session shown in Figure 1. The demo session has two examples. The first few commands show an example of linear regression, which in my opinion is the Hello World technique of statistical computing. The second set of R commands show what's called the t-test for two unpaired means. The R Web site has links to several mirror sites where you can download and install R. The install is a simple self-extracting executable. R is supported on Windows XP and newer OSes, and also on most common non-Windows platforms. I have installed R on Windows 7 and Windows 8 and Windows 10 machines without any issues. By default the installation process gives you both 32-bit and 64-bit versions of R. This article assumes you have at least intermediate level C# programming skills (so you can understand the explanations of the similarities between C# and R), but does not assume you know anything about R. In addition to explaining R techniques, this article presents a C# demo program that shows how to perform a t-test so you can compare C# and R. The C# program is a bit too long to present in its entirety but the complete source code is available in the download that accompanies this article. Linear Regression Analysis Using R I installed R version 3.1.2 and accepted the default location of a C:\Program Files\R\R-3.2.1 directory. To launch the simple R shell shown in Figure 1, I navigated to the R.exe program located in the 64-bit bin\x64 subdirectory and double-clicked on it. The first set of R commands in Figure 1 show an example of linear regression. Linear regression is a statistical technique that's used to describe the relationship between a numeric variable, called the dependent variable, and one or more explanatory variables, called the independent variables. The independent variables can be either numeric or categorical. When there is just one independent explanatory/predictor variable, the technique is usually called simple linear regression. When there are two or more independent variables, as in the demo, the technique is usually called multiple linear regression. Here, the goal is to predict a person's annual income from their occupation, age and some measure of technical skill. Looking at Figure 1, you'll immediately notice that using R is quite a bit different from using C#. Although it's possible to write R scripts, R is most often used (at least among my colleagues) in an interactive mode in a command shell. Before doing the R linear regression analysis, I created an eight-item, comma-delimited text file named Income.txt in directory C:\IntroductionToR with this content: Occupation,Age,Tech,Income "Developer",28,7.0,64.0 "Developer",41,8.0,82.0 "Developer",33,6.0,58.0 "Manager ",37,8.0,70.0 "Manager ",54,3.0,54.0 "Quality ",26,6.0,38.0 "Quality ",29,5.0,42.0 "Quality ",31,7.0,48.0 This file is supposed to represent the annual incomes of people with their job occupation, age and some measure (0.0 to 10.0) of technical expertise. The idea is to predict Income values in the last column from the Occupation, Age and Tech values. Two of the Occupation values (Developer and Manager) have embedded spaces for better readability. The R prompt is indicated by the '>' token in the shell. The first statement typed in Figure 1 begins with the '#' character, which is the R token to indicate a comment. After the comment, the first three R commands in the linear regression analysis are: > setwd("C:\\InroductionToR") > table <- read.table("Income.txt", header=TRUE, sep=",") > print(table) The first command sets the working directory so I wouldn't have to fully qualify the path to the source data file. Instead of using the "\\" token as is common with C#, I could have used "/" as is common on non-Windows platforms. The second command uses the built-in read.table function to load the data into memory in a table object named table. Notice that R uses both anonymous and named parameters. The parameter named header tells R whether the first line is header information (TRUE, or T in shortened form) or not (FALSE or F). R is case-sensitive. In R, to assign values to variables or objects, you can usually use either the "<-" operator or the '=' operator. The choice is mostly a matter of personal preference. I typically use "<-" for object assignment and "=" for parameter value assignment. The sep (separator) parameter indicates how values on each line are separated. For example, "\t" would indicate tab-delimited values, and " " would indicate space-delimited values. In R, the '.' character is often used rather than the '_' character to create variable and function names that are easier to read. If you are a very experienced .NET developer, the common R use of the period character in variable and function names can take some time to get used to. The print function displays the data table in memory. The print function has many optional parameters. Notice that the output in Figure 1 displays data item indices starting at 1. For array, matrix and object indices, R is a 1-based language rather than 0-based as in the C# language. The linear regression analysis is performed by these two R commands: > model <- lm(table$Income ~ (table$Occupation + table$Age + table$Tech)) > summary(model) You can interpret the first command as, "Store into an object named 'model' the result of the lm (linear model) function analysis where the dependent variable to predict is the Income column in the table object (table$Income), and the independent predictor variables are Occupation, Age and Tech." The second command means, "Display just the basic results of the analysis stored in the object named model." The lm function generates a large amount of information. Suppose you wanted to predict the Income value when the input values are Occupation = Manager, Age = 37 and Tech = 8.0. (Notice that this corresponds to data item [4] that has an actual Income value of 70.0.) To make a prediction you'd use the values in the Estimate column: Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -3.9883 16.9005 -0.236 0.8286 table$OccupationManager -7.1989 4.9508 -1.454 0.2419 table$OccupationQuality -14.6279 4.2709 -3.425 0.0417 * table$Age 0.8850 0.3152 2.808 0.0674 . table$Tech 5.9856 1.2099 4.947 0.0158 * If X represents the independent variables, and if Y represents the predicted Income, then: X = (Developer = NA, Manager = 1, Quality = 0, Age = 37, Tech = 8.0) Y = -3.9883 + (-7.1989)(1) + (-14.6279)(0) + (0.8850)(37) + (5.9856)(8.0) = -3.9883 + (-7.1989) + (0) + (32.745) + (47.8848) = 69.44 Notice the predicted Income, 69.44, is very close to the actual Income, 70.0. In words, to make a prediction using the model, you calculate a linear sum of products of the Estimate values times their corresponding X values. The Intercept value is a constant not associated with any variable. When you have categorical explanatory variables, one of the values is dropped (Developer in this case). The information at the bottom of the output display indicates how well the independent variables, Occupation, Age and Tech, explain the dependent variable, Income: Residual standard error: 4.219 on 3 degrees of freedom Multiple R-squared: 0.9649, Adjusted R-squared: 0.918 F-statistic: 20.6 on 4 and 3 DF, p-value: 0.01611 The multiple R-squared value (0.9649) is the percentage of variation in the dependent variable explained by the linear combination of the independent variables. Put slightly differently, R-squared is a value between 0 and 1 where higher values mean a better predictive model. Here the R-squared value is extremely high indicating Occupation, Age and Tech can predict Income very accurately. The F-statistic, adjusted R-squared value, and p-value are other measures of model fit. One of the points of this example is that when using R, your biggest challenge, by far, is understanding the statistics behind the language functions. You have to know which R function to use, and how to interpret the output. Most people learn R in an incremental way, by adding knowledge of one technique at a time, as needed to answer some specific question. A C# analogy would be learning about the various .NET namespaces. When you first started using .NET you probably didn't learn about the System.IO namespace until you needed to read a text file. Most developers learn about one namespace at a time rather than trying to memorize information about all the namespaces before writing any programs. The t-Test Using R The second example in Figure 1 shows a t-test. The goal of the t-test is to determine if there's statistical evidence that the source means of two sets of sample numbers are the same or not. The two commands in the example are: > x <- c(78, 87, 78, 85, 80, 92, 88, 78, 90) > y <- c(82, 76, 63, 71, 75, 70, 80, 81) These commands create two vectors, x and y, using the c ("concatenate") function. The numbers are supposed to represent sample test scores of two different groups. An R vector can hold objects of different types. I could have made R numeric arrays like so: > x <- array(c(78, 87, 78, 85, 80, 92, 88, 78, 90)) > y <- array(c(82, 76, 63, 71, 75, 70, 80, 81)) A roughly equivalent C# statement would be: var x = new double[] { 78, 87, 78, 85, 80, 92, 88, 78, 90 }; As it turns out, the mean of the x-data is 84.00 and the mean of the y-data is 74.75. So the sample means are different, but could the difference in average test score be due to chance rather than due to a true difference in the population scores? After creating the vectors, the t-test is performed by issuing a single R command: > t.test(x,y) The result of calling the R t.test function is quite a bit of text: Welch Two Sample t-test data: x and y t = 3.1272, df = 13.956, p-value = 0.007444 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 2.90411 15.59589 sample estimates: mean of x mean of y 84.00 74.75 There are several different variations of the t-test. R uses a variation called Welch's t-test. The t statistic and the df value ("degrees of freedom") are calculated from the input data. The t statistic is often called Student's t. The t statistic and df value are used to compute the p-value of 0.007444. A p-value is the probability that the two means of the two data sets under investigation are equal. In this case the p-value is so low, well under 1 percent (0.01), that you'd conclude that there's statistical evidence that the means of the two data sets are not equal. In C# terms, most R functions, including the t.test, return a data structure that can be ignored, but contain many Console.WriteLine equivalent statements that expose output. It's up to you to decipher the meaning of R output. Graphs with R As a C# programmer, when I want to make a graph of some program output data, I typically run my program, copy the output data, paste the data into Notepad to remove control characters, then copy that data, paste it into Excel, and then create a graph using Excel. This approach is a bit inconvenient but works fine in most situations. One of the strengths of the R system is its native ability to generate graphs. Take a look at an example in Figure 2. This is a 3-D type graph that isn't possible in Excel without an add-in of some sort. In addition to the simple shell program in Figure 1, R also has a semi-GUI interface, RGui.exe, for use when you want to make graphs. The graph in Figure 2 shows the function z = f(x,y) = x^2 + y^2. The first three R commands to generate the graph are: > rm(list=ls()) > x <- seq(-6, 6, length=25) > y <- seq(-6, 6, length=25) The rm function deletes an object from the current workspace in memory. The command used is a magic R incantation to delete all objects from the workspace. The second and third commands create vectors of 25 values, evenly spaced, from -6 to +6 inclusive. I could've used the c function with hardcoded values instead. The next two commands are: > f <- function(x,y) { x^2 + y^2 } > z <- outer(x,y,f) The first command shows how to define a function in R using the function keyword. Next, the built-in R function named outer creates a matrix of values using vectors x and y, and a function definition f. The result is a 25x25 matrix named z where the value in each cell is the value of function f that corresponds to x and y. The 3-D graph is displayed using the persp ("perspective graph") function: > persp(x, y, z, theta=30, phi=15, expand=0.7, col="cyan", + shade = 0.5, ticktype="detailed", d=5, r=1) When typing a long line in R, if you hit the Enter key before the end of the command, the system will jump the cursor down to the next line and place a '+' character as a prompt to indicate your command is not yet complete. The persp function has a lot of optional, named parameters. Parameter theta controls the left-right viewing angle. Parameter phi controls the up-down viewing angle. The parameter named expand controls the ratio of the height and width of the graph. The col parameter is the color (or colors) to use. The parameter named shade controls simulated shading from a virtual light source. Parameter ticktype controls how values on the x, y, and z axes are displayed. Parameters r and d control the perceived eye distance to the graph, and the perceived 3-D effect. The persp function has many more parameters, but the ones used here will be sufficient in most situations. This example points out that R has very powerful and flexible native graphing capabilities, but they tend to be relatively low-level and require a fair amount of effort. The t-Test in C# In order for you to gain an understanding of the similarities and differences between R language analyses and C# language programming, it's useful to examine a C# implementation of a t-test. In addition, the C# code can make a nice addition to your personal code library. Take a look at the C# demo program in Figure 3. The demo program approximates the R language t-test shown in Figure 1. Notice the output values of the C# demo are exactly the same as those in the R session. The key code in the demo program is the calculation of the p-value, defined in method Student. The code for method Student is presented in Listing 1. Even a quick glance at the code should make it obvious that the method requires deep math knowledge. public static double Student(double t, double df) { // For large integer df or double df // Adapted from ACM algorithm 395 // Returns 2-tail p-value double n = df; // to sync with ACM parameter name double a, b, y; t = t * t; y = t / n; b = y + 1.0; if (y > 1.0E-6) y = Math.Log(b); a = n - 0.5; b = 48.0 * a * a; y = a * y; y = (((((-0.4 * y - 3.3) * y - 24.0) * y - 85.5) / (0.8 * y * y + 100.0 + b) + y + 3.0) / b + 1.0) * Math.Sqrt(y); return 2.0 * Gauss(-y); // ACM algorithm 209 } Surprisingly, coding complicated numerical functions isn't as difficult as you might first guess because there are many resources available. Two of my most frequently used references are the Collected Algorithms (CALGO) repository of the Association for Computing Machinery (ACM) and the "Handbook of Mathematical Functions" by Abramowitz and Stegun (so well-known it's often just called "A&S"). Both references are freely available in several places on the Web. Method Student implements ACM Algorithm number 395 and calls a helper method, Gauss, which implements ACM Algorithm 209. An alternative to ACM 209 is A&S equation #7.1.26 plus a simple wrapping statement. Many of the functions in the ACM CALGO and A&S are implemented in existing C# libraries, but most of those libraries are quite large. When possible I prefer to code from scratch, using just those methods I need and avoiding external dependencies. A Few Comments There are a few R language integrated development tools you can use. One well-known project is called RStudio. I generally prefer using the native R console. Several Microsoft products work with R. For example, the Microsoft Azure Machine Learning service can use R language scripts. I suspect that support for R will be added to Visual Studio at some point. This article shows only a tiny fraction of the R language, but it should be enough to get you up and running with R. Naturally, the best way to get familiar with R is to actually try it out. Installing R (and uninstalling, if necessary) is quick and painless, and running the three R examples presented in this article will give you a great feel for the language.
https://visualstudiomagazine.com/articles/2015/12/01/introduction-to-r.aspx
CC-MAIN-2020-40
refinedweb
3,178
65.01
This week is a rather quiet on the game AI front in the build-up to GDC in San Francisco. However, by digging a little deeper we’ve found a bunch of smart links for you. This roundup is brought to you by Alex Champandard and Nov<< Turok Interview: Re-inventing the Wheel Here’s another interview about Turok’s and its acclaimed AI, already featured in video 1 and video 2 a few weeks ago. “We knew that we wanted to create the impression of a realistic ecosystem. At the same time we couldn?t model true dinosaur behavior because it’s an action game and it could be boring. We went through a few phases in our research and development of the creatures. In our first phase we learned as much as we could about dinosaurs, the historical facts of their time on the planet and theories on their behaviors and interactions. In the second phase we looked at popular culture. We looked at Jurassic Park, and other various films and books to see the different influences that people would have that would live up to expectations.” Anyone played the game care to post a short review? Re-inventing the Wheel, canada.com Prototype AI for Green Vegetables Dan Cook over at LostGarden.com is providing a full design for a game: Play With Your Peas, along with fancy graphics for programmers who want to prototype a simulation game. The design has many challenges when it comes to the AI, and Dan has the following advice: One problem that is common to AI-driven systems is that most of the behaviors go on underneath the cover, away from the player’s eyes. It is very easy to fall into the trap of creating an intricate AI that ‘plays itself’ but is completely incomprehensible to the player. Instead of asking how you might make the most realistic AI system, I prefer to steal a page from Nintendo’s playbook. Instead ask ‘What is the simplest system that drives forward the player experience?’ Soren Johnson at GDC: A Farewell to Civ Civilization 4’s lead designer and AI programmer Soren Johnson wrote a blog post about his upcoming talk at GDC next week: “Essentially, I will be talking about the difference between thinking of the AI as the player’s opponent and thinking of it as simply an extension of the core game design (what one might call the difference between ‘good’ AI and ‘fun’ AI). There will also be a long section on AI cheating - the bane of my existence for many years - concerning which type of cheats are acceptable to players and which type are not, using Civ as an extensive case study. Further, I hope to prove that, for Civ at least, there is no such thing as - and never could be - a ‘fair’ difficulty level where the AI is playing the same game as the human. Your mileage , of course, might vary.” The talk is inspired in part by his AIIDE ‘07 “Work in Progress” slides. Computer AI: Playing Tetris “This article describes how a computer can play the classic video game Tetris by getting information about the board, determining good actions, and performing those actions. […] An ordinary USB web.” Fregl: An Introduction to FRP Luke Palmer introduces a new version of his Fregl library for Functional Reactive Programming. This kind of stuff is ideal for game logic, combining events and signals into elegant programs in the same way a behavior tree builds up control from modular logic. Here’s an example: --) clickInTenSeconds = eitherEvent waitTenSeconds mouseClick where waitTenSeconds = waitTime 10 >> return (0,0) European GDC(s) Call for Papers With the American Game Developer’s conference just underway, both conferences in Europe scheduled for the next 6 months are calling for papers. It’s not directly AI related, but it can be if you submit a proposal! Also, be sure to post below if you’re planning on going. The Soul of The Sims, by Will Wright This is part of a roundup for news that’s almost exactly 10 years old! Don Hopkins posts about the AI for.” 2K Boston Hiring Senior AI Programmer Chris Kline sent word that his studio is hiring. In fact, 2K Boston will be sponsoring next Tuesday’s discussion with a signed copy of BioShock. “2K Boston (formerly Irrational Games) is looking for a Senior Level AI Programmer to help ensure the success of our next AAA title.” NaturalMotion and Unreal Engine 3 Sitting in a Tree… NaturalMotion, which provides behavioral animation based on physically accurate simulations, is joining the integrated partners program for the Unreal Engine. Here’s the blurb: .” Neversoft Seeking Senior AI Programmer “Neversoft Entertainment is looking for a Senior AI Programmer who will work on core AI system functionality (navigation, pathfinding, FSM, optimization and upgrading our existing AI system.” Stay tuned next week for more smart links from around the web! You can also reply to this thread in the forums.
http://aigamedev.com/links/2008-week-7
crawl-001
refinedweb
835
59.33
Question : Consider the following code : class Super { static String ID = "QBANK"; } class Sub extends Super{ static { System.out.print("In Sub"); } } public class Test{ public static void main(String[] args){ System.out.println(Sub.ID); } } What will be the output when class Test is run ? A. I t will print In Sub and QBANK. B. I t will print QBANK. C. Depends on the implementation of JVM. D. It will not even compile. E. None of the above. Answer Answer is option B. Explanation It would look like the program would print "In sub" followed by QBANK and the option would be A but it is not. A class is initialized only when it's content (variables/methods) which are not inherited gets referenced. Not otherwise. From JLS 12.4.1: From JLS 12.4.1:, and an assert statement (§14.10) lexically nested within T is executed.
http://opensourceforgeeks.blogspot.com/2014_06_11_archive.html
CC-MAIN-2019-43
refinedweb
148
70.9
The Proximity Box is an interactive box that detects a user's proximity! Last seen at the 2015 San Mateo Maker Fair! The Proximity Box senses a user's proximity by detecting the intensity of infrared light reflected off the user. The modular boxes vary the color of the several hundred LEDs on their surfaces to indicate the proximity of a detected object. If you want to know about the innards, skim past the following picture gallery. The Proximity Box uses infrared sensors for input and addressable LEDs for output. The basic principle of the Proximity Box is to shine infrared light from the interactive surface to a nearby object and then detect the intensity of reflections from objects. Less intensity would mean that the object is further away, since intensity diminishes with distance. One of the challenges of using infrared light is that ambient infrared interferes with the sensing. I found a solution by using the Vishay TSSP4938 sensors, which have an optical filter to select only a particular wavelength of infrared and have an integrated demodulator to pick out modulated infrared from the environment. Modulation can be done by simply blinking an IR LED (or IR LED strips in my case) at the correct modulation frequency as specified in the sensor's datasheet. Vishay's TSSP line is quite special because they can express intensity as a pulse width. The more popular version of the sensor only detects whether or not the light has exceeded a threshold and outputs a binary high or low. With the TSSP sensor, a weakly detected signal would correspond to a narrow (in time) pulse, while a strong one would correspond to a wide pulse. An incredibly strong signal would give a constant level, an "infinite width pulse." Note that the pulse encoding is not a continuous PWM signal, but a single impulse-like pulse beginning when any low intensity IR is detected. In math-land, the pulse is u(t) - u(t-a), where a is proportional to intensity. More about Vishay's TSSP can be found in their application note/brochure. After the sensors detect proximity, corresponding colors were displayed on a very long chain of APA102 RGB LEDs (see my post on the LED). The APA102 RGB LEDs are daisy-chained LEDs with memory and a simple shift-register-like SPI interface. Although it may seem that there are four separate surfaces for the Proximity Box, the LEDs are are actually daisy chained across all four boxes. The hardware, modular in design, is composed of the Motherboard, the Panel, and the Subpanel. A single Motherboard connects to four Panels. Each Panel connects to four Subpanels. In total there are 128 infrared sensors and 384 output LEDs. Since I was a busy student at the time, the hardware was designed with lack of time on mind. For example, through-hole components were chosen over SMD, since it's easier to solder or probe through-hole components than SMD. Another instance is that I used a resistor network in a DIP form instead of individual ones to save time while soldering. The motherboard houses the microcontroller, supporting circuity, and connectors. The microcontroller used was the MSP430 (MSP-EX430F5529LP), chosen for its availability at the time. Supporting circuity includes a 555 timer for modulating the infrared LEDs without controller intervention, a MUX for selecting the infrared LEDs, and a level shifter. The motherboard also includes 16 potentiometers to tune the intensity of the infrared LEDs in case a stronger or weaker signal is needed. The motherboard has no power circuity, because the Proximity Box is powered by a PSU taken from a computer. Just three wires from the mother board are needed to push data to the output LED strip. The motherboard is connected to four panel circuits which correspond to the four boxes. The panel circuits contain TI's TCA9535 I2C I/O expanders that read in the pulses from the TSSP sensors. Since no hardware interrupts are available at this scale, the I/O expanders were simply sampled very quickly to obtain the pulse width. The panels also have four FETs that modulate the infrared LEDs. The subpanels were not actual circuit boards, but a schematic exists for it. Each panel is connected to four subpanels, which corresponds to the four rows of sensors on each box. The subpanels were constructed with plenty of hot glue and ribbon cables. The gist of the code is that I had to measure the pulse width (indicating signal strength) of every sensor through I2C, convert pulse width to pixel color, and then send the data to the LEDs. The challenge was doing this fast enough for the system to respond in real time. Thinking that I was working with a large and slow system, I did a few hacks with loop unrolling, a few I2C header-skipping shortcuts specific to the I/O expander, and parallelized polling. It turns out I underestimated my hacks, so the ProxBox updates so fast (I don't remember the exact rate, but it was definitely over 100 Hz), it's almost like a shadow under your finger tips. The code for this project is in this GitHub repository (used with the Code Composer IDE). I have to admit, some of the code is disgusting, since I added a lot of fixes in the last minute. The following is a cleaned up version of my main.c. #include <msp430.h> #include <stdint.h> #include "led_drive.h" #include "sensor.h" ... setup/configuration function definitions here int main(void) { WDTCTL = WDTPW | WDTHOLD; // Stop watchdog ti config_clock(); config_spi(); config_i2c(); config_gpio(); // LED Table uint8_t led_table[TABLE_SIZE]; // [ 0x0E + Brightness | B | G | R ] off(led_table, NUM_LED); uint32_t i, reset_count=0; // SENSE Table uint16_t sense_table[NUM_SENSE]; for(;;) { P1OUT ^= 0x01; // blinky gather(sense_table); off(led_table, NUM_LED); process(led_table, sense_table); put_data(led_table, NUM_LED); } // main loop return 0; } 1/21/16: added block diagram 1/1/16: Revised wording. I finally found my found and fixed my PCB files. The KiCad people decided that it would be a good idea to change the file format and break everything. Written on the 13th of November in 2015
http://jgtao.me/content/11-13-15/
CC-MAIN-2020-29
refinedweb
1,027
61.77
Tracing AWS SDK calls with the X-Ray SDK for Node.js When your application makes calls to AWS services to store data, write to a queue, or send notifications, the X-Ray SDK for Node.js tracks the calls downstream in subsegments. Traced AWS services, and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the service map in the X-Ray console. You can instrument all AWS SDK clients by wrapping your aws-sdk require statement in a call to AWSXRay.captureAWS. Example app.js - AWS SDK instrumentation var AWS = AWSXRay.captureAWS(require('aws-sdk') ); To instrument individual clients, wrap your AWS SDK client in a call to AWSXRay.captureAWSClient. For example, to instrument an AmazonDynamoDB client: Example app.js - DynamoDB client instrumentation var AWSXRay = require('aws-xray-sdk'); ... var ddb = AWSXRay.captureAWSClient(new AWS.DynamoDB()); Do not use both captureAWS and captureAWSClient together. This will lead to duplicate subsegments. For all services, you can see the name of the API called in the X-Ray console. For a subset of services, the X-Ray SDK adds information to the segment to provide more granularity in the service map. For example, when you make a call with an instrumented DynamoDB client, the SDK adds the table name to the segment for calls that target a table. In the console, each table appears as a separate node in the service map, with a generic DynamoDB node for calls that don't target a table. Example Subsegment for a call to DynamoDB to save an item { "id": "24756640c0d0978a", "start_time": 1.480305974194E9, "end_time": 1.4803059742E9, "name": "DynamoDB", "namespace": "aws", "http": { "response": { "content_length": 60, "status": 200 } }, "aws": { "table_name": "scorekeep-user", "operation": "UpdateItem", "request_id": "UBQNSO5AEM8T4FDA4RQDEB94OVTDRVV4K4HIRGVJF66Q9ASUAAJG", } } When you access named resources, calls to the following services create additional nodes in the service map. Calls that don't target specific resources create a generic node for the service. Amazon DynamoDB – Table name Amazon Simple Storage Service – Bucket and key name Amazon Simple Queue Service – Queue name
https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-awssdkclients.html
CC-MAIN-2021-39
refinedweb
344
56.15
Using sqlite3_load_extension on windows (1.2) By curmudgeon on 2020-05-07 18:20:47 edited from 1.1 [link] [source] Can anyone tell me where I'm going wrong here? I'm using C++ bulder 10.2 (clang compiler). From IDE menu I've selected File|New|Dynamic Link Library and chosen compile as C with no dependencies. I've then added sqliteFcts.c and made the sqliteFcts.dll library. It all compiles fine. Contents of sqliteFcts.c. //------------------------------------- #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_sqliteFcts_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); return rc; } // SQLite code is above. Code below was created by the IDE // Commenting out the code below still gives the same error message #pragma argsused int _libmain(unsigned long reason) { return 1; } //------------------------------------ From my own app I try to use the dll with the following code int rc; sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,1,&rc); // sets rc=1 rc=sqlite3_load_extension(db,"C:/temp/sqliteFcts.dll","sqlite3_sqliteFcts_init",&buf); // rc==1 and buf contains "The specified procedure cannot be found\r\n" (2.1) By Larry Brasfield (LarryBrasfield) on 2020-05-07 15:49:37 edited from 2.0 in reply to 1.1 [link] [source] Try either of these fixes: Rename your entry point to have only lower case. In your sqlite3_load_extension call, provide the entry point you have. (3.1) By curmudgeon on 2020-05-07 18:19:37 edited from 3.0 in reply to 2.1 [link] [source] Thanks for the reply Larry but same error message. Well spotted though. The fact I wasn't supplying the 3rd parameter sqlite was forming the name using lower case characters. I've corrected that in the opening post. I've been trying to do this for 5 days :-( (5) By Larry Brasfield (LarryBrasfield) on 2020-05-07 18:26:04 in reply to 3.0 [link] [source] I compile your code thusly: cl -nologo -W4 -DINCLUDE_MSVC_H=1 -DSQLITE_OS_WIN=1 -I. -I. -fp:precise -MT -DNDEBUG -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS -DSQLITE_THREADSAFE=1 -DSQLITE_THREAD_OVERRIDE_LOCK=-1 -DSQLITE_TEMP_STORE=1 -DSQLITE_MAX_TRIGGER_DEPTH=100 -DSQLITE_ENABLE_FTS4=1 -DSQLITE_ENABLE_FTS5=1 -DSQLITE_ENABLE_JSON1=1 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_COLUMN_METADATA=1 -DSQLITE_DEFAULT_FOREIGN_KEYS=1 -DSQLITE_ENABLE_SESSION=1 -DSQLITE_ENABLE_GEOPOLY 3_OMIT_WINDOWFUNC -O2 -DSQLITE_API=__declspec(dllimport) -LD sqliteFcts.c Then I3_sqliteFcts_init sqlite> .q > sqlite3m SQLite version 3.32.0 2020-02-18 19:49:48 (with modified shell) Enter ".help [<command>]" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> .load sqliteFcts Error: The specified procedure could not be found. sqlite> .q > notepad ..\sqliteFcts.c After changing the entry point to 'sqlite3_sqlitefcts_init' (note case change), I compiled again, the same way, and> .q I don't know what you are doing differently. As far as I can tell, if you build the DLL with the usual calling convention and export, it should work with the entry point renamed or with it explicitly specified to sqlite3_load_extension(). Perhaps you are not linking correctly to the sqlite3 API. See the last -D argument to CL.exe about that. (7.1) By curmudgeon on 2020-05-07 19:56:37 edited from 7.0 in reply to 5 [source] Larry thanks for your efforts. I had no idea I was required to have the -DSQLITE_API=__declspec(dllimport) -LD sqliteFcts.c directive. What does it mean? In any case I added it to the directives and got a string of error messages from the compiler of the form [bcc32c Error] sqlite3.h(345): expected unqualified-id When I double clicked the error messages in turn it highlighted different lines in sqlite3.h e.g. SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API const char *sqlite3_sourceid(void); SQLITE_API int sqlite3_libversion_number(void); etc. etc. (9) By Larry Brasfield (LarryBrasfield) on 2020-05-07 23:19:26 in reply to 7.1 [link] [source] I hope that I have not led your attention too far astray with that voluminous compiler invocation. I use it to compile extensions which do a bit more than yours, and make use of the SQLite API to do so. The SQLITE_API qualifier is used to denote SQLite library entry points that are exposed, outside of the library itself, so that clients can call into the API by means of references that are resolved at link time. In this case, the linkage is into a dynamic load library, with linkages resolved at DLL load time. In that context, '__declspec(dllimport)' means 'create a reference (or address) to be resolved when the client code loads and either loads (or finds already loaded) the SQLite library as a DLL. By convention, extensions do not rely on linkage resolved that way; instead, they get a struct passed into them which contains all the API function addresses already resolved before the extension is loaded. If your extension works that way, (once it is made to actually do something), you will not need that particular define. It has been too long since I used clang for me to opine usefully on what it is complaining about. However, I can suggest that looking at the preprocessed form of your code can be very helpful when setting out to cure that sort of problem. If my posts on this have any relevance, it is to show that your problem lies in linkage issues rather than some mysterious failure of sqlite3_load_extension() to load a DLL and attempt to find the entry point it is given or must deduce as a default. As you can see, that works per that API's documentation. FWIW, I second Keith's recommendation that you use dumpbin.exe to sort out what has happened. With that tool, it is easy to see what names have actually been defined and compare those to the names reflecting to-be-resolved-at-link references. In addition to possible (but unlikely IMO) C versus C++ name decoration issues, you may be suffering from decoration variation with calling convention. Keywords to lookup on that are CDECL and STDCALL. (10) By curmudgeon on 2020-05-08 09:51:02 in reply to 9 [link] [source] Thanks for the explanation and your time Larry. See my reply to Keith below. (4) By Keith Medcalf (kmedcalf) on 2020-05-07 18:23:13 in reply to 1.1 [link] [source] Just because you told your C++ compiler does not affect the C++ "name mangling" done by C++ compilers. Suggest you use DUMPBIN (or whatever tool you want to use) to look at the export table for the DLL. It is probably exporting the name mangled all to ratshit (in the C++ fashion). The exported name should be "sqlite3_sqlitefcts_init" to match the name of the dll file. If the name is mangled to ratshit in the C++ fashion (ie, not the above) try declaring it a cdecl as in: __declspec(dllexport) cdecl int sqlite3_sqliteFcts_init (6) By curmudgeon on 2020-05-07 19:41:16 in reply to 4 [link] [source] Thanks Keith but it didn't help. I don't have DUMPBIN but I'll look into it. I tried _cdecl but same error. I even tried renaming sqliteFcts to x throughout and still got the same error message. (8) By Keith Medcalf (kmedcalf) on 2020-05-07 19:58:27 in reply to 6 [link] [source] DUMPBIN is a part of many Windows SDKs. DEPENDS.EXE (Dependancy Walker) can also show you dependancies and import/export names. (11.2) By curmudgeon on 2020-05-08 11:04:53 edited from 11.1 in reply to 8 [link] [source] Thanks Keith. I downloaded Dependency Walker. In the top left window I've got SQLITEFCTS.DLL highlighted. The bottom panel shows Error: At least one required implicit or forwarded dependency was not found. Warning: At least one delay-load dependency module was not found. The middle left panel has a string of modules the first 5 of which are API-MS-WIN-CORE-APIQUERY-L1-1-0.DLL API-MS-WIN-CORE-APPCOMPAT-L1-1-0.DLL API-MS-WIN-CORE-APPCOMPAT-L1-1-1.DLL API-MS-WIN-CORE-APPINIT-L1-1-0.DLL API-MS-WIN-CORE-ATOMS-L1-1-0.DLL The first 90+ have errors all of which are "Error opening file. The system cannot find the file specified (2)." showing on the middle right. On the top right lower panel there are 2 listed under Function _sqlite3_sqliteFcts_init __CPPdebugHook. I tried calling sqlite3_load_function with the entry point parameter set to "_sqlite3_sqliteFcts_init" (i.e. underscore before sqliteFcts) and it's now working. It would therefore seem to be a name wrangling thing but I'd like to get shot of the anomaly if possible. Use of _cdecl before the sqlite3_sqliteFcts_init declaration doesn't remove it. Edit: Since posting the above I've discovered that the initial underscore is only required when compiled as 32 bit. For 64 bit it works as expected. This applies regardless of debug or release mode. (12) By Larry Brasfield (LarryBrasfield) on 2020-05-08 11:42:00 in reply to 11.2 [link] [source] If you were to change the 'F' in your init function's name to 'f', then it would not be necessary to provide the entry point to sqlite3_load_extension(). For several years, since Microsoft introduced Delay-loaded DLLs, the dependency walker has shown "errors" associated with references to such DLLs. They can generally be ignored. You can recognize them, and justify ignoring them, from the fact that the dependency tree shows them as called into by one (or more) DLL(s) that you did not create. Your germane concern is with unsatisfied references from any DLL you have created. (13) By Keith Medcalf (kmedcalf) on 2020-05-08 12:31:45 in reply to 11.2 [link] [source] Yeah, those API-MS-... and MS-EXT-... are how Microsoft implements "interfaces" in Windows 10. They are not really DLLs at all. They can be ignored. Anything that is compiled to run on Windows 10 will have a crap load of them. If you target exclusively an earlier version of Windows, they will all go away. If a DLL is missing and it is NOT one of these "interface" dlls, then it is a "real" error as opposed to just a fake error because the dependancy walker does not properly ignore these "interfaces". I don't know why your compiler is mangling the names, but at least now you know what it is doing. (14) By curmudgeon on 2020-05-08 13:11:38 in reply to 11.2 [link] [source] Many thanks to you both for your time. For the time being at least I can remove the rope from the attic :-) (15.1) By curmudgeon on 2020-05-10 12:19:50 edited from 15.0 in reply to 11.2 [link] [source] I found that if the entry point was declared with __stdcall the function name had no leading underscore in dependency walker. Thought that was that but alas no. Using the code below, line // 1 doesn't return SQLITE_OK and line // 2 gives an exception with message "privileged instruction at 0x004f158a" in console.exe. I've googled the error but I can't see anything that would cause a memory overwrite. lite32c.dll file //--------------------------------------------- #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 #ifdef _WIN32 __stdcall __declspec(dllexport) #endif int sqlite3_lite32c_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); return rc; } //--------------------------------------------- console.exe file //--------------------------------------------- #ifdef _WIN32 #include <tchar.h> #else typedef char _TCHAR; #define _tmain main #endif #include "sqlite3.c" int _tmain(int argc, _TCHAR* argv[]) { sqlite3 *db; sqlite3_open(":memory:",&db); int rc; sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,1,&rc); rc=sqlite3_load_extension(db,"c:/temp/Win32/Debug/lite32c.dll",0,0); // 1 rc=sqlite3_load_extension(db,"c:/temp/Win32/Debug/lite32c.dll", // 2 "sqlite3_lite32c_init",0); return 0; } //--------------------------------------------- (16) By curmudgeon on 2020-05-12 14:09:53 in reply to 11.2 [link] [source] While experimenting with dlls I tried to create a source file that called each of the entry points in the extension files I required in order to save me having to create a dll for each extension. The dll source file starts with the lines #include "eval.c" #include "carray.c" #include "series.c" #include "btreeinfo.c" but I get the error "redefinition of sqlite3_api" in each of the above files bar the first. If I comment out the SQLITE_EXTENSION_INIT1 line in each of the bottom 3 files it all works fine but I can't help but feel I've transgressed some unwritten law. I have the same 4 includes at the bottom of my sqlite3.c amalgamation code before my core_init function and that compiles fine. Is there a reason I shouldn't be doing this and, if not, is there a #define I can put before the #includes that will suppress the redefinition errors so I can leave the extension source files untouched. (17.2) By Keith Medcalf (kmedcalf) on 2020-05-12 17:37:28 edited from 17.1 in reply to 16 [link] [source] You could define redefine SQLITE_EXTENSION_INIT1 after the first include. The reason that these work when appended to the sqlite3.c (the amalgamation) is that it (sqlite3.c) has the symbol SQLITE_CORE defined which indicates that the sqlite3 API is to be called directly rather than via the "global array of indirect pointers" created by the SQLITE_EXTENSION_INIT1 macro (and initialized by the SQLITE_EXTENSION_INIT2 macro), thus those macro's expand to /* no-op */ and do nothing. Since you can only declare a global once, you can only execute the SQLITE3_EXTENSION_INIT1 macro once per compilation unit. #include "eval.c" #undef SQLITE_EXTENSION_INIT1 #define SQLITE_EXTENSION_INIT1 /* no-op */ #include "carray.c" ... etc ... (18) By curmudgeon on 2020-05-12 17:41:48 in reply to 17.2 [link] [source] Brilliant Keith. That works. (19) By Keith Medcalf (kmedcalf) on 2020-05-12 18:12:18 in reply to 18 [link] [source] You could probably make it look nicer (easier to maintain in the future) by doing something like this: #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 #undef SQLITE_EXTENSION_INIT1 #define SQLITE_EXTENSION_INIT1 /* no-op* / #include "eval.c" #include "carray.c" #include "series.c" #include "btreeinfo.c" #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_whatever_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); if ((rc = sqlite3_eval_init(db, pzErrMsg, pApi)) == SQLITE_OK) if ((rc = sqlite3_carray_init(db, pzErrMsg, pApi)) == SQLITE_OK) if ((rc = sqlite3_series_init(db, pzErrMsg, pApi)) == SQLITE_OK) if ((rc = sqlite3_btreeinfo_init(db, pzErrMsg, pApi)) == SQLITE_OK) ; return rc; } To make it clear that SQLITE_EXTENSION_INIT1 is only called once and ignored in the included files, and provide an init function for the entire DLL ... (20) By curmudgeon on 2020-05-13 06:44:09 in reply to 19 [link] [source] Agreed Keith. Thanks.
https://sqlite.org/forum/info/0565948fc5b3a382
CC-MAIN-2022-27
refinedweb
2,446
65.52
6 In a previous guide, I covered JavaScript objects in depth and how they function within the language. I also mentioned that objects are only one of two main JavaScript data types, the other being primitives. I will go more into depth here about what primitives consist of, their roles, and multiple variants. Like HTML, JavaScript is a client-side language that does not need to be compiled prior to runtime, thus it is interpreted. However, unlike HTML, which is a markup language, JavaScript is a scripting language. JavaScript follows the ECMAScript standard, which scripting languages rely on, and which include eight data types overall. One of the data types is objects, while the other is primitives, which have seven variations. The seven types of primitives include: The main thing to keep in mind about primitives is that they represent data that has no methods and cannot be altered. They also have a fixed size in memory. Variables hold the actual values of primitive types, but they hold only references to the values of reference types. If a primitives has a value contained within it, it can be attributed to a variable. The variable holds the reference to the values of referred types. Here is an example below of how variables reference values: 1 var a_num = 1.45 // a_num holds the reference to the actual value Primitives differ from objects because they have no properties, thus their values cannot be changed. They are immutable. They also have no methods and can be looked at as just code or data. When primitives are called upon, the JavaScript language will call upon their object counterpart and switch between the two depending on need. Thus, in reality and in its bare code, JavaScript will form an object, use it, and return its results. This means that even though primitives are vital to the JavaScript language, they are also tied to objects through being copied and destroyed. Variables can hold primitives or compound data (arrays or clusters of data and objects) without being tied to objects. Properties is the term for variables that are actually tied to objects. Let us take a look at what some of these primitives do as an example of their functionality. Null is a primitive that signifies that the value is unknown. Keep in mind that the typeof operator returns object for null due to ECMAScript’s evaluation. Undefined is not a declared value and is not defined in any meaningful way for someone to interpret. Any variable not assigned a value belongs to this category. Boolean refers to a logical statement with only two values: true or false. String is a primitive that represents characters put together in words or phrases that make up text. Thus, it can be referred to as textual data. BigInt represents integers that were possibly calculated and formed into digits of precision only limited by available system memory (arbitrary precision format). In essence, this primitive represents whole numbers larger than 253 - 1: the largest number JavaScript can reliably represent. 1 const theBiggestInt = 2003199254740456n 1 2 const hugeString = BigInt("2003199254740456") // ↪ 9007199254740991n Number is a primitives type continuing 8 bytes of data. 1 2 Number.NEGATIVE_INFINITY // -Infinity Number.POSITIVE_INFINITY // Infinity Symbol can be used as a key of an object’s property. Here is an example using apple as an object: 1 2 3 4 var key = Symbol() var an_obj = { [key]: ’apple’ } When objects are added, subtracted or printed (shown up on the console) using the alert(obj) command, primitives come into play. In each of these cases, objects are converted to primitives before any of these three operations are carried out within JavaScript. For example, string will be converted to System.String, which is a class that happens to be the wrapper class for the string primitive type. JS++ introduces a compare method that vanilla JavaScript lacks. Thus, the JS++ compiler autoboxes the string value with the System.String object wrapper class in order to provide the compare method. Here is an example comparing strings blue and red: 1 2 3 4 import System; Comparison compare1 = "blue".compare("red"); // Valid due to auto-boxing Comparison compare2 = (new System.String("blue")).compare("red"); // Equivalent boxed expression Another example of autoboxing is when JavaScript accesses variables within a primitive and when .call and .apply functions are used for a .this argument using a primitive. Here is an example of variable access: 1 var part = 'apple’.substr(0,2) Unboxing also occurs within JS++ when an object wrapper class is converted to its corresponding primitive data type. Although most aspects of JavasScript may appear to focus on objects and how everything within the code relates to objects, this is not always the case. Primitives are also part of the JavaScript language. These seven primitives hold information that is vital to the language and keeps it afloat. 6
https://www.pluralsight.com/guides/understanding-javascript-primitives-and-their-functionality
CC-MAIN-2020-29
refinedweb
810
56.05
I'm extending a control to be able to reuse it across my current Xamarin project. As part of this control, I need to create a DataTemplate programmatically. I have this part figured out and it works ok. The DataTemplate has a Label in it. I need to bind the Label's BindingContext property to {Binding Source}. I need to bind the Label's Text property to {Binding Path=Name}. This works in XAML, but I don't want to have to copy it to a million different places in the code base. <dxGrid:TemplateColumn <dxGrid:TemplateColumn.DisplayTemplate> <DataTemplate> <Label BindingContext="{Binding Source}" Text="{Binding Source, Path=MyPropertyName}" /> </DataTemplate> </dxGrid:TemplateColumn.DisplayTemplate> My extended control looks like this right now: `public class MyColumn : TemplateColumn { public MyColumn() { DataTemplate displayTemplate = new DataTemplate(() => { BindingBase textBinding = new Binding(FieldName); Label label = new Label(); // TODO: Bind BindingContextProperty to {Binding Source} //label.SetBinding(BindingContextProperty, binding); label.SetBinding(Label.TextProperty, textBinding); return new ViewCell { View = label }; }); DisplayTemplate = displayTemplate; } }` I'm getting hung up in the binding because I'm not sure how to do the equivalent of {Binding Source} in code. Any help would be appreciated. This question was originally posted to StackOverflow here: @TC2254 - binding should be the same as any other control. By default the control will get the BindingContext of its parent. Below should be the equivalent of BindingContext={Binding Source}but are you getting an error or something using the below? label.SetBinding(Label.BindingContextProperty, Source); @AdamP Thanks for the response. Unfortunately this does not work as there is no "Source" property on the TemplateColumn. If I set it to a string "Source", then it fails with a Null Reference Exception. I made another pass at it this morning and got it working this way: @TC2254 - glad you managed to get it working. Apologies, I missed the fact it was in a DataTemplate. Is there also any way to perform GetBinding? I want to get the actual Binding(i.e. the property name), not the value. Anyone? @ShimmyWeitzhandler - Neither BindingContext nor BindableObject have any methods that would help you search for a binding, so I believe the answer is "No". AFAIK, you would have to create the bindings in code (not XAML), and create your own association (dictionary) between views (or viewmodels?) and binding names. Maybe you can create and cache the BindableProperties involved in the bindings? @SteveShaw.5557 - You actually CAN create a binding in XAML and use it later. It can be cached in the resource dictionary (which I recommend if you are switching bindings at runtime) or created in place. Here is a simple example: <Binding x: If you are following the MVVM principles, no ViewModel should ever have to bother with creating/setting/caching bindings, if you'd ask me. @GaetanF - that is useful to know, thanks. Given that, the answer to Shimmy, is to go about it a different way. While AFAIK it isn't possible to do what he asked, if the goal is to be able to switch between bindings, then instead of trying to access property names, using resources and their names is a good solution. The way I read his question, he was trying to get information (in code behind) about the DependencyProperty that was attached to a binding, once a BindingContext was attached. He asked for a GetBindingequivalent to SetBinding- BindableObject.SetBinding(BindableProperty, BindingBase). Or perhaps a BindableObjectExtensions.SetBindingmethod that takes a string. What you suggest is much cleaner (if it solves the need). You have resource objects, each of which is a System.Windows.Data.Binding. Set a UI property to one of those at runtime, and let internal code hook that up to the DependencyPropertydescribed by Binding's Path. To attach to a different DependencyProperty, use a binding with a different path (or change the path property of the binding?) It isn't GetBindingfunctionality, but it allows some interesting "Set" scenarios. This raises a question I don't know the answer to: Could GetBindingbe approximated this way: Pathproperty of that binding. SetBinding. If this is possible, what would the code for those steps look like? (To keep it simple, NOT inside of a DataTemplate, which is what TC2254 asked about.) I don't have a reason to test this right now, but something like this? in code-behind: NOTE: I'm not suggesting this is a good idea, even if possible. Just exploring the limits of what is possible, to better understand working with XAML.
https://forums.xamarin.com/discussion/62189/how-to-do-the-equivalent-of-binding-source-in-code
CC-MAIN-2020-50
refinedweb
744
56.66
Creating and using constructor along properties should paid more attention by the Programmer as Using Constructor is inevitable in everywhere in Java coding. Many postings are given with utmost importance about using constructor in way2java.com and read them as well as to get all the concepts in one example is not possible. In Java, a class comprises of instance (global) variables, constructors, methods and objects (excluding static blocks and inner classes). These are known as constructs of a class. It’s being a beginner’s code, the instance variables and methods are also discussed briefly. Instance variable: An instance variable dictates the property to the object of a class. Different objects may have different properties. For example: public class Car { double petrol; int speed; } In the above snippet of code, petrol property gives the petrol fuel existing with the Car. The speed variable gives the property at what speed the Car is moving right now. Method: The method gives the behavior to the Car object by controlling the instance variables. The Car may start with an initial petrol filled with 100.5 liters. The speed property can be changed very often in the course of driving. See how the following code gives 100.5 liters of petrol and 50 KM speed to the Car vehicle at the start. public class Car { double petrol; int speed; public void setBehavior(double pet, int spe) { petrol = pet; speed = spe; } } The setBehavior() method sets the Car for a petrol given by the local variable pet and for a speed given by spe. How to set the values for pet and spe will be seen in the following program. By calling the setBehavior() method number of times the properties (using instance variables) of a Car can be changed. Now let us go to a full blown program. public class Car { double petrol; int speed; public void setBehavior(double pet, int spe) { petrol = pet; speed = spe; } public static void main(String args[]) { Car maruthi = new Car(); maruthi.setBehavior(100.5, 50); System.out.println("First time Petrol filled: " + maruthi.petrol + " and running speed: " + maruthi.speed); // the properties can be changed by calling again setBehavior() method maruthi.setBehavior(200.5, 80); System.out.println("Second time Petrol filled: " + maruthi.petrol + " and running speed: " + maruthi.speed); } } The same maruthi Car object is given two times different values by calling the method setBehavior() two times. Here the intention is not much emphasis on variables and methods (they are given in Using Local and Instance Variables and Using Variables from Methods) but is on constructors. See the following statement. Car maruthi = new Car(); In the above statement Car() is known as constructor. The constructors, default constructor and overloading of constructors are discussed elaborately with example programs and screen outputs in Constructors and Constructor overloading.
https://way2java.com/oops-concepts/constructors/how-to-use-a-java-constructor/
CC-MAIN-2022-33
refinedweb
465
65.93
We are excited to launch the public preview of Azure Event Hubs as a new service on the Azure portal. With this launch you will also experience the namespace spilt and will now be creating event hub entities under Azure Event Hubs service. Here’s how you get started in creating an Event Hub in the new portal Click on New -> and type Event Hubs in the search box. Or click New -> Internet of Things -> Event Hubs You can now see what each pricing tier offers, including the price. ‘Loading pricing’ - of course, we’d want you to check out the portal yourself for the best price! You can now create a support ticket on the portal page itself! A neat feature is – at any time, you can move your Event Hub to a different subscription or resource group allowing fine-grained control over your billing and resource organization! You can also set the properties for your Event Hubs or scale your throughputs or change your pricing tier. Event Hubs on the new Azure portal offers you more flexibility with fewer clicks. If you have been creating Event hub entities along with Queues and Topics under the Messaging namespace type, you will not find these event hubs in the new Azure portal. You will need to recreate these event hubs to migrate to the new portal. We will be supporting mixed entities (event hubs, queues and topics under Messaging namespace type) in the classic Azure portal but not for long. Our suggestion for you is to migrate while we continue to support. By separating the services, we aim to provide better performance, scale better and simplify your service usage experience. We would love to hear your feedback and address your questions. Leave us a comment down here! Enjoy your new experience! Great to see Service Bus getting better UX capabilities! “You can also set the properties for your Event Hubs or scale your partitions” – does it mean We can increase the partitions with new portal or just throughput units as usual? I tried creating event hubs both in Basic and Standard tiers. Was unable to increase the partition count. Looks like We still need to approach Microsoft Support to change this. Hi Arunkumar – You are correct, we still do not offer the option of changing partition counts because of the implications this has on our service. Glad to see you like the UI otherwise! Will there be a release of Service Bus powershell cmdlets that leverage the ARM model anytime soon? Hi David – We are actively developing PowerShell cmdlets that will work with the ARM model. Please check back at this blog for an announcement. Where is the send event in the rest api? Its in classic but not the current version Look for an update on that MSDN page in the next day or two. We had these things mis-organized. The runtime API is actually separate, and not related to the management API’s.
https://blogs.msdn.microsoft.com/eventhubs/2016/08/29/azure-event-hubs-now-live-on-new-azure-portal/
CC-MAIN-2018-05
refinedweb
496
72.36