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 |
|---|---|---|---|---|---|
29 June 2012 10:59 [Source: ICIS news]
MOSCOW (ICIS)--The Russian government on Friday announced a downward review of export duties on petrochemical products for July.
Next month, the duty levied on ethylene, propylene, butylene and butadiene will amount to $133/tonne (€106/tonne), down from $237.10/tonne in June, according to a decree signed by Russian Prime Minister Dmitry Medvedev.
?xml:namespace>
From 1 July, the duty levied on benzene, xylenes and toluene is set at $243.70/tonne, or down from $277/tonne. Propylene trimer and propylene tetramer will be subject to a $24/tonne duty, down from $27.20 | http://www.icis.com/Articles/2012/06/29/9573837/russias-government-cuts-july-petrochemical-export-duties.html | CC-MAIN-2014-15 | refinedweb | 104 | 64.41 |
CodePlexProject Hosting for Open Source Software
I performed the following steps to setup an Orchard development environment for module development:
1. Downloaded Orchard Source code
2. Extracted the source code into a folder
3. Fired-up Visual Studio 2010 Professional and opened the Orchard solution/project (Orchard) under the src folder
4. Build the solution in Visual Studio
5. Run the solution - entered the info: site name / password / database
6. From the command-line performed a 'codegen module MyModule /IncludeInSolution:true' (for a new module)
Problems I have/had (until now):
1 - No intellisense for MVC 3 -> I unloaded my module/project added the following to .csproj file
<ProjectTypeGuids>{e53f8fea-eae0-44a6-8774-ffd645390401}
...
Should I do this or not?
2 - Get error: 'The Name "Script" Does not exist in the current context.' when adding to a View
@Script.Require("jQuery")
@Script.Require("jQueryUI")
3 - Error messages in existing Orchard module views: "There is no build provider for the extension 'cshtml'"
4 - Analogous to error 2 "The name "Display" does not exist in the current context.": in eg
@Display(Model.Header)
@Display(Model.Actions)
What am i missing to avoid all these problems?
Thanks.
Can someone please explain how to setup a
workable dev environment. Or are the mentioned problems all bugs?
I think the errors you are describing are all basically the same intellisense issue. Your project should still run fine - I have no problem building and running the current dev / 1.x enlistment and developing modules in it.
To improve the intellisense situation, you can add the following Web.config into your
module project root directory. Then build your solution, and close and reopen Visual Studio. I originally got this from another thread on these forums, where there is more explanation if you want to search for it.
A couple of things to make sure of;
I know the dev team are looking at a number of things to improve developer workflow once 1.1 is out but I've had personally had no trouble developing 3 working modules and 2 themes on the current codebase. Yes there are a few niggles at this stage (and things
that will make your head hurt!) but it really is worth it, so many things become very easy once you get your head round it. I recommend reading as much as you can in these forums, and also blogs of people like Bertrand Le Roy and Piotr Szmyd as they offer
a lot of useful tutorials and insights.
Module Web.config">
<remove name="host" />
<remove name="pages" />
="Orchard.Mvc.ViewEngines.Razor.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
<add namespace="Orchard.Mvc.Html"/>
</namespaces>
</pages>
</system.web.webPages.razor>
<system.web>
<compilation targetFramework="4.0">
<assemblies>
"/>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</assemblies>
</compilation>
</system.web>
</configuration>
It works now with the modification of the web.config in my module.
So not using the 'standard' source download from Codeplex (zip-file) but downlaoding the code with Tortoise?
Guy
I'm not sure if you mean the 'standard' 1.0.20 release source, or if you're downloading the latest dev branch. But if you set up a TortoiseHG enlistment instead, you can regularly pull down new changes and merge with any of your own modifications. It also
means you can version control your own work locally.
Thanks.
yes i meant the release source. i suppose there's backward compatibility when using/developing with the latest dev branch (when deploying modules to the web Orchard.Web version)?
Compatibility is pretty decent. All the stuff I've made has been fine with both, but I have seen some modules that break in 1.1. This close to the release it's kind of preferable to be compatible with the upcoming version in my opinion. Enough things are
being improved that the majority of users will want to switch very quickly and by targetting only 1.0 you'd just be creating potential upgrade headaches for yourself and anyone using your module if you released it. I'm using 1.1 on my own live site and it's
been running fine, although of course if it was a customer's site I'd be more careful which version I used. The only real problem I've had is 1.0 modules that haven't yet released a compatible version. Basically if you're building a new site or module now,
you might as well target 1.1 because it'll be out by the time you're finished. I hope :)
The only way to make sure is to develop against the latest dev, and also have a 1.0.20 installation to also test on. If you absolutely need to ensure compatibility with both versions then you simply have to test on both.
Thanks.
Maybe a stupid question but is the v1.1 version (alpha, beta) already available/downloadable? Or is this the version you automatically get when downloading the latest development branch?
Dev branch is the latest code and basically is moving towards the 1.1 release. It's being steadily merged in batches into the 1.x branch. So you can go with 1.x branch for stability, or dev for latest changes; but there's little difference. Either have a
lot of changes from 1.0.20. Most importantly, Shape Tracing, which is basically the Firebug for Orchard :)
The latest in the integration branch usually is a good compromise between stable and up-to-date.
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. | http://orchard.codeplex.com/discussions/251403 | CC-MAIN-2016-40 | refinedweb | 985 | 59.7 |
SMIL 2.0 provides a scalability framework, where a family of scalable SMIL profiles can be defined using subsets of the SMIL 2.0 language profile. A SMIL document can be authored conforming to a scalable SMIL profile such that it provides limited functionality on a resource-constrained device while allowing richer capabilities on a more capable device. SMIL 2.0 Basic (or SMIL Basic) is a profile that meets the needs of resource-constrained devices such as mobile phones and portable disc players. The SMIL Basic profile provides the basis for defining scalable SMIL profiles. SMIL Basic is SMIL host language conformant. It consists of precisely those modules that are required for SMIL host language conformance. This section defines the SMIL 2.0 mobile phones, portable disk players, car navigation systems, television sets, and voice user agents. Each of these platforms has its specific capabilities and requirements. It is clear that not all of the SMIL 2.0 features will be required on all platforms. SMIL 2.0 modules in its own profile.
As such a SMIL profile allows a SMIL user agent to implement only the subset of the SMIL 2.0 standard it needs, while maintaining document interoperability between devices profiles built for different needs. SMIL 2.0, using the content control facilities to support application/device specific features via a namespace mechanism. SMIL Basic is SMIL 2.0.0 language profile automatically conform to SMIL 2.0 Basic.
This section is normative.
SMIL 2.0 Basic Profile consists of the same set of modules that are required for SMIL Host Language Conformance in resource constrained devices. It includes the following SMIL 2.0 Modules:.0 document.
A SMIL Basic user agent is a program which can parse SMIL 2.0 documents, process the subset of SMIL 2.0 functionality defined, and render the contents of the document onto output mediums. A conforming SMIL Basic user agent must meet all of the following criteria:
Examples:
<smil xmlns=""> . . . </smil>
<smil xmlns=""> . . . </smil>
<smil xmlns="" xmlns: <smil20:excl> ... </smil20.0 in a uniform way. The SMIL 2.0 namespace may be used with other XML namespaces as per [XML-NS], although such documents are not strictly conforming SMIL 2.0 documents as defined elsewhere. It is expected that future work by W3C may address ways to specify conformance for documents involving multiple namespaces.
A scalable SMIL 2.0 profile contains all the modules in the SMIL Basic Profile as defined above.
Additionally it may contain any one or more modules from the SMIL 2.0 Modules which are not part of SMIL 2.0.0 Language conformant devices.
A SMIL 2.0.0.0.0 specification. The list of the module names is summarized in SMIL 2.0.
A scalable SMIL document must be a conforming SMIL 2.0 document.
A conforming scalable user agent must conform to the requirements for SMIL Basic User Agents above.
A conforming user agent must implement as a minimum all the modules defined by the SMIL 2.0 Basic Profile.
The switch element and the system test attributes can be processed either by the client in the terminal, or by the server on the server side before delivery (perhaps after a CC/PP [CC/PP] negotiation). | http://www.w3.org/TR/2004/PER-SMIL2-20041105/smil-basic.html | CC-MAIN-2016-30 | refinedweb | 543 | 59.8 |
How to: Open a Spreadsheet Document for Read-only Access
Last modified: October 14, 2010
Applies to: Excel 2010 | Office 2010 | PowerPoint 2010 | Word 2010
In this article
When to Open a Document for Read-Only Access
Getting a SpreadsheetDocument Object
Basic Document Structure
Attempt to Generate the SpreadsheetML Markup to Add a Worksheet
Sample Code
This topic shows how to use the classes in the Open XML SDK 2.0 for Microsoft Office to open a spreadsheet document for read-only access programmatically.
The following assembly directives are required to compile the code in this topic.
Sometimes you want to open a document to inspect or retrieve some information, and you want to do this in a way that ensures the document remains unchanged. In these instances, you want to open the document for read-only access. This How To topic discusses several ways to programmatically open a read-only spreadsheet document. that you call one of the Open() overload methods. Several Open methods are provided, each with a different signature. The methods that let you specify whether a document is editable are listed in the following table.
The table earlier in this topic lists only those Open methods that accept a Boolean value as the second parameter to specify whether a document is editable. To open a document for read-only access, specify False for this parameter.
Notice that two of the Open methods create an instance of the SpreadsheetDocument class based on a string as the first parameter. The first example in the sample code uses this technique. It uses the first Open method in the table earlier in this topic; with a signature that requires two parameters. The first parameter takes a string that represents the full path file name from which you want to open the document. The second parameter is either true or false. This example uses false and indicates that you want to open the file as read-only.
The following code example calls the Open Method.
The other two Open methods create an instance of the SpreadsheetDocument class based on an input/output stream. You might use this approach, for example, if you have a Microsoft SharePoint Foundation 2010 application that uses stream input/output, and you want to use the Open XML SDK 2.0 to work with a document.
The following code example opens a document based on a stream.
Suppose you have an application that uses the Open XML support in the System.IO.Packaging namespace of the .NET Framework Class Library, and you want to use the Open XML SDK 2.0 to work with a package as read-only. Whereas the Open XML SDK 2.0 includes method overloads that accept a Package as the first parameter, there is not one that takes a Boolean as the second parameter to indicate whether the document should be opened for editing.
The recommended method is to open the package as read-only at first, before creating the instance of the SpreadsheetDocument class, as shown in the second example in the sample code. The following code example performs this operation.
After you open the spreadsheet document package, you can access the main workbook part. To access the main workbook part, you assign a reference to the existing workbook part, as shown in the following code example. as follows.
< as follows.
Using the Open XML SDK 2.
The sample code shows how, when you try to add a new worksheet, you get an exception error because the file is read-only. When you have access to the body of the main document part, you add a worksheet by calling the AddNewPart<T>(String, String) method to create a new WorksheetPart. The following code example attempts to add the new WorksheetPart.. } }
The following code sample is used to open a Spreadsheet Document for Read-only Access. You can call the OpenSpreadsheetDocumentReadonl method by using the following code, which opens the file "Sheet10.xlsx," as an example.
The following is the complete sample code in both C# and Visual Basic.. } } | https://msdn.microsoft.com/en-us/library/cc823095(v=office.14) | CC-MAIN-2017-39 | refinedweb | 677 | 54.83 |
Important: Please read the Qt Code of Conduct -
Qt with openEXR and the code crashed
Hi everyone.
I'm writing an image viewer.
For EXR, I've compiled the source code to get:
bin, includes, libs and dlls.
The openEXR is compiled in x64 and the version is 3.
zlib is x64
Imath is x64
My Qt is x64 and the free version.
In the pro file, I added:
LIBS += -l$$PWD/openEXR/lib/Iex-3_1_d
LIBS += -l$$PWD/openEXR/lib/IlmThread-3_1_d
LIBS += -l$$PWD/openEXR/lib/Imath-3_1_d
LIBS += -l$$PWD/openEXR/lib/OpenEXR-3_1_d
LIBS += -l$$PWD/openEXR/lib/OpenEXRUtil-3_1_d
INCLUDEPATH += $$PWD/openEXR/include/Imath
INCLUDEPATH += $$PWD/openEXR/include/openEXR
My test code:
openexrloader.h
#ifndef OPENEXRLOADER_H #define OPENEXRLOADER_H #include <QWidget> #include <QtCore> #include <QtGui> #include <QImageIOPlugin> //Imath #include <half.h> //openEXR #include <OpenEXRConfig.h> #include <ImfRgbaFile.h> #include <ImfRgba.h> #include <ImfArray.h> //Namespace #include "namespaceAlias.h" class openEXRLoader:QObject { public: explicit openEXRLoader(); void writeRgba1 (const char fileName[], const IMF::Rgba *pixels, int width, int height); signals: }; #endif // OPENEXRLOADER_H
openexrloader.cpp
#include "openexrloader.h" openEXRLoader::openEXRLoader():QObject() { const char fileName[] = "D:/test.exr"; //Declare a pointer in the memory for RGBA IMF::Rgba *pixels = NULL; int width = 100; int height = 100; try { writeRgba1(fileName, pixels, width, height); } catch (const std::exception &exc) { std::cerr << exc.what() << std::endl; } } void openEXRLoader::writeRgba1 (const char fileName[], const IMF::Rgba *pixels, int width, int height) { IMF::RgbaOutputFile file (fileName, width, height, IMF::WRITE_RGBA); // 1 file.setFrameBuffer (pixels, 1, width); // 2 file.writePixels (height); // 3 }
NO errors, but the code will crash.
Which part do I did it incorrectly?
Thank you for help.
@Sisqos said in Qt with openEXR and the code crashed:
NO errors, but the code will crash.
If code crashes, run under the debugger, and look at the stack trace when it crashes.
I found IMF::RgbaOutputFile is the reason to make a crash.
We knew FreeImage can work with Qt directly, but openEXR can't.
Does anyone know the reason?
I've solved the problem.
I forget to consider that .exe require .dlls to execute.
Just copy .dlls to the folder where .exe is executed. | https://forum.qt.io/topic/127726/qt-with-openexr-and-the-code-crashed | CC-MAIN-2021-31 | refinedweb | 360 | 61.73 |
Adding Real-Time FedEx Shipping Rates to Kentico 11 Bryan Soltis — Apr 12, 2018 ecommerceshipping optionsshipping providercustom module If you have an e-commerce store, chances are you ship things to your customers. This means a lot of orders and a lot of calculations. One of the biggest ways to get more sales and happy customers is to integrate real-time shipping rates into your site. In this article, I’ll show you how to add real-time FedEx rates to your Kentico 11 site. When it comes to shopping online, people want information quickly. They want to know that the item’s in stock, that they’re getting it for a great price, and when they’ll receive it (of course they want it NOW). Another important cost is the shipping. Luckily, there’s a lot of options for developers to display this data real-time in their Kentico sites. Whether you’re using FedEx, UPS, or some other carrier, chances are they have an API you can integrate with to get up-to-date costs for shipping your packages. Let me show you how to pull in FedEx rates into your application. Note Most of concepts in this article are covered in our documentation for creating custom shipping carrier providers. Implementing custom shipping carrier providers Creating a custom module Before you can add any custom code, you need somewhere to put it. The first step will be to create a custom module in your Kentico site. This involves registering a new module within your UI, creating a new class, and adding some super cool functionality. Creating custom modules First, in your Modules application, create a new module and set your configuration. On the General tab, set your module name and description. Be sure you note the codename, as that will be important in the custom code. Next, you will want to create some settings to use within your module. This will allow admins to update service logins and addresses without redeploying the site. On the Settings tab, create a new category and group(s) for your carrier settings. Now, you can open the Settings app and see your new fields. A little later in the article, I’ll show you to create a configuration page right in the Ecommerce app to make things even easier. Lastly, you will want to create your new module in the Visual Studio Solution. If you use a sperate project, you’ll be able to isolate your code for easy updates and duplication into other Kentico sites. Create your new class to match your module code name. using CMS; using CMS.DataEngine; using CMS.Ecommerce; using CMS.EventLog; using CMS.Globalization; using CMS.Helpers; using CMS.Membership; using CMS.Modules; using CustomFedEx.FedExRateService; using System; using System.Collections.Generic; using System.Linq; [assembly: RegisterModule(typeof(CustomFedEx.CustomFedExCarrier))] namespace CustomFedEx { public class CustomFedExCarrier : ICarrierProvider { private const string <cms:SettingsGroupViewer </asp:Content> Open the Modules application and select your new module. On the UI Elements tab, create a new element, with your custom module selected and the URL for your new configuration page. Note the codename for the element. Next, in your custom module code, update the GetConfigurationUIElmentGUID function to get the new element by the code name. /// <summary> /// Returns the Guid for the configuration page. This allows the Store Settings UI to display the configuration page on the carrier details. /// </summary> public Guid GetConfigurationUIElementGUID() { UIElementInfo ui = UIElementInfoProvider.GetUIElementInfo("CustomFedExCarrier", "CustomFedExCarrierConfiguration"); return ui.ElementGUID; } Updating this function will tell Kentico to load your new UI element as the Configuration page for your shipping carrier in the Ecommerce module. Store configuration After a rebuild, you should be ready to configure your store. This will involve creating a carrier, and defining your shipping options. Creating a carrier In your Store configuration module, select Shipping / Carriers and create your new carrier. For the provider, select your custom assembly name and class Once you add it, you’ll see a swanky new Configuration tab, which will allow you to update your carrier settings. Creating shipping options On the Shipping options tab, create a new option for each of your defined shipping methods. In the Carrier service dropdown, select the appropriate option. Add each of the options you want to offer. NOTE The Carrier service options are populated from the GetServices function of the custom module. Testing At this point, you should be ready to test your functionality. On your site, add items to your cart and proceed to the checkout process. On the Delivery options page, confirm the new shipping options are listed, along with the real-time rates. In your Debug console, you can check to make sure the rates are being cached correctly for each option. If the cart does not change, the custom module will pull the cache data for the rates, saving you processing time and resources. Moving forward Congratulations, you now have real-time FedEx rates flowing to your app! With this code, you can give users accurate pricing for their shipping options and help them complete purchases faster. You no doubt will want to add additional error handling and fallbacks in your code, in the event FedEx (or your service) is not available. I hope this code helps you create some awesome ecommerce applications and sell tons of merchandise. Good luck! Get the full source. | https://devnet.kentico.com/articles/adding-real-time-fedex-shipping-rates-to-kentico-11 | CC-MAIN-2022-05 | refinedweb | 892 | 57.67 |
LV Please DON'T use XML for configuration files though. I've used several applications that did - hated every one of them...JMN 2007-05-28 Could you or someone please explain this distaste for using XML in configuration files? I can understand that if the more complex features of XML such as namespaces are used - it can get very ugly very quickly from a human readability & editability viewpoint.. but I would have thought that if the configuration file was specified to be constrained in the XML features used it would be a much better format than the myriad ad-hoc & somewhat inconsistent formats that seem to get invented for configurations.In particular.. it seems to me to be a great win for a configuration file parser to be able to pass off a chunk of configuration to some other body of code to deal with, so some sort of tree structure to the data makes a lot of sense.What are the big objections to XML for configuration?LV In my case, both technical and non-technical users dealing with these applications found reading and modifying the XML files difficult. Perhaps if there were absolutely positively NO chance a user had to modify such a file directly, then it would be okay. In the cases I've experienced, applications required the users to code the XML files directly - that was nasty. There were also times, with the same application, where some hardware or OS type problem would occur, causing one or more characters in the file to be changed. Trying to figure out what the right value should be might be obvious to some, but not always.Then there are the applications who tried to embed logic into the XML - attempting to turn it into nearly a programming language. In the end, that application ended up moving from XML into another format in hopes of gaining functionality.[BLG] Unless you really think your config files need semantics, XML is pretty much overkill. In essence you should be serializing the configuration object (or objects depending on how you roll things). Unserializing via a format like YAML reduces the volume of parsing necessary to recreate the object. XML is, and for the foreseeable future, will be all about some form of iterating over the DOM tree. Absolutely essential, I suppose, for a strongly typed language, but as you note, it quickly devolves into something not human readable. I'd go so far as to say that XML/XSL/XSLT are the least preferable method of serializing data unless you really like complexity and need semantics. Very few applications of this sort require that level of semantics, IMHO. Define and solve the problem first, then select the tech to support it and you'll be happier and *much* more successful.
I know that I am too late to fight against RoR- that is not my intention, but I see it more as a fun project.Everybody who is willing to help is invited (I know it will be very few :-) ), but you can also help me with your comments.When I am really starting to implement the project, I will give it the name ToW (Tcl on WebFreeWay). That was inspired by the term, which I saw in the USA, "car in tow" and it should reflect the picture: take that package as a "car in tow" which you just add to your application and you have access to the Web freeway.I hope this page gets a lot of comments on the general idea and on requirements/features you would like to have.This is the starting point to get it somehow done instead only discussing about it!RLH I would have some suggestions. Either use Tcl+Snit to have a pure Tcl solution that is easy to install since it is all Tcl, or use XOTcl. I personally would use Snit for the all-Tcl version. I would also program it to target the CGI space and scale well up to FastCGI and above. It will be much easy to get Tcl installed for CGI and you would have a better chance of more people using it. I know that NearlyFreeSpeech [1] gives you Tcl 8.4.14 to work with as a CGI process. So maybe that could be a proving ground because it is a pay-as-you-go service and would be "cheap" to use.APW I like Itcl much more then XOtcl, so I don't know if that will be the way ..., and I will think about Snit.MR If you're going this way, you may be interested in a short e-book called 'Rubyisms in Rails' (available on Safari and elsewhere). It talks about how some of the particular language features and philosophy in Ruby were taken advantage of to give Rails some of the convenience and expressiveness that people have liked. Some of the techniques would translate nicely to Tcl, some would not, and of course there are some Tcl idioms that might well make a lot of sense in this domain that aren't present in Ruby. The point is, doing a web framework that respects Tcl idioms would be quite different, and probably more interesting and useful, than one that simply tries to clone Rails in Tcl, which would likely result in a weird impedance mismatch.APW It was not my intention to just clone RoR, but to build some Tcl-ish framework and get a little bit inspired from RoR.LV Amen! One of the complaints that I have frequently heard about pTk (a perl effort to make use of the Tk C interface without including any Tcl) has been that the interface was not perl-y enough. I would think there isn't really a need for a straight port of Ruby on Rails to Tcl. Instead, evaluating what people using Ruby on Rails love most - which, from the brief browsing I've done, is the sheer ease of specifying minimal specs and getting generated a web site which takes intelligent defaults (gee, sort of sounds like what some people love about Tk!).APW I am not planning a straight port, that is why I am asking for features which are useful. My direction will be to build some generators to make it easy as LV suggests to build at first simple web pages and later on web pages with more comfort.For example I am thinking about having an XML structure (maybe similar to a XML-Schema specification) and to use that to generate XSLT templates, which then can be filled. But that is an additional feature besides "normal" HTML files. I am also thinking about a little tool which helps you defining CSS files (maybe something in that direction already exists). Another tool would be a simple generator which use a XML, XSLT and CSS file and generates the html file (that's very easy using the tools already there but for beginners that might be hard). I would also like to have as one of the databases a starkit/meta DB and I think some of the tools or all should be in a starkit to make it easy to install and start. There should be also included one of the Tcl http servers to be able to generate a small application to begin with with minimal effort.RS Starting with Schema, XSLT, CSS doesn't look like minimal to me :^) I'd suggest to start from one use case, see what's needed for that, and how it can be implemented with most convenient for the user. Then the next, etc. ... APW you are right, XSLT, CSS etc. are not planned for the start, that is only planned for a later version :-).escargo 16 May 2007 - I've looked at this problem from a couple of viewpoints before. One question that's central is, "Is the user trying to have access to an existing data base store, or is the user wanting to manipulate some population of objects that he or she wants to be persistent?" In the latter case, one could have Snit objects, something like the Snit object inspector, and a Snit persistence layer through a Snit data base connector. (Instead of a Tk interface to the Snit object inspector, one would need to generate a form that presented the same information.)slebetman You guys are already starting to talk about implementation here. Whatever the implementation ends up being, itcl, XOtcl, Snit or plain ensemble, I hope from the user's point of view it looks and feels like Tk. For me, the user, I don't want to be forced to work in an object oriented manner. I guess snit is the most flexible choice. Anyway, the key is the features. What I'd like ToW to have is:
- scaffolding generator (with nice, sensible defaults)
- separation of presentation and business logic (MVC will do this, but there are other ways)
- database neutrality (either a back-end neutral API or, like Rails, a migration tool)
- web server neutrality (scales from CGI and up)
RS: re hype psychology, I'm not sure that "On Tow" has all positive connotations - doesn't it suggest "Here's a defective vehicle being slowly towed to repair or demolition"?APW I had more people in mind which are driving there trailer when having holidays and had their "normal" car in tow. Don't know, if that is still true, my experience is 25 years ago. Nevertheless I am open to a better name for it, please make suggestions. I think it should be a really "cool" name, to help it to become well known, if the project succeeds.stevel Tcl on Trax ?APW What does "Trax" stand for?stevel Trax, Tracks, Rails .... never mind, I was ranting.MR FWIW, most of the suggestions about what to include so far would correlate to building yet another web framework without most of the conveniences that Rails brought (not that there is anything wrong with that, just saying). If you think the big thing about Rails is the scaffolding, you're missing the point. The other meta-note is that one of the reasons Rails was interesting is that (being extracted from a particular type of application), it handles a certain class of application very well, and becomes just gross for many other types of applications. The Tcl community historically has worried a lot about generality and doing things to fit many different situations, which is the antithesis of this approach. Frankly, I'm not about to knock anyone who wants to go about writing a Rails-or-any-other-framework-in-Tcl knockoff from scratch "just because", but my expectations for anything of the sort would be quite modest.Also of interest might be a framework that targets a different type of web (or other) application. Are there niches that existing solutions aren't filling well? Are there any such niches that Tcl seems to do well in? Are there existing Tcl apps in the niche to use as inspiration (extracting the framework from them, or at least core ideas)? Is the niche large enough to support a bit of a community of users, and can enough be put in place off the bat to interest that community? And could people be restrained enough to stay focused and not try to turn it into a general purpose solution capable of doing anything, but nothing well?APW Just one question to MR: what do you mean with "conveniences that Rails brought"? Maybe that also can at least partially be included, if I know what you are speaking about.NEM Like others, I'd say keep it simple and concentrate on a single particular application you want to build. I'd also suggest that the very first thing you should do is figure out why we need this project at all:
- What is wrong with Rails/Django/Struts/whatever?
- What particular advantages would a Tcl framework have?
- What sort of applications do you want to build? Digg/Reddit-style aggregators? Amazon-style business sites? 'Blogs? Forums? Calendaring/email/PIM stuff? Word-processors/spreadsheets/database apps? Pick one to start with.
- There is nothing wrong besides it's not Tcl, so I would need additional SW to be installed
- One application with one environment (using Tcl)
- What is RoR used for mostly?
RLH I would go with <% some code %>. Less to type.APW that is also what I would prefer, as it is also what Tcl Rivet uses, which perhaps some users are familiar with.LV These last two comments puzzle me. I am not certain to what they refer and the comment's don't seem to tie into other things on the page now. Did something get deleted? APW did fix the missing/deleted stuff, don't know how they did disappear during editing from somebody; does anyone have an idea how that can happen and how you can avoid that?.
I have looked around in Symfony, Propel, Creole, Phing - all parts of PHP/written using PHP for doing similar things like RoR and I like very much the strategy used there to put all relevant information into XML/XSL ... files, using DTD and Schema files for validation. Not that I want to start with that directly, but I want to keep that in mind, because that can make automatic validation of input later on relatively easy. As there are already tools in Tcl for handling that sort of things tDOM including XPath, tclXML etc. the parts are already there to be combined for an application.APW inspired from stevel Tcl on Trax what about using TRAX (Tcl Rapid webAccess eXtension) as the name instead of ToWescargo 21 May 2007 - Would there be any benefit to making the templating compatible with what's available as part of AOLserver Dyanmic Pages? (Or is that assuming the answer too soon?) Or is the templating in Wtcl adequate?APW 2007-05-21 after having a more detailed look at symfony [4], propel [5] and phing [6] :
- if you are going to use an execute this type file format, then there are security concerns that will need to be addressed
- likewise, when humans can edit the file, then they are like to mangle it - so checking of the input needs to take care
- certainly there is potential for complaining ... but tcl was designed, initially, to be an embedded language in applications, so that users would use tcl to configure the application. using tcl for the configuration of this system makes a lot of sense to me
databases { customer { tables { person { columns { person_id { attributes { type integer required yes primary_key yes size 10 } } department_id { attributes { type integer required yes size 10 } } first_name { attributes { type string required yes size 25 } } last_name { attributes { type string required yes size 35 } } } } department { columns { department_id { attributes { type integer required yes primary_key yes size 10 } } company { attributes { type string required yes size 25 } } name { attributes { type string required yes size 35 } } } } } joins { person:department { from { table person column department_id } to { table department column department_id } } } } }That could be the "abstract" description of a little database (container). The indentation does not matter; it's just for readability!escargo - When humans can edit the file, to some extent all bets are off. At least with Tcl we can execute the file in a safe interpreter to extract the information. Even with XML, if humans are allowed to edit the file it could still wind up being broken. APW You are right!DKF: That reminds me of dealing with users of some software I wrote that were complaining that "your software is broken", when in fact they'd written ill-formed XML configuration files (despite all the examples being correct) and the software was giving very clear error messages in the log (it was server software, so that was the right way to report problems). The moral? Many users are stupid and will not read even the clearest of instructions. :-(FF: but XML structures also have DTDs. I guess you can perform DTD validation prior to using the XML file; so you'll know if the XML tree is not valid before parsing/using it. Instead I don't like Tcl config files. Yes, they look cool, but it's too easy to break an application and difficult to find such bugs (if whoever has edited the config files was so good at hiding the error, and your syntax highlight can't help).escargo 25 May 2007 - I had a bit of an "aha" moment and realized that there is some code out there that related to this discuss (that's the good news): Orb Spinner. (The bad news is that web site that hosted it is gone.) Orb Spinner was, in some sense, more of a Content Management System than a web application framework because it dealt with static pages rather than dynamic pages. That duality might be considered somewhat artificial. Many of the pieces that Orb Spinner used (data base for values, a templating engine to convert a template + data into an HTML page) could be reused in a more dynamic environment. I'd certainly like to see the possibility of Tcl being used for both static and dynamic pages.APW Do you have any code of Orb Spinner which you could send to me so that I could get some ideas (it sounds interesting from what you are describing), as there seems to be a dead link as you have mentioned. At the moment I am thinking about using a metakit database for the values and files for templates for generating HTML pages with a simple GUI representing the project (this is mainly the root directory), the storage (database or filesystem), the collections (tables in the database) and fields (columns in the database).So the tree structure I am planning could be:
projects wiki # this is the project name storages adapter # which database to use sqlite : collections # the tables in the database pages # this is a table for storing wiki pages fields # the columns in the database name # one of the pages columns used for storing the page name : # here the attributes will be filled in contents # one of the pages columns used for storing the page text : # here again space for the attributes : : authors # this is a table for storing author infos fields name : : project2 storage adapter mysql : :More details to follow. The adapter could be "none", that would be for web pages without a database in back, if you just want to handle the layout using the tool. The collections represent the model (a la MVC (Model/View/Controller)) concept, the views and layout will be below that topic, the controllers will be below the storages.Any comments?escargo - I don't have an OrbSpinner download on the machine I'm using at the moment. I'll have to get a different machine (rarely used) back on-line to look.escargo 27 May 2007 - I had a few more thoughts about this as I was taking a walk today.
- Would there be a benefit to making the templating system more general than an HTML templating system? (The trade-off is one of generality versus convenience for HTML. I can see advantages to both sides. I was imagining the more general templating system being useful for generating Tcl and Tk code on the fly.)
- I was thinking that the templating system needs to be able to handle something like the production of rows in tables. It's not just enough to take one object and create a row for it; there needs to be a way to take in multiple groups of data and produce a whole table with multiple rows.
- The storage adapter should present an interface to the templating subsystem that hides the data source implementation, so that the templating system can ask the data source for more and get something back that has a type that the templating system can make a decision with. Or, the templating system can ask the data source for a list of objects of a particular type and get zero or more back. Given a template and a data source, the templating system processes the template looking for markers that require particular types of objects which it then turns to the data source for. Keeping all of these separate would allow a lot easier unit testing (with the possibility of using mock objects). You could then use adapters with compatible interfaces to provide data sources from CSV files, XML files, YAML files, Metakit data bases, or SQL data bases, as long as there was an appropriate facade to act as the adapter.
Page { id {15} title {my page} description {an example page} text {....} Author { id {346} name {some guy} email [email protected]} } modification_date {20050123} access_counter {474} Comments { {id {4657} text {cool!} Author {id {655} name {some other guy} email {}} date {20070605}} {id {4659} text {sounds interesting} Author {id {125} name {a developer} email [email protected]}} date {20070606}} } }Ideally this data comes directly from the Page model, which knows which operations to perform on read (e.g. increment the access_counter, perform join across the Author and Comment table, ...) like:
set data [MyPageModel::read 15]So that $data holds structured data, but we don't know how to make it appear to the user (work for the template engine).In my opinion a template engine shouldn't know anything about HTML, XML, WAP, PostScript, TeX or whatever, but should be flexible enough to allow mixing both plain text, pseudo-code, loops, and so on, allowing almost a plain representation of the data. If we want to spool the $data (of the Page type/model) both in HTML and XML, we have to do two different views, and we have to know both HTML and XML. From my experience, a template system would work this manner:
<!-- Begin of document ---> <h1>{$title}</h1> <p class="pageDescription">{$description}</p> <hr> <div id="pageText">{$text}</div> <p class="pageAuthor">{$Author:name} (<a href="mailtto:{$Author:email}">{$Author:email}</a>)</p> <!-- comments <table border="0" width="300"> <tr> <th bgcolor="green">Comments (<a href="{$SCRIPT_NAME}?action=add">add a comment</a>)</th> </tr> {foreach from=$Comments item=entry} <tr bgcolor="{cycle<td> posted by {$entry:Author:name|escape} on {$entry:date|date_format:"%e %b, %Y"}<br /> {$entry:text|escape} </td></tr> {foreachelse} <tr><td>No records</td></tr> {/foreach} </table> <!-- End of document --->I hope this will be understandable by most people knowing a bit of HTML or XML (or other markup language). Sorry for being so verbose: I wanted to show some practical (everyday) issues while showing a generic example. The code above I borrowed from PHP Smarty [7] to:
<!-- Begin of document ---> <h1><%= @page.title %></h1> <p class="pageDescription"><%= @page.description %></p> <hr> <div id="pageText"><%= @page.text %></div> <p class="pageAuthor"><%= @author.name %> (<a href="mailtto:<%= @author.email %>"><%= @author.email %></a>)</p> <!-- comments <table border="0" width="300"> <tr> <th bgcolor="green">Comments (<a href="<%= :SCRIPT_NAME %>?action=add">add a comment</a>)</th> </tr> <% foreach |entry| @comments %> <tr bgcolor="<%= cycle<td> posted by <%= escape(@comments.author{entry] => :name) %> on <%= date_format("%e %b, %Y", @comments[entry] => :date) %><br /> <%= escape(@comments[entry] => text) %> </td></tr> <% foreachelse %> <tr><td>No records</td></tr> <% end %> </table> <!-- End of document --->Please don't nail me down on the exact syntax, I have only had a shorter look at RoR and have never used it :-) Nevertheless I think the idea is very similar in both cases, so that seems to be the right direction. The <%= ... %> and <% ... %> syntax is borrowed from ASP (Active Server Pages) to the best of my knowledgeAs I see it after all the discussion, the ideas of symfony, RoR, Smarty seem to relativly similar in using the MVC concept, having an abstraction from the data source, using a generator to convert an input template in some format be it HTML, XML whatsowever with spread in Tcl code to generate (at least for the 3 systems mentioned) HTML output.The spread in code should not only be able to handle one static input of the data source, but to be able to make additional requests to the data source for getting additional input to handle. The data source should be accessed via the abstract CRUD interface (shortly described above), the generators should be able to handle different kinds of templates (i.e. HTML, XML ...). There are controllers which handle the requests (actions) in calling generators for producing the output. The output is driven by the use of templates (the views) which describe how the output has to be formatted and by use of CRUD requests for getting the appropriate data.As HTML and XML have both the < ... > tags there is no problem in parsing the stuff if no validation of the semantic is done, the validation could be done by some different program which could be added later on to the tool. For other stuff WAP, Postscript, TeX etc. one would need a closer look to see, if that is also possible with the same generators or with different ones (at least parsers for the input). As I only know Postscript of these others should comment that.APW 2007-05-30 What about doing the templating the other way around and let the template be some Tcl code which is called like a preprocessor and produces output (for example a HTML page):the above RoR example could then look like:
<%= { <!-- Begin of document ---> <h1>} ; <%= {[@page getTitle]} ; <%= {</h1>} <%= {<p class="pageDescription">} ; <%= {[@page getDescription]} ; <%= {</p>} <%= {<hr> <div id="pageText">} ; <%= {[@page geText]} ; <%= {</div>} <%= {<p class="pageAuthor">} ; <%= {[@author getNname]} ; <%= {(<a href="mailtto:} <%= {[@author getEmail]} ; <%= {">} <%= {[@author getEmail]} ; <%= {</a>)</p>} <%= {<!-- comments --> <table border="0" width="300"> <tr> <th bgcolor="green">Comments (<a href="} ; <%= {[set SCRIPT_NAME]} <%= {?action=add">add a comment</a>)</th> </tr>} set rows [@comments getRows] foreach entry $rows { <%= {<tr bgcolor="} <%= {[cycle values "#dedede,#eeeeee" advance false]} <%= {"><td> posted by} ; <%= {[escape [[[@comments getEntry] getAuthor] getNname]]} <%= { on } ; <%= {[clock format [clock scan [[@comments getEntry] getDate]] -format "%e %b, %Y"]} <%= {<br />} <%= {[escape [[@comments getEntry] getText]] <%= {</td> </tr>} } if {[llength $rows] == 0} { <%= { <tr><td>No records</td></tr>} } <%= {</table> <!-- End of document --->}@page: the @ marks it as a "page" object (from the model of that application). getText, getAuthor etc. are methods of that object which return the field value of the appropriate field of the current row of the object. <%= is a proc which is returning its argument "<%= {hallo}" returns "hallo" or if it starts with "[" is evaluating the argument "<%= {[@page getTitle]}" returns the title field contents of the current row of the page object. the escape proc would do the HTML escaping.The generator knows what to do with the results (for example it just outputs it to the client using the result as a HTML page).Comments are welcome!escargo 30 May 2007 - If we intend to keep the template syntax close to Tcl syntax, and template data access is understood to always be relative to the current data source, then I could see some things simplifying to "<%$page(title)%>" (if data are stored in tables) or maybe "<[email protected] title%>" if data are stored in dicts, (where @ is syntactic sugar for "dict get $").APW Good idea, I would prefer the dict usage!This would also allow to change the foreach loop above to:
while [@comments nextRow] { @comments getAuthor <%= {<tr bgcolor="} <%= {[cycle values "#dedede,#eeeeee" advance false]} <%= {"><td> posted by} ; <%= {[escape <[email protected] name%>]} <%= { on } ; <%= {[clock format [clock scan <[email protected] date%>] -format "%e %b, %Y"]} <%= {<br />} <%= {[escape <[email protected] text%>] <%= {</td> </tr>} }FF 2007-05-30 - honestly I liked much the first syntax for template (the classic ASP-like). I developed a very minimal template engine at TemplaTcl. I hope you guys get interested in it, and share comments, ideas, and code if needed.APW There has been a very interesting suggestion from jcw Templates and subst on that page. I think that would be a good approach for a template syntax (and an implementation is already there, some lines below :)) )APW 2007-06-07 There seems to be a solution for templating (see above), so the next point is a database abstaction layer. For that I plan to use nstcl. After a closer look at it, it seems to have all the features needed. Nevertheless there will be the need for an additional layer to separate object relations from database table relations. I am looking around to see, if there exists already something in that direction.escargo - Note that nstcl includes a templating system, nstcl-templating [8], [9]
SDW - Adding ToW to the Wiki to describe the implementation "in progress" of these ideas
APN Whatever happened to this project? Is it being worked on or does it now belong to the bursting-at-the-seams open source orphanage?apw 2008-12-10 at the moment there is no action from my side, as I am working on 3 other Open Source projects itcl-ng, ntkwidget and reportingTools. itcl-ng work will go down (I hope) when the 1st beta version will be released this week. If I have some spare time and ideas, I will continue with the small parts I have started to code. So don't expect to much from my side within the next few months. Nevertheless I don't see it as a dead project, only delayed.
CMcC 2010-2-22 opines: it is a major error to copy the name of a competing product. It represents a reactionary stance, which is never a good look. It also unconsciously hems you in, so you miss all the opportunities to be different and better, and you set your sights so low that all you set out to achieve is to become a knock-off.
apw 2010-04-02 my implementation project has now started with a different name, it is called ATWF.
See: Woof! Spindle | http://wiki.tcl.tk/18088 | CC-MAIN-2017-26 | refinedweb | 4,991 | 57.81 |
What is Kivy?
Kivy is a free, open source Python library that allows for quick and easy development of highly interactive multiplatform applications..
Knowledge you need to get started with Kivy
This tutorial requires some knowledge of Python, and very basic terminal skills, but also it requires some understanding of Object-Oriented Programming (OOP) concepts. If you are not good with the classes and object oriented programming, don’t worry, just go through my Object Oriented Programming tutorials, so that you don’t find any difficulties in future.
Let’s create the most basic app with kivy:
from kivy.app import App from kivy.uix.button import Label class hello(App): def build(self): return Label(text="Hello, World") if __name__=='__main__': hello().run()
This is a very simple Python code. Launching a Kivy program is not any different from launching any other Python application.
#Output:
So, is Kivy just another library for Python? Well, yes. But as part of the library, Kivy offers its own language in order to separate the logic from the presentation and to link elements of the interface.
Moreover, remember that this library will allow you to port your applications to many platforms. Let’s start to explore the Kivy language. We will separate the previous Python code into two files, one for the presentation (interface), and another for the logic. The first file includes the Python lines:
file name – hello.py
from kivy.app import App from kivy.uix.button import Label class hello(App): def build(self): return Label() if __name__=='__main__': hello().run()
The hello.py code is very similar to our previous. The difference is that the method build(self) doesn’t have the Hello World! message. Instead, the message has been moved to the text property in the Kivy language file (hello.kv).
file name- hello.kv
<Label>: text: 'Hello, World!'
You might wonder how Python or Kivy knows that these two files (hello.py and hello.kv) are related. This tends to be confusing at the beginning. The key is in the name of the subclass of App, which in this case is hello.
Once that consideration is included, this example can be run in the same way we ran the previous one. We just need to be sure we are calling the main file – python hello.py .
It will give us the same output as above.
That’s it for today we will continue in the next chapter. | https://thecleverprogrammer.com/2020/05/09/python-kivy-tutorials-introduction-to-kivy/ | CC-MAIN-2021-43 | refinedweb | 410 | 68.26 |
hello, im newbie here and also newbie in c++. I have a problem with char data type. I try writing the code input character 'D', 'd', 'R' and 'r'. if input are correct, the output will be 'OK' but turn out, even I give input other character, still give the output 'OK'. anyone can help me resolve the problem?
this is my code;
#include <iostream> using namespace std; int main () { char choice ; choice = 'D', 'R', 'd', 'r'; cout << "Insert choice: "; cin >> choice; if ( choice == 'D' || 'd' || 'R' || 'r' ) { cout << "OK!" << endl; } else cout << "Nub!" << endl; return 0; }
p/s: im using mingw g++ compiler | https://www.daniweb.com/programming/software-development/threads/301040/problem-with-char-data-type-help-plz | CC-MAIN-2017-17 | refinedweb | 104 | 83.76 |
Hello all,
I want to save particle data in hdf5file. In order to do this, I need to import 'h5py' module. I think I need to add 'h5py'module in Yade library, is it possible?
Thank you for your help in advance.
Jinny Kim.
Question information
- Language:
- English Edit question
- Status:
- Expired
- For:
- Yade Edit question
- Assignee:
- No assignee Edit question
- Last query:
- 2019-09-09
- Last reply:
- 2019-09-24
I tried that, but I got this error: ImportError: No module name h5py. When I run the python script, I am using this command in terminal: yade filename.py..
Have you installed h5py to your computer?
If yes, how?
If no, what version of yade you use?
Jan
Yes, I have installed it. I installed it with Miniconda by following [1].
[1] http://
Could be python 2/3 problem.
What does Yade says if you type
import sys; sys.version
?
what is the output of command line commands
python -c "import h5py"
python3 -c "import h5py"
?
thanks
Jan
What does Yade says if you type
import sys; sys.version
?
> '2.7.12 (default, Nov 12 2018, 14:36:49) \n[GCC 5.4.0 20160609]'
what is the output of command line commands
python -c "import h5py"
python3 -c "import h5py"
?
> If i try those commands in the terminal, there is no any output.......
> If i try those commands in the terminal, there is no any output.......
it means everything is ok and h5py is available for both python 2 and 3.
For some reason, the installation with miniconda (don't know it) is not visible for Yade. You can try:
a) point python to the actual installation in your script:
import sys
sys.path.
import h5py
b) use pip
pip install h5py --user
(or without --user, then you would need sudo)
c) use apt
sudo apt install python-h5py
cheers
Jan
Thank you so much for your help. Can I ask a simple question? how to find the path where h5py was installed?
I am trying (a) in your reply. I found the path of the module like this:
import sys
sys.modules['h5py']
Then, I tried (a) by using the path that I got above. but tase said 'no module named h5py'..
Okay, I think I found the problem. when I try this command (python2 -c "import h5py"), it says that 'no module named h5py. I think h5py is no available for python2..
This question was expired because it remained in the 'Open' state without activity for the last 15 days.
Hi,
> In order to do this, I need to import 'h5py' module.
yes. it should be no problem (or?)
> I think I need to add 'h5py'module in Yade library, is it possible?
just use h5py in your python script
(not sure what you mean by library)
cheers
Jan | https://answers.launchpad.net/yade/+question/683753 | CC-MAIN-2019-47 | refinedweb | 473 | 84.47 |
Basic constructs (Java)
This article describes some basic constructs in the Java programming language. This is not a tutorial, just a collection of example code. The Java Tutorial is the standard place to go for a tutorial introduction to the Java language.
[edit] Loops
There are 3 standard ways to create a loop in Java.
The for-loop is the most commonly used.
The following example will print the numbers from 0 to 9 on separate lines.
<<for loop>>= System.out.println("For loop"); for(int i = 0; i < 10; i++) { System.out.println(i); } System.out.println();
Here is an example of a while-loop. The output is exactly the same as in the for-loop example.
<<while loop>>= System.out.println("While loop"); int j = 0; while(j < 10) { System.out.println(j); j++; } System.out.println();
The do-while-loop works like the while-loop, except the test expression is evaluated after the code block.
<<do-while loop>>= System.out.println("Do-while loop"); int k = 0; do { System.out.println(k); k++; } while (k < 10); System.out.println();
<<loops>>= public void loops() { for loop while loop do-while loop }
Note:
Sometimes infinite (never ending) loops might be useful. You can write them as
for(;;),
while(true).
[edit] Simple I/O
Unfortunately, compared with similar languages like C, Java's I/O is rather more challenging than it should be. Most programs dealing with input/output require the java.io package.
<<import java.io>>= import java.io.*;
Java has a very rich IO system. Here we illustrate the two most commonly required IO methods: standard input and output (input from keyboard, output to console) and text-file IO.
<<input and output>>= void io() throws IOException { String line = null; standard input and output file input and output }
[edit] Standard input/output
Output to the console (stdout) and the error stream (stderr) is relatively simple in Java and is handled by the methods
println(String) and
print(String) of the
java.io.PrintStream methods of the system objects
java.lang.System.out and
java.lang.System.err.
System.out.print("Hello World!");
prints
Hello World! and
System.out.println("Hello World!");
prints
Hello World!<NEWLINE> (that is
println adds the system-specific new-line character sequence to the text of the argument). A useful additional method call is
System.out.println() which prints only the new line character. For portability it is safer to use
println than to use the C-like convention
System.out.print("Hello World!\n");
In Java, intput from the keyboard (stdin) is more of a challenge! For reasons of flexibility, the Java IO system is designed so that different sources and sinks of data can easily be combined. For this purpose it makes use of the Decorator pattern which makes it relatively simple to wrap a suitable IO processor around any source of data (for example a file, keyboard or network connection). Unfortunately, the designers of the language failed to provide a simple-to-use object for the simplest form of IO of all: text from the keyboard. The object
java.lang.System.in, which represents the keyboard, is a
java.io.InputStream, an object which cannot be used directly to input lines of text. To make it useful as a source of strings, System.in has to be decorated by an
InputStreamReader which itself has to be decorated by a
BufferedStreamReader:
<<create source of input>>= BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
Once we have done this, we can read a line from the keyboard using the method
in.readLine().
<<standard input and output>>= System.out.println("Standard I/O"); create source of input System.out.print("Type a line of text (enter with Return): "); line = in.readLine(); System.out.println("You entered: " + line); System.out.println();
[edit] File reading writing
This code will read the first line of the file input.txt and write the same line to output.txt.
[edit] Create a File to Read and Write
Let's create a file for testing purposes.
<<input.txt>>= Now is the Winter of our Discontent Made glorious Summer by this son of Yorke;
[edit] Reading from a Text File
To read a text file it has to be opened. In Java this is achieved decorating a
FileReader with a
BufferedReader. The filename is passed to the
FileReader as a constructor argument.
<<open input file>>= BufferedReader fin = new BufferedReader( new FileReader("input.txt"));
To read a line from the file, we simply call
readLine() on the
BufferedReader. If we have reached the end of the line,
readLine returns
null:
<<read first line from input file>>= line = fin.readLine(); if (line == null) throw new EOFException("Unexpected End of File encountered while reading \"input.txt\"");
Closing an input file is a simple as calling the
close() method on the
BufferedReader. This will also close the
FileReader and hence the file.
<<close input file>>= fin.close();
[edit] Writing a Text File
Opening a file for writing is similar to the procedure for opening a file for reading. This time we decorate a
FileWriter with a
BufferedWriter, and decorate the
BufferedWriter in turn with a
PrintWriter.
<<open output file>>= PrintWriter fout = new PrintWriter( new BufferedWriter( new FileWriter("output.txt")));
We can use
fout.println to print the line to this new file.
<<write line to output file>>= fout.println(line);
Now close the
PrintWriter which closes the file.
<<close output file>>= fout.close();
[edit] Handling IO Exceptions
Java has support for exceptions built-into the language, and an exception handler built-in to the runtime system. IO operations should make use of try-catch blocks to ensure that any IO errors are handled by the exception handler. As we can't actually do anything useful if this progam fails (which will most likely be due to file permissions), we simply print an error message and rethrow the exception which will cause the program to close and print a stack trace.
<<file input and output>>= try { open input file read first line from input file close input file } catch (IOException e) { System.err.println("ERROR: Cannot read \"input.txt\""); throw e; } try { open output file write line to output file close output file } catch (IOException e) { System.err.println("ERROR: Cannot write to \"output.txt\""); throw e; }
[edit] Command line arguments
Java is always executed by starting the virtual machine and passing it the class that contains the main method:
java AClass [command line arguments]
The optional command line arguments are passed to the body of the main method via an array of strings which is conventionally named
args.
<<main method>>= public static void main(String[] args) throws Exception { BasicConstructs bc = new BasicConstructs(); validate command-line arguments process command-line arguments System.exit(0); }
Array access is used to access the arguments. The number of arguments to process will be accessible via the field
args.length. Unlike C, this number does not include the command itself (which will always be java classname).
<<process command-line arguments>>= for (int i = 0; i < args.length; i++) { if ( "loops".equals(args[i]) ) bc.loops(); else if ( "io".equals(args[i]) ) bc.io(); else { unexpected command-line argument } }
When the wrong number of arguments are passed to the program:
<<validate command-line arguments>>= if (args.length < 1) { System.err.println("ERROR: Wrong number of arguments"); bc.usage(); }
or incorrect or unexpected arguments are encountered while processing the command-line arguments:
<<unexpected command-line argument>>= System.err.println("ERROR: Unexpected command line argument: " + args[i]); bc.usage();
programs normally display an error mesage, along with a usage message showing the allowed arguments.
<<display usage message>>= private void usage() { System.err.println("Usage java BasicConstructs loops|io"); System.exit(1); }
[edit] The Program
<<BasicConstructs.java>>= import java.io public class BasicConstructs { loops input and output display usage message main method }
[edit] Reference
Bruce Eckel, Thinking in Java, 4th Ed., Prentice Hall, 2006. | http://en.literateprograms.org/Basic_constructs_(Java) | CC-MAIN-2015-27 | refinedweb | 1,319 | 59.09 |
Under.
icinga2 console <1> => keys(globals) [ "Environment", "Icinga", "Internal", "MaxConcurrentChecks", "NodeName", "StatsFunctions", "System", "Types" ]
“Environment”, “MaxConcurrentChecks”, “NodeName” are special global constants, the other keys are registered namespaces. You can access specific constants either via namespace prefix, or without.
<2> => System.ApplicationVersion "v2.9.1-180-gc9db7a0" <3> => PlatformName "CentOS Linux"
Coming from v2.9 and older, nothing changes if you’re using global constants and functions.
There’s one safety warning in place though: When you’re overriding a constant at some later point, the configuration compiler will log a warning including the file and line details.
What’s in there for me?
Think of your own safe place for constants and functions.
v2.9 introduced a global constant called “Environment” which will be used for TLS SNI handling in an addon. This broke an existing Icinga setup (no-one reads upgrading docs ;)). In addition to that, global functions are currently registered in this “cumbersome” syntax:
globals.functionname = function(param1, param2) { ... }
while the documentation on functions suggests to rather write
function functionname(param1, param2) { ... }
if we would have a namespace. With v2.10, you have and I’ll show you in a bit how to solve this.
Create a namespace
Prepare the configuration and include the newly created “namespaces.conf” file in your “icinga2.conf” configuration file.
vim /etc/icinga2/icinga2.conf include "constants.conf" + include "namespaces.conf"
Next, edit “namespaces.conf” and add a namespace with the unique name
vim /etc/icinga2/namespaces.conf" namespace ApplyFunctionsBE { Mysql.databases["production"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } Mysql.databases["staging"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } }
This is safe, and when you now open the debug console, the namespace isn’t used globally yet.
Use a namespace
Namespaces can be loaded into the current scope with the “using” keyword. Edit “namespaces.conf” again and add the following after the namespace declaration. Note: This loads the namespace immediately. You can also move this into a specific configuration file on top – think of Python package imports for example.
vim /etc/icinga2/namespaces.conf using ApplyFunctionsBE
Now restart Icinga 2 and use the debug console to connect to the running instance via REST API.
systemctl restart icinga2 ICINGA2_API_USERNAME=root ICINGA2_API_PASSWORD=icinga icinga2 console --connect '' <1> => ApplyFunctionsBE { Mysql = { databases = { .... } } }
The above example shows you how to access an attribute registered in this namespace. You can use that in your configuration objects and apply rules then. Thanks to loading the namespace, you can directly access the namespace variables too.
Add a function to a namespace
Next to specific variables in namespaces, you might want to register functions in a specific namespace. This keeps the global namespace safe and no-one is allowed to override this function by accident.
Go with a simple example which flattens a nested dictionary like this (e.g. from a host “vars” dictionary).
databases["production"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } databases["staging"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } }
to
result["production-app1"] = { "port" = 3306, "location" = "BE" } result["production-app2"] = { "port" = 3307, "location" = "BE" } result["staging-app1"] = { "port" = 3306, "location" = "BE" } result["staging-app2"] = { "port" = 3307, "location" = "BE" }
The algorithm is easy, the function rather short, and it has a namespace specific custom attribute inside. I’ve hacked up this function in 10 minutes, it includes error handling and logging. Feel free to adopt or enhance :)
/* namespace begin: ApplyFunctionsBE. */ namespace ApplyFunctionsBE { const MysqlUsername = "icinga-be" /* Flatten a dictionary with unique keys for service apply for rules. */ function flattenDictionary2ndLevel(d) { var res = {} if (typeof(d) != Dictionary) { log(LogWarning, "config", "ERROR: flattenDictionary2ndLevel parameter is not a dictionary.") return {} // return an empty result set on error, including the log above } for (k1 => v1 in d) { if (typeof(v1) != Dictionary) { log(LogWarning, "config", "ERROR: First level with key " + k1 + " is not a dictionary value.") continue; } for (k2 => v2 in v1) { var new_key = k1 + "-" + k2 /* Generate a unique name. */ var new_val = v2.clone() /* Add a namespace specific variable. */ new_val["username"] = MysqlUsername /* This pulls in the namespace local constant. */ res[new_key] = new_val } } return res } /* This is for testing only. Move this into an actual host object. */ Mysql.databases["production"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } Mysql.databases["staging"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } /* namespace end: ApplyFunctionsBE. */ } /* Load namespaces. */ using ApplyFunctionsBE
Validate the configuration, restart Icinga 2 and test again with the debug console. This results in the following output:
<8> => ApplyFunctionsBE.flattenDictionary2ndLevel(ApplyFunctionsBE.Mysql.databases) { "production-app1" = { port = 3306.000000 username = "icinga-be" } "production-app2" = { port = 3307.000000 username = "icinga-be" } "staging-app1" = { port = 3306.000000 username = "icinga-be" } "staging-app2" = { port = 3307.000000 username = "icinga-be" } }
Note: The debug console requires to explicitly load the namespace again for tests. The configuration snippet above already takes care for the config compiler.
<9> => using ApplyFunctionsBE; flattenDictionary2ndLevel(Mysql.databases)
A configuration example can look like this:
object Host "namespace01" { check_command = "dummy" vars.mysql_databases["production"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } vars.mysql_databases["staging"] = { "app1" = { "port" = 3306 }, "app2" = { "port" = 3307 } } } /* This explicitly accesses the namespace. */ //apply Service "mysql-" for (db_key => config in ApplyFunctionsBE.flattenDictionary2ndLevel(host.vars.mysql_databases)) { /* This requires using the namespace globally. */ apply Service "mysql-" for (db_key => config in flattenDictionary2ndLevel(host.vars.mysql_databases)) { check_command = "dummy" vars += config }
What’s next?
Use the snapshot packages (e.g. inside the Vagrant boxes) and play around with the namespaces. Find a suitable use case for you and share your ideas and findings on the community channels :)
v2.10 will be released end of September. Special thanks to Gunnar for implementing this nifty feature.
> v2.9 introduced a global constant called “Environment” which will be used for TLS SNI handling in an addon. This broke an existing Icinga setup (no-one reads upgrading docs ;))
Well, to be fair… this was added to the upgrading docs for 2.10 after we reported () that it broke stuff in 2.9. The 2.9 upgrading docs do not mention the new constant.
But all nitpicking aside: Thanks for fixing it by introducing namespaces to Icinga2! :) | https://icinga.com/2018/09/17/icinga-2-dsl-feature-namespaces-coming-in-v2-10/ | CC-MAIN-2018-43 | refinedweb | 989 | 51.65 |
44
Joined
Last visited
Community Reputation12048 Excellent
About Nypyren
- RankContributor
Personal Information
- LocationEugene, OR, USA
- Interests|programmer|
Nypyren replied to MarcusAseth's topic in Math and Physics[redacted] I missed the part where you're doing axis+angle rotation.
Nypyren replied to Josheir's topic in For BeginnersEach dot is a "commit" - they represent changes made to one or more files. A single line between two commits means that the upper commit was created from the lower commit. In other words, the person who created the upper commit had the lower commit checked out when they committed their changes. The lower commit is called the "parent". A commit which has more than one parent is a "merge". These happen because two people can begin their work at the same time on different computers from the same (or different) starting points, make commits separately which don't know about each other, then try to push later. When the second person tries to push, git will tell them that they need to pull first. When they pull, git will merge the other person's work into their branch (and possibly need to resolve conflicts). This 'merge' step creates the multi-parent merge commits. After that, the second person can push. At any time, you or someone else can check out any commit in the history they want, and start making commits at that point. You can then merge those commits into any branch you want, if you feel like it, or leave them separated if you decide not to merge them (perhaps they are an experiment that you want to keep separate, for example). Clarification about 'local' and 'remote' branches: The branch you see on your own computer called "origin/master" is sometimes called a "remote tracking branch", frequently shortened to just "remote branch" and represents where your computer last fetched/pulled that branch from the 'origin'. 'origin' is the default name of whatever host (github, bitbucket, visual studio team services, etc) you cloned from, and where you push/pull to by default. The remote branch on your computer can differ from where the equivalent branch is on github/bitbucket/etc. It only updates when you fetch, pull, or push that branch. When you commit, you only update your local branch.
Nypyren replied to AlluMihu's topic in Networking and MultiplayerH.
- Yeah, 53 languages is a lot. The games I work on only support 16. I'm not sure how many strings-per-language we have, but it's definitely in the thousands. We don't support third party mods, so that's a distinct advantage. As far as finding the longest strings, we have a mode in our UI editor where it will will automatically look up all of the strings for a given widget, measure their size, and display the longest one. Then the UI designer lays the dialog out so everything fits. Then we have another mode where we rapidly cycle through all languages while rendering the dialog, and the UI designer interacts with the dialog while it's cycling through languages to make sure nothing breaks.
- For my own UIs, I generally prefer to avoid the "localization can change things size" idea - instead, I find the widest possible localized string and lay the UI out for that size by hand. This guarantees that nothing surprising will happen due to automatic layout. For user-entered data or things like large data sets, I prefer to build in WinForms/WPF-style vertical/horizontal splitters (draggable separators which let the user control the width/height of the two adjacent UI elements themselves). I also prefer the WinForms style of using left/right/top/bottom Anchors to control child size when a parent size changes. This allows for the user to customize the UI for what they want to see, instead of being at the mercy of your automatic layout code and the UI design team. In this approach, *nothing* changes size other than when the user explicitly changes it.
- When you say "immediate-mode" I immediately think of Unity's "OnGUI" approach. It's simple for doing a few buttons, but gets massively slower the more you do - this is due to the OnGUI function hierarchy being called multiple times in different 'states' - layout, input handling, rendering, etc. I *much* prefer OOP retained-mode UIs - WinForms, WPF, NGUI and UnityEngine.UI for example. You construct an object hierarchy and separate methods on those objects can handle input, rendering, layout. You can split things up by component like Unity does, keep objects monolithic like WinForms does, use visitor patterns, or however you feel like doing it. As far as your layout concern goes, what I usually see is the layout is only recalculated if something changes - when a control is resized, it propagates the layout change up and down the hierarchy. On frames where the layout is not changing, no layout code is executed at all and rendering simply uses the cached layout rects of each control from the last time layout was recalculated.
Nypyren replied to khawk's topic in NewsC# 6 and .Net 4.6 Good, GOOD.
Nypyren replied to blueshogun96's topic in Games Career DevelopmentSeattle and SF have ridiculously high cost of living, high competition, and lots of companies that go bust quickly. You might try Oregon or Texas, if you can find any jobs in those states. (I'm in Oregon.)
Nypyren replied to Crayz92's topic in Networking and MultiplayerMemory bandwidth on modern x86-64 class hardware is usually a few gigabytes/sec. But keep in mind that the more of that bandwidth you use for allocations, the less you can use for actual work. I've seen 'surprising' things that on the surface don't LOOK like they would use a lot of memory bandwidth in C#, such as concatenating strings with the + operator. I ran into one case where someone was creating a 100K string one character at a time and estimated that the combined memory access was in the dozens of gigabytes. The operation was mostly RAM-speed-limited due to this and took about 10 seconds. Changing to a StringBuilder instead limited the operation to less than a meg of memory access and took less than a millisecond.
Nypyren replied to Crayz92's topic in Networking and MultiplayerImproving performance means reducing computations, and memory management is computations. But if you know that you only need 30 steps per second, you have a well-defined budget for computations: You have 33ms worth of time to do whatever you want, and if your memory allocations and GCs still fit within that budget, then you're fine. That said... megabytes per update seems a bit high to me. If you look in unity's profiler, what are the majority of those allocations?
Nypyren replied to Josheir's topic in For BeginnersVS2017 has a mode where the solution explorer browses folders before you've opened a solution - Perhaps this is what you're seeing? Make sure you actually open a .sln file.
Nypyren replied to Dovahfox's topic in For BeginnersProgramming languages let you organize code by building things out of small, well-defined pieces. Larger pieces of the program are built by combining smaller pieces. The way that these pieces are allowed to be combined are defined by the language's "grammar". For example in the C# code: X = Y + 1; "X" and "Y" are identifiers (which can be used anywhere an expression is allowed). "1" is an integer-literal (which can also be used anywhere an expression is allowed). "Y+1" is an additive-expression (which is a type of expression). "X = Y+1" is an assignment (which is also a type of expression). "X = Y+1;" is an expression-statement (which is a type of statement). A function can contain statements. A class can contain one or more fields, properties, functions. Classes can be put inside namespaces. A program can contain multiple namespaces. You can see the entire set of what pieces are allowed to be combined in its nitty-gritty detail in a formal grammar. Usually this is too hard to read for day-to-day purposes but sometimes you can find something that you didn't know was possible by reading through them:
Nypyren replied to myvraccount's topic in For BeginnersFor hard drive encryption, you've got BitLocker and other full-disk-encryption systems. For RAM encryption, there are things like AMD's SME or Intel's SGX.
Nypyren replied to laiyierjiangsu's topic in For BeginnersDo you have edit-and-continue turned on and you're looking at the JMP thunk?
Nypyren replied to NikiTo's topic in General and Gameplay ProgrammingI'm guessing that the C# thread has already called CoInitializeEx itself. I believe this is what the [STAThread] and [MTAThread] attributes do on the default Program.Main function that a new project template has. If your C# entry point doesn't have [STAThread] on it, try adding it. | https://www.gamedev.net/profile/35207-nypyren/?tab=topics | CC-MAIN-2017-30 | refinedweb | 1,501 | 61.16 |
Elly’s Prime Matrix
Happy Fourth of July to our Topcoders in the United States of America! What is a better way to celebrate freedom than by solving a statistics problem (more specifically a matrix problem)! Elly’s Prime Matrix was originally a qualification round problem for TCC India 2018. The solution below follows the outline provided by jeel_vaishnav.
The problem statement is as follows: Elly has a matrix of digits. There is a prime number in the matrix, and it can be summoned by taking one digit from each row and concatenating the digits (in the order of first to last). The solution to the problem involves providing how many prime numbers are possible from the matrix.
The matrix is provided as a String[] to the method getCount() which then returns an int. The length of the resulting string, m, is provided as the number of rows in the matrix, m. For example, let us say we have a matrix:
“4,0,6” “1,1,2”
The possible prime numbers are: 02. Therefore, the number of outputs is 1. If the matrix is constructed as such:
“4,1,6” “1,0,2”
There are no prime numbers, so the resulting output is 0.
With this in mind, let us start looking at the solution. Let us say that in an unordered_set str_set, we need to find the size of the set. We can:
Code: C++ int ans = str_set.size();
This will return the number of possible prime numbers as the size of the set will be the prime numbers found.
Now let us look at how we will find the prime numbers in the set. The idea is fairly simple. Just take the matrix string and concatenate the numbers together and check if the numbers are prime or not. The numbers that are found to be prime are added to the set.
Pseudocode:
set <string> created_numbers, prime_set; for (int i = 0; i < num_rows; i++): string num_str; for (int j = 0; j < num_col; j++): num_str.add(j) created_numbers.add(num_str) for (int i = 0; i < created_num.size(); i++): if(created_num[i] is prime): prime_set.add(i); else: continue
Now that the pseudocode has been written, let us write the code in C++. The code will take advantage of C++’s strings, type casting capabilities, and unordered sets. Note the code has not been compiled and tested.
Code C++:
EllysPrimeMatrix.h:
#include <cstdlib> #include <iostream> #include <fstream> #include “string.h” Class EllysPrimeMatrix{ public: int getCount(str[] s); };
EllysPrimeMatrix.cpp:
#include “EllysPrimeMatrix.h” int EllysPrimeMatrix::getCount(str[] s){ int ans = 0; char [ ][ ] a = new char[s.length()][ ]; int row = s.length(); for (int i = 0; i < row; ++i){ a[i] = (char) s[i]; } int column = a[0].length(); int prime[ ] = new int []; prime[-1] = new int[MAX_INT]; prime[0] = -1; for (int i = 2; i < MAX_INT-1; ++i){ if (prime[i] == 0){ for (int j = i; j <= MAX_INT-1; j ++) { prime[j] = i; } } } unordered_set <int> prime_set = new unordered_set<>(); set.add(0); for (int i = 0; i < row; ++i){ unordered_set <int> new_set = new unordered_set<>(); for (int j = 0; j < column; ++j){ for (int k = 0; k < prime_set.size(); ++k){ int val = k * 10 + (a[i][j] - ‘O’); new_set.add(val); } prime_set = new_set; ans = prime_set.size(); } } return ans; }
The original answer was written in Java. Be sure to catch the next SRM that will occur on July 9th. Happy Fourth of July and happy coding!
| https://www.topcoder.com/blog/ellys-prime-matrix/ | CC-MAIN-2019-39 | refinedweb | 571 | 75.2 |
Frequently Asked Questions
This.
Why is it named angr?
The core of angr's analysis is on VEX IR, and when something is vexing, it makes you angry.
How should "angr" be stylized?
All lowercase, even at the beginning of sentences. It's an anti-proper noun.
How can I get diagnostic information about what angr is doing?
angr uses the standard
logging module for logging, with every package and submodule creating a new logger.
The simplest way to get debug output is the following:
import logging logging.
Why is angr so slow?
How do I find bugs using angr?.
Why did you choose VEX instead of another IR (such as LLVM, REIL, BAP, etc)? supports x86.
- lables (i.e., the
Ijk_Retfor returns,
Ijk_Callfor calls, and so forth) are VEX enums.
- VEX treats registers as a memory space, and so does angr. While we provide accesses to
state.regs.raxand friends, on the backend, this does
state.registers.load(8, 8), where the first
8is a VEX-defined offset for
raxto the register file.
To support multiple IRs, we'll either want to abstract these things or translate their labels to VEX analogues.
My load options are ignored when creating a Project.
CLE options are an optional argument. Make sure you call Project with the following syntax:
b = angr.Project('/bin/true', load_options=load_options)
rather than:
b = angr.Project('/bin/true', load_options)
Why are some ARM addresses off-by-one?.
How do I serialize angr objects?
Pickle will work.
However, python will default to using an extremely old pickle protocol that does not support more complex python data structures, so you must specify a more advanced data stream format.
The easiest way to do this is
pickle.dumps(obj, -1). | https://docs.angr.io/docs/faq.html | CC-MAIN-2017-51 | refinedweb | 290 | 69.89 |
Welcome to the world of Graphs. If you have connected data then you might need one of the types of graphs to model those patterns. There are several things that can be done with Graphs like mapping traffic patterns, managing water distribution networks, social media analysis, etc... At it's heart we need to be able to create Nodes and Edges with data associated about each.
NetworkX is a library dealing with Graph Database creation/import/export/manipulation/algorithms/plotting. You can start using several types of network graphs. For example: Facebook might put their users in a plain Graph()
import networkx as nx facebook = nx.Graph() facebook.add_node('you') facebook.add_node('me') if both_agree_to_be_friends('you','me'): facebook.add_edge('you','me') #order isn't important here.
Facebook would use a regular Graph() because there isn't anything special about the edge between nodes. This Facebook example can only have one edge (friendship) between nodes.
Another type of Graph would be a Directed Graph. Twitter would use a Directed Graph because the nodes have a direction. In Twitter I can follow you but you don't have to follow me. So we could represent that with this code:
import networkx as nx twitter = nx.DiGraph() twitter.add_node('you') twitter.add_node('me') twitter.add_edge('me','you') #order is important here.
This is how Twitter might set up 'me' to follow 'you', but not the other way around.
There are MultiGraphs() and MultiDiGraphs() as well just in case you want more than one edge between two nodes. These four types cover a wide variety of problems that can be represented with Graphs. If you want you can add a dictionary of data to both nodes and edges. The documentation on this module is incredible. Every algorithm is well researched and well implemented. I hope you enjoy working with it.
Installation instructions: The detailed instructions on installing NetworkX is available here.
As with any other python package, NetworkX can be installed using pip, Miniconda/Anaconda and from source code.
Installing with pip
pip install networkx
An attempt will be made to find and install an appropriate version of NetworkX that matches your operating system and Python version.
To use pip, you need to have setuptools installed.
If you want to install the development version from GitHub, use the command
pip install git://github.com/networkx/networkx.git#egg=networkx
Miniconda and Anaconda use
conda for software installation/updates.
NetworkX is currently installed with Anaconda. Miniconda doesn't come with NetworkX by default.
You can update/install NetworkX to the latest version with:
conda install networkx
or if you want to update NetworkX installation then
conda update networkx
Installing from source
Source file archive
python setup.py installto build and install
Installing from GitHub
Clone the NetworkX repository (see for options)
git clone
Change directory to NetworkX
Run
python setup.py install to build and install
(Optional) Run nosetests to execute the tests if you have nose installed.
If you don’t have permission to install software on your system, you can install into another directory using the
--user,
--prefix, or
--home flags to setup.py.
Requirements To use NetworkX you need Python 2.7, 3.3 or later
Optional Packages
3: 2: | https://riptutorial.com/networkx/example/18973/installation-or-setup | CC-MAIN-2021-25 | refinedweb | 538 | 57.87 |
Setting up an array of objects
Joe Lank
Greenhorn
Joined: Jun 08, 2004
Posts: 9
posted
Jun 08, 2004 15:00:00
0
I'm having trouble accessing arrays of objects, probably something wrong with my syntax declaring the array.
class Student1 { public void Student() { System.out.println( "Call to constructor complete." ); }} public class Student { public static void main ( String[] args ) { Student1 stu[] = new Student1[ 5 ]; stu[1].Student(); // This is where I have trouble }}
This gives a
java.lang.NullPointerException
error. Any help is greatly appreciated.
[ June 08, 2004: Message edited by: Joe Lank ]
Jason Fox
Ranch Hand
Joined: Jan 22, 2004
Posts: 114
posted
Jun 08, 2004 15:32:00
0
When you initiate the Student1 array, you are creating a new Student1[] (array) object, you are not creating any Student1 objects, and since all array objects (or primitives) are assigned there default value, each Student1 object in the Student1[] array object is set to null. Try:
stu[1] = new Student(); stu[1].Student();
I hope this makes sense.
Mark Vedder
Ranch Hand
Joined: Dec 17, 2003
Posts: 624
I like...
posted
Jun 08, 2004 15:54:00
0
Hi Joe,
Welcome to JavaRanch� A quick administrative note, it is generally a lot easier if you place any sample code in UBB [code] [/code] tags. It makes reading the code much easier. Take a look
here
to learn how to use UBB�
In addition to Jason�s comment, there is another "problem" in your code that should be pointed out so you do not confuse yourself about something. Looking at your code with line numbers for easy referencing:
01 class Student1 02 { 03 public void Student() 04 { 05 System.out.println("Call to constructor complete."); 06 } 07 } 08 09 public class Student 10 { 11 public static void main(String[] args) 12 { 13 Student1 stu[] = new Student1[5]; 14 stu[1].Student(); // This is where I have trouble 15 } 16 }
The code on lines 3-6 is not actually a constructor, as you indicate in your System out comment; based on the way you have it defined, it is a method. Constructors must be named the same as the class and do not have a return type, not even void. I think you just made a typo since you have similarly named classes, Student and Student1. To be a constructor, you need to change line so the name matches the class, and remove the return type:
public Student[B]1[/B]() { System.out.println("Call to constructor complete."); }
This will now output the comment when you construct an instance of Student1 using the syntax Jason gave you.
Previously, a Student1 object could still be constructed since by default, all objects have a no argument constructor such as this:
public Student1() { }
If we change lines 3-6 to be a constructor instead of a method named "Student", it will make line 14 syntactically incorrect
if your intent was to call the constructor
since you do not call constructors with dot-notation. As Jason indicates, you need to use the keyword new.
If you then wanted to call a method on the object, you use the dot-notation on any methods you have defined. Since having a method named Student inside the class Student1 which is used in the Class Student is rather confusing, let�s instead add a method named sayHello to the Student1 class so you can see how to call a method. So if we take all the above along with Jason�s comments, we would have this:
class Student1 { public Student1() { System.out.println("Call to constructor complete."); } public void sayHello() { System.out.println("sayHello method called"); } } public class Student { public static void main(String[] args) { Student1 stu[] = new Student1[5]; stu[1] = new Student1(); stu[1].sayHello(); } }
This should run and give you the output:
Call to constructor complete.
sayHello method called
As you continue to read about Array�s, you should learn how to iterate through the entire array and place an object in each position.
Hope that helps
Joe Lank
Greenhorn
Joined: Jun 08, 2004
Posts: 9
posted
Jun 08, 2004 16:18:00
0
Wow! I can't thank you both enough! And thanks for clearing up about methods and constructors.
Did you see how Paul
cut 87% off of his electric heat bill with 82 watts of micro heaters
?
subject: Setting up an array of objects
Similar Threads
Two Dimentional Array
Compile error
Sorting Keys(Value Objects) in HashMap
new elements in the arraylist
how to display data from database on jsp using struts2
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/396605/java/java/Setting-array-objects | CC-MAIN-2013-48 | refinedweb | 779 | 60.04 |
ttyname()
Get a fully qualified pathname for a file
Synopsis:
#include <unistd.h> char *ttyname( int fildes );
Arguments:
- fildes
- A file descriptor that's associated with the file whose name you want to get.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The ttyname() function returns a pointer to a static buffer that contains a fully qualified pathname associated with the file associated with fildes.
Returns:
A pointer to the pathname for fildes, or NULL if an error occurred (errno is set).() function isn't implemented for the filesystem specified by filedes.
- ENOTTY
- The fildes argument doesn't refer to a tty.
- EPERM
- The process doesn't have sufficient permission to carry out the requested command.
Examples:
/* * The following program prints out the name * of the terminal associated with stdin. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main( void ) { if( isatty( 0 ) ) { printf( "%s\n", ttyname( 0 ) ); } else { printf( "\n" ); } return EXIT_SUCCESS; } | https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/t/ttyname.html | CC-MAIN-2020-34 | refinedweb | 168 | 59.09 |
Previously we discussed control structures in our scripting languages and we have touched on chunking up your code into procedures/functions/subroutines. Today we're going to take that a little further and discuss the ways in which our chosen languages group up those pieces of code into what is commonly referred to as a 'module'.
Conveniently, Python, Lua, and Perl all refer to collections of reusable code as modules so we don't need to learn a whole bunch of different words for the same concept today. However each language has different syntax (shocking, I know) for both: the creation of, and use of, modules.
Perl modules
Perl uses the Paamayim Nekudotayim to separate the scope of modules, so
the Perl module which provides access to a useful piece of code designed to
dump out data structures is called
Data::Dumper. To use that in your own
Perl code, you might do:
use Data::Dumper;
Perl is, as you might expect if you've gotten this far in our discussion of scripting languages, a little odd when it comes to building your own modules. Fortunately the Perl community is pretty awesome and they have written a very good simple module tutorial.
Python modules
Python uses the
. to separate the scope of modules, so the Python module
which provides you access to the system's path-related functions is called
sys.path. To use that in your own Python code, you might do:
import sys.path
Python's module syntax is slightly less complex than Perl's: namely you just
have a .py file and it's implicitly usable as a module straight off. Python
extends this slightly by allowing for a special file called
__init__.py which
acts as the content of a module whose name is actually a directory. This
allows you to group modules into what Python refers to as a package. You can
learn more about this
here.
Lua modules
Lua uses
. as Python does. However Lua doesn't come with many modules by
default, but if you happen to have it installed, then the Lua module containing
code representing a multimap in the
Penlight library of code is called
pl.multimap and you would use it
as follows:
local mm = require "pl.multimap"
Lua's module syntax is mid-way between Python's and Perl's. Unlike Python, you must explicitly return your module's contents, however unlike Perl you do not have to include a lot of other stuff in order to make it work. There's a reasonable Lua module tutorial available to help you with this.
Challenge
Your homework for this time, is to take some time to investigate what modules are available on your computer for the various languages you are playing along with, and see what they have to offer you. If you're feeling 'advanced' then you should proceed to write your own code module, perhaps containing some of the software you've written thanks to your experimentation in the previous installments of this series. | https://yakking.branchable.com/posts/scripting-modules/ | CC-MAIN-2020-40 | refinedweb | 506 | 60.45 |
PHP Cookbook/Variables - Revision history 2014-04-16T23:28:18Z Revision history for this page on the wiki MediaWiki 1.11.0 Docbook2Wiki: Initial conversion from Docbook 2008-03-07T13:36:04:36, 7 March 2008</td> </tr> </table> Docbook2Wiki Evanlenz: 1 revision(s) 2008-03-06T22:30:01Z <p>1 revision />.<br /> <br /> A variable is either set or unset. A variable with any value assigned to it, <tt>true</tt> or <tt>false</tt>, empty or nonempty, is set. The function <tt>isset( )</tt> returns <tt>true</tt> when passed a variable that's set. The only way to turn a variable that's set into one that's unset is to call <tt>unset( )</tt> on the variable. Scalars, arrays, and objects can all be passed to <tt>unset( )</tt>. You can also pass <tt>unset( )</tt> multiple variables to unset them all:<br /> <br /> unset($vegetables);<br /> unset($vegetables[12]);<br /> unset($earth, $moon, $stars);<br /> <br /> If a variable is present in the query string of a URL, even if it has no value assigned to it, it is set. Thus:<br /> <br /> <nowiki></nowiki><br /> <br /> sets <tt>$_GET['monkeys']</tt> to <tt>12</tt> and <tt>$_GET['chimps']</tt> to the empty string.<br /> <br /> All unset variables are also empty. Set variables may be empty or nonempty. Empty variables have values that evaluate to <tt>false</tt> as a boolean: the integer 0, the double 0.0, the empty string, the string "0", the boolean <tt>false</tt>, an array with no elements, an object with no variables or methods, and <tt>NULL</tt>. Everything else is nonempty. This includes the string "00", and the string " ", containing just a space character.<br /> <br /> Variables evaluate to either <tt>true</tt> or <tt>false</tt>. The values listed earlier that evaluate to <tt>false</tt> as a boolean are the complete set of what's <tt>false</tt> in PHP. Every other value is <tt>true</tt>. The distinction between empty and false is that emptiness is only possible for variables. Constants and return values from functions can be <tt>false</tt>, but they can't be empty. For example, the following is valid because <tt>$first_name</tt> is a variable:<br /> <br /> if (empty($first_name)) { .. }<br /> <br /> On the other hand, these two examples return parse errors because <tt>0</tt> (a constant) and the return value from <tt>get_first_name( )</tt> can't be empty:<br /> <br /> if (empty(0)) { .. }<br /> if (empty(get_first_name())) { .. }<br /> <br /> == Avoiding == Versus = Confusion ==<br /> <br /> === Problem ===<br /> <br /> You don't want to accidentally assign values when comparing a variable and a constant.<br /> <br /> === Solution ===<br /> <br /> Use:<br /> <br /> if (12 == $dwarves) { ... }<br /> <br /> instead of:<br /> <br /> if ($dwarves == 12) { ... }<br /> <br /> Putting the constant on the left triggers a parse error with the assignment operator. In other words, PHP complains when you write:<br /> <br /> if (12 = $dwarves) { ... }<br /> <br /> but:<br /> <br /> if ($dwarves = 12) { ... }<br /> <br /> silently executes, assigning <tt>12</tt> to the variable <tt>$dwarves</tt>, and then executing the code inside the block. (<tt>$dwarves = 12</tt> evaluates to <tt>12</tt>, which is <tt>true</tt>.)<br /> <br /> === Discussion ===<br /> <br /> Putting a constant on the left side of a comparison coerces the comparison to the type of the constant. This causes problems when you are comparing an integer with a variable that could be an integer or a string. <tt>0 == $dwarves</tt> is <tt>true</tt> when <tt>$dwarves</tt> is <tt>0</tt>, but it's also true when <tt>$dwarves</tt> is <tt>sleepy</tt>. Since an integer (<tt>0</tt>) is on the left side of the comparison, PHP converts what's on the right (the string <tt>sleepy</tt>) to an integer (<tt>0</tt>) before comparing. To avoid this, use the identity operator, <tt>0 === $dwarves</tt>, instead.<br /> <br /> === See Also ===<br /> <br /> Documentation for <tt>=</tt> at '''' and for <tt>==</tt> and <tt>===</tt> at ''''.<br /> <br /> == Establishing a Default Value ==<br /> <br /> === Problem ===<br /> <br /> You want to assign a default value to a variable that doesn't already have a value. It often happens that you want a hardcoded default value for a variable that can be overridden from form input or through an environment variable.<br /> <br /> === Solution ===<br /> <br /> Use <tt>isset( )</tt> to assign a default to a variable that may already have a value:<br /> <br /> if (! isset($cars)) { $cars = $default_cars; }<br /> <br /> Use the ternary (<tt>a ? b : c</tt>) operator to give a new variable a (possibly default) value:<br /> <br /> $cars = isset($_REQUEST['cars']) ? $_REQUEST['cars'] : $default_cars;<br /> <br /> === Discussion ===<br /> <br /> Using <tt>isset( )</tt> is essential when assigning default values. Without it, the nondefault value can't be <tt>0</tt> or anything else that evaluates to <tt>false</tt>. Consider this assignment:<br /> <br /> $cars = $_REQUEST['cars'] ? $_REQUEST['cars'] : $default_cars;<br /> <br /> If <tt>$_REQUEST['cars']</tt> is <tt>0</tt>, <tt>$cars</tt> is set to <tt>$default_cars</tt> even though <tt>0</tt> may be a valid value for <tt>$cars</tt>.<br /> <br /> You can use an array of defaults to set multiple default values easily. The keys in the defaults array are variable names, and the values in the array are the defaults for each variable:<br /> <br /> $defaults = array('emperors' => array('Rudolf II','Caligula'),<br /> 'vegetable' => 'celery',<br /> 'acres' => 15);<br /> <br /> foreach ($defaults as $k => $v) {<br /> if (! isset($GLOBALS[$k])) { $GLOBALS[$k] = $v; }<br /> }<br /> <br /> Because the variables are set in the global namespace, the previous code doesn't work for setting function-private defaults. To do that, use variable variables:<br /> <br /> foreach ($defaults as $k => $v) {<br /> if (! isset($$k)) { $$k = $v; }<br /> }<br /> <br /> === See Also ===<br /> <br /> Documentation on <tt>isset( )</tt> at ''''; variable variables are discussed in [[PHP Cookbook/Variables#Creating a Dynamic Variable Name|Recipe 5.5]] and at ''''.<br /> <br /> == Exchanging Values Without Using Temporary Variables ==<br /> <br /> === Problem ===<br /> <br /> You want to exchange the values in two variables without using additional variables for storage.<br /> <br /> === Solution ===<br /> <br /> To swap <tt>$a</tt> and <tt>$b</tt>:<br /> <br /> list($a,$b) = array($b,$a);<br /> <br /> === Discussion ===<br /> <br /> PHP's <tt>list( )</tt> language construct lets you assign values from an array to individual variables. Its counterpart on the right side of the expression, <tt>array( )</tt> , lets you construct arrays from individual values. Assigning the array that <tt>array( )</tt> returns to the variables in the <tt>list( )</tt> lets you juggle the order of those values. This works with more than two values, as well:<br /> <br /> list($yesterday,$today,$tomorrow) = array($today,$tomorrow,$yesterday);<br /> <br /> This method isn't faster than using temporary variables, so you should use it for clarity, but not speed.<br /> <br /> === See Also ===<br /> <br /> Documentation on <tt>list( )</tt> at '''' and <tt>array( )</tt> at ''''.<br /> <br /> == Creating a Dynamic Variable Name ==<br /> <br /> === Problem ===<br /> <br /> You want to construct a variable's name dynamically. For example, you want to use variable names that match the field names from a database query.<br /> <br /> === Solution ===<br /> <br /> Use PHP's variable variable syntax by prepending a <tt>$</tt> to a variable whose value is the variable name you want:<br /> <br /> $animal = 'turtles';<br /> $turtles = 103;<br /> print $$animal;<br /> '''103'''<br /> <br /> <br /> === Discussion ===<br /> <br /> The previous example prints <tt>103</tt>. Because <tt>$animal</tt> <tt>=</tt> <tt>'turtles',</tt> <tt>$$animal</tt> is <tt>$turtles</tt>, which equals 103.<br /> <br /> Using curly braces, you can construct more complicated expressions that indicate variable names:<br /> <br /> $stooges = array('Moe','Larry','Curly');<br /> $stooge_moe = 'Moses Horwitz';<br /> $stooge_larry = 'Louis Feinberg';<br /> $stooge_curly = 'Jerome Horwitz';<br /> <br /> foreach ($stooges as $s) {<br /> print "$s's real name was ${'stooge_'.strtolower($s)}.\n";<br /> }<br /> '''Moe's real name was Moses Horwitz.'''<br /> '''Larry's real name was Louis Feinberg.'''<br /> '''Curly's real name was Jerome Horwitz.'''<br /> <br /> <br /> PHP evaluates the expression between the curly braces and uses it as a variable name. That expression can even have function calls in it, such as <tt>strtolower( )</tt>.<br /> <br /> Variable variables are also useful when iterating through similarly named variables. Say you are querying a database table that has fields named <tt>title_1</tt>, <tt>title_2</tt>, etc. If you want to check if a title matches any of those values, the easiest way is to loop through them like this:<br /> <br /> for ($i = 1; $i <= $n; $i++) {<br /> $<br /> '''Example 5-1. pc_check_the_count( )'''<br /> <br /> function pc_check_the_count($pitch) {<br /> static $strikes = 0;<br /> static $balls = 0;<br /> <br /> switch ($pitch) {<br /> case 'foul':<br /> if (2 == $strikes) break; // nothing happens if 2 strikes<br /> // otherwise, act like a strike<br /> case 'strike':<br /> $strikes++;<br /> break;<br /> case 'ball':<br /> $balls++;<br /> break;<br /> }<br /> <br /> if (3 == $strikes) {<br /> $strikes = $balls = 0;<br /> return 'strike out';<br /> }<br /> if (4 == $balls) {<br /> $strikes = $balls = 0;<br /> return 'walk';<br /> }<br /> return 'at bat';<br /> }<br /> <br /> $what_happened = check_the_count($pitch);<br /> </div><br /> <br /> In <tt>pc_check_the_count( )</tt>, the logic of what happens to the batter depending on the pitch count is in the <tt>switch</tt> statement inside the function. You can instead return the number of strikes and balls, but this requires you to place the checks for striking out, walking, and staying at the plate in multiple places in the code.<br /> <br /> While <tt>static</tt> variables retain their values between function calls, they do so only during one invocation of a script. A <tt>static</tt> variable accessed in one request doesn't keep its value for the next request to the same page.<br /> <br /> === See Also ===<br /> <br /> Documentation on <tt>static</tt> variables at ''''.<br /> <br /> == Sharing Variables Between Processes ==<br /> <br /> === Problem ===<br /> <br /> You want a way to share information between processes that provides fast access to the shared data.<br /> <br /> === Solution ===<br /> <br /> Store the data in a shared memory segment, and guarantee exclusive access to the shared memory with a semaphore:<br /> <br /> $semaphore_id = 100;<br /> $segment_id = 200;<br /> // get a handle to the semaphore associated with the shared memory<br /> // segment we want<br /> $sem = sem_get($semaphore_id,1,0600);<br /> // ensure exclusive access to the semaphore<br /> sem_acquire($sem) or die("Can't acquire semaphore");<br /> // get a handle to our shared memory segment<br /> $shm = shm_attach($segment_id,16384,0600);<br /> // retrieve a value from the shared memory segment<br /> $population = shm_get_var($shm,'population');<br /> // manipulate the value<br /> $population += ($births + $immigrants - $deaths - $emigrants);<br /> // store the value back in the shared memory segment<br /> shm_put_var($shm,'population',$population);<br /> // release the handle to the shared memory segment<br /> shm_detach($shm);<br /> // release the semaphore so other processes can acquire it<br /> sem_release($sem);<br /> <br /> === Discussion ===<br /> <br />.<br /> <br /> To get control of a semaphore, use <tt>sem_get( )</tt> to find the semaphore's ID. The first argument to <tt>sem_get( )</tt> <tt>sem_get( )</tt> (in this case, <tt>1</tt>), and the semaphore's permissions are set to <tt>sem_get( )</tt>'s third argument (<tt>0600</tt>). These permissions work just like file permissions, so <tt>0600</tt> means that the user that created the semaphore can read it and write to it. In this context, user doesn't just mean the process that created the semaphore but any process with the same user ID. Permissions of <tt>0600</tt> should be appropriate for most uses, in which web server processes run as the same user.<br /> <br /> <tt>sem_get( )</tt> returns an identifier that points to the underlying system semaphore. Use this ID to gain control of the semaphore with <tt>sem_acquire( )</tt> . This function waits until the semaphore can be acquired (perhaps waiting until other processes release the semaphore) and then returns <tt>true</tt>. It returns <tt>false</tt> on error. Errors include invalid permissions or not enough memory to create the semaphore. Once the semaphore is acquired, you can read from the shared memory segment.<br /> <br /> First, establish a link to the particular shared memory segment with <tt>shm_attach( )</tt> . As with <tt>sem_get( )</tt>, the first argument to <tt>shm_attach( )</tt> is an integer key. This time, however it identifies the desired segment, not the semaphore. If the segment with the specified key doesn't exist, the other arguments create it. The second argument (<tt>16384</tt>) is the size in bytes of the segment, and the last argument (<tt>0600</tt>) are the permissions on the segment. <tt>shm_attach(200,16384,0600)</tt> creates a 16K shared memory segment that can be read from and written to only by the user who created it. The function returns the identifier you need to read from and write to the shared memory segment.<br /> <br /> After attaching to the segment, pull variables out of it with <tt>shm_get_var($shm, 'population')</tt> . This looks in the shared memory segment identified by <tt>$shm</tt> and retrieves the value of the variable called <tt>population</tt>. You can store any type of variable in shared memory. Once the variable is retrieved, it can be operated on like other variables. <tt>shm_put_var($shm,'population',$population)</tt> puts the value of <tt>$population</tt> back into the shared memory segment as a variable called <tt>population</tt>.<br /> <br /> You're now done with the shared memory statement. Detach from it with <tt>shm_detach( )</tt> and release the semaphore with <tt>sem_release( )</tt> so another process can use it.<br /> <br />.<br /> <br /> === See Also ===<br /> <br /> [[PHP Cookbook/Web Basics#Program: Abusive User Checker|Recipe 8.28]] includes a program that uses shared memory; documentation on shared memory and semaphore functions at ''''.<br /> <br /> == Encapsulating Complex Data Types as a String ==<br /> <br /> === Problem ===<br /> <br /> You want a string representation of an array or object for storage in a file or database. This string should be easily reconstitutable into the original array or object.<br /> <br /> === Solution ===<br /> <br /> Use <tt>serialize( )</tt> to encode variables and their values into a textual form:<br /> <br /> $pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');<br /> $fp = fopen('/tmp/pantry','w') or die ("Can't open pantry");<br /> fputs($fp,serialize($pantry));<br /> fclose($fp);<br /> <br /> To recreate the variables, use <tt>unserialize( )</tt> :<br /> <br /> <nowiki>$new_pantry = unserialize(join('',file('/tmp/pantry')));</nowiki><br /> <br /> === Discussion ===<br /> <br /> The serialized string that is reconstituted into <tt>$pantry</tt> looks like:<br /> <br /> a:2:{s:5:"sugar";s:6:"2 lbs.";s:6:"butter";s:8:"3 sticks";}<br /> <br /> This stores enough information to bring back all the values in the array, but the variable name itself isn't stored in the serialized representation.<br /> <br /> When passing serialized data from page to page in a URL, call <tt>urlencode( )</tt> on the data to make sure URL metacharacters are escaped in it:<br /> <br /> $shopping_cart = array('Poppy Seed Bagel' => 2,<br /> 'Plain Bagel' => 1,<br /> 'Lox' => 4);<br /> print '<a href="next.php?cart='.urlencode(serialize($shopping_cart)).'">Next</a>';<br /> <br /> The <tt>magic_quotes_gpc</tt> and <tt>magic_quotes_runtime</tt> configuration settings affect data being passed to <tt>unserialize( )</tt>. If <tt>magic_quotes_gpc</tt> is <tt>on</tt>, data passed in URLs, POST variables, or cookies must be processed with <tt>stripslashes( )</tt> before it's unserialized:<br /> <br /> $new_cart = unserialize(stripslashes($cart)); // if magic_quotes_gpc is on<br /> $new_cart = unserialize($cart); // if magic_quotes_gpc is off<br /> <br /> If <tt>magic_quotes_runtime</tt> is <tt>on</tt>, serialized data stored in a file must be processed with <tt>addslashes( )</tt> when writing and <tt>stripslashes()</tt> when reading:<br /> <br /> <nowiki>$fp = fopen('/tmp/cart,'w');<br /> fputs($fp,addslashes(serialize($a)));<br /> fclose($fp);<br /> <br /> // if magic_quotes_runtime is on<br /> $new_cart = unserialize(stripslashes(join('',file('/tmp/cart'))));<br /> // if magic_quotes_runtime is off<br /> $new_cart = unserialize(join('',file('/tmp/cart')));</nowiki><br /> <br /> Serialized data read from a database must also be processed with <tt>stripslashes( )</tt> when <tt>magic_quotes_runtime</tt> is <tt>on</tt>:<br /> <br /> mysql_query(<br /> "INSERT INTO cart (id,data) VALUES (1,'".addslashes(serialize($cart))."')");<br /> <br /> $r = mysql_query('SELECT data FROM cart WHERE id = 1');<br /> $ob = mysql_fetch_object($r);<br /> // if magic_quotes_runtime is on<br /> $new_cart = unserialize(stripslashes($ob->data));<br /> // if magic_quotes_runtime is off<br /> $new_cart = unserialize($ob->data);<br /> <br /> Serialized data going into a database always needs to have <tt>addslashes( )</tt> called on it (or another database-appropriate escaping method) to ensure it's saved properly.<br /> <br /> === See Also ===<br /> <br /> [[PHP Cookbook/Database Access#Repeating Queries Efficiently|Recipe 10.8]] for information on escaping data for a database.<br /> <br /> == Dumping Variable Contents as Strings ==<br /> <br /> === Problem ===<br /> <br /> You want to inspect the values stored in a variable. It may be a complicated nested array or object, so you can't just print it out or loop through it.<br /> <br /> === Solution ===<br /> <br /> Use <tt>print_r( )</tt> or <tt>var_dump( )</tt>:<br /> <br /> $array = array("name" => "frank", 12, array(3, 4));<br /> <br /> print_r($array);<br /> '''Array'''<br /> '''('''<br /> ''' [name] => frank'''<br /> ''' [0] => 12'''<br /> ''' [1] => Array'''<br /> ''' ('''<br /> ''' [0] => 3'''<br /> ''' [1] => 4'''<br /> ''' )'''<br /> ''')'''<br /> var_dump($array);<br /> '''array(3) {'''<br /> ''' ["name"]=>'''<br /> ''' string(5) "frank"'''<br /> ''' [0]=>'''<br /> ''' int(12)'''<br /> ''' [1]=>'''<br /> ''' array(2) {'''<br /> ''' [0]=>'''<br /> ''' int(3)'''<br /> ''' [1]=>'''<br /> ''' int(4)'''<br /> ''' }'''<br /> '''}'''<br /> <br /> <br /> === Discussion ===<br /> <br /> The output of <tt>print_r( )</tt> is more concise and easier to read. The output of <tt>var_dump( )</tt>, however, gives data types and lengths for each variable.<br /> <br /> Since these functions recursively work their way through variables, if you have references within a variable pointing back to the variable itself, you can end up with an infinite loop. Both functions stop themselves from printing variable information forever, though. Once <tt>print_r( )</tt> has seen a variable once, it prints <tt>*RECURSION*</tt> instead of printing information about the variable again and continues iterating through the rest of the information it has to print. When <tt>var_dump( )</tt> sees a variable more than three times, it throws a fatal error and ends script execution. Consider the arrays <tt>$user_1</tt> and <tt>$user_2</tt>, which reference each other through their <tt>friend</tt> elements:<br /> <br /> $user_1 = array('name' => 'Max Bialystock',<br /> 'username' => 'max');<br /> <br /> $user_2 = array('name' => 'Leo Bloom',<br /> 'username' => 'leo');<br /> <br /> // Max and Leo are friends<br /> $user_2['friend'] = &$user_1;<br /> $user_1['friend'] = &$user_2;<br /> <br /> // Max and Leo have jobs<br /> $user_1['job'] = 'Swindler';<br /> $user_2['job'] = 'Accountant';<br /> <br /> The output of <tt>print_r($user_2)</tt> is:<br /> <br /> Array<br /> (<br /> [name] => Leo Bloom<br /> [username] => leo<br /> [friend] => Array<br /> (<br /> [name] => Max Bialystock<br /> [username] => max<br /> [friend] => Array<br /> (<br /> [name] => Leo Bloom<br /> [username] => leo<br /> [friend] => Array<br /> *RECURSION*<br /> [job] => Accountant<br /> )<br /> <br /> [job] => Swindler<br /> )<br /> <br /> [job] => Accountant<br /> )<br /> <br /> When <tt>print_r( )</tt> sees the reference to <tt>$user_1</tt> the second time, it prints <tt>*RECURSION*</tt> instead of descending into the array. It then continues on its way, printing the remaining elements of <tt>$user_1</tt> and <tt>$user_2</tt>.<br /> <br /> Confronted with recursion, <tt>var_dump( )</tt> behaves differently:<br /> /> <br /><br /> <b>Fatal error</b>: Nesting level too deep - recursive dependency? in <br /> <b>var-dump.php</b> on line <b>15</b><br /><br /> <br /> It's not until the fourth appearance of the reference to <tt>$user_1</tt> that <tt>var_dump( )</tt> stops recursing. When it does, it throws a fatal error, and no more variable dumping (or script execution) occurs.<br /> <br /> Even though <tt>print_r( )</tt> and <tt>var_dump( )</tt> print their results instead of returning them, you can capture the data without printing it using output buffering:<br /> <br /> ob_start();<br /> var_dump($user);<br /> $dump = ob_get_contents();<br /> ob_end_clean();<br /> <br /> This puts the results of <tt>var_dump($user)</tt> in <tt>$dump</tt>.<br /> <br /> === See Also ===<br /> <br /> Output buffering is discussed in [[PHP Cookbook/Web Basics#Buffering Output to the Browser|Recipe 8.13]]; error handling with PEAR's DB module, shown in [[PHP Cookbook/Database Access#Finding the Number of Rows Returned by a Query|Recipe 10.9]], uses output buffering with <tt>print_r( )</tt> to save error messages; documentation on <tt>print_r( )</tt> at '''' and <tt>var_dump( )</tt> at '''' .</div> Docbook2Wiki | http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Variables&action=history&feed=atom | CC-MAIN-2014-15 | refinedweb | 3,484 | 50.16 |
Ask Guido van Rossum 202
This week's interview is with Guido van Rossum, a man who, as they say, needs no introduction. (Not around here, at least.) To learn a bit more about him, check his personal page. You might want to ask him about Python 2.1, which was released today. One question per person, please. We'll send 10 of the highest-moderated ones to Guido about 24 hours after this post went up, and will run his answers as soon as he gets them back to us.
Re:Language Specification (Score:1)
Please mod this down. It's a fair question, but it's kind of uninformed. It certainly doesn't pertain specifically to Python.
(First of all, Python doesn't have ++ and -- operators.)
Even C goes through revisions. Some C programs that work on more recent C compilers won't work under older ones.
Any language newer than C is likely to have this problem, because computing (let's face it) is exploding. The number of standard libraries people want is always increasing. Java definitely has this problem. Just one call to a v1.3 API prevents your program from running in a v1.2 JRE. Likewise, Perl has new language features and libraries with each release. And so on.
Either you accept change, and you get all the benefits of progress; or you standardize on one Final version, and you get the benefit of language stability. Most people prefer for Python (and Perl; and Java; etc.) to keep improving. Go figure.
For your Debian box at home, I recommend upgrading to (at least) Python 2.0.
-- jason
Favourite Python sketch? (Score:5)
Alex Bischoff
---
Re:Python 3000 (Score:2)
Of course, there's also JPython, which has fantastic integration between Java and Python code, and resolves the threading thing... so if yer extending Java code, it's really a no-brainer (IMHO).
Re:Performance (Score:2)
There has been efforts, most notably the (currently inactive, I believe) static typing SIG [python.org], which would make it possible to make code that could be efficiently translated to machine code (also known as "compiling"). Static typing is by no means required to translate to machine code, but it would probably make that faster.
An interesting option might be something like Squeak [squeak.org] did, with a subset of the language that can be efficiently translated into C (and then compiled). This is something like what the static type SIG was aproaching -- not quite Python, but something that could run in the conventional CPython interpreter, wouldn't necessarily require any knowledge of C or assembly, but could run fast.
Of course, it is also possible to simply compile Python into system code just as it is (well, if someone wrote the compiler). There is nothing that makes Python inherently interpreted. The problem, however, would be in the efficiency of that code. A naive attempt to do this would probably be slower than CPython. OTOH, compilers for Scheme (which have many similar issues as Python) have produced very fast code (on par with C). In particular, Stalin is very fast (though there are others which are very fast as well) -- sometimes faster than C. Python doesn't have any of the huge flaws that languages like, say, Tcl have in this regard. Some operations are difficult in compiled environments -- like getattr or eval -- but they could still be possible, or they could be left out (since much code doesn't use them). OTOH, all the best Python code uses them.
Re:does Python need a CPAN? (Score:2)
distutils fulfills some of the functionality required for a Python CPAN. I think it has reached a state of relative maturity -- it may be asked to do more later, but it does what it needs to well right now.
There has also been some discussion and implementation of methods to describe and upload modules, which would probably be included in distutils or something related when they mature. I think at that point, along with a little infrastructure on the web, Python will have its own little CPAN. I know CPAN does more than this, but not all that much more, and it's something that should be grown into.
I couldn't find what I was really looking for on the subject, but maybe this thread [google.com] would be a starting place. There's more stuff elsewhere as well. This message [google.com] (from that thread) gives a nice overview of what's necessary for CPAN, I think. And I guess the whole discussion starts here [google.com].
Do you believe in Object Oriented Programming? (Score:2)
Almost every modern high-level application language today supports, and perhaps forces the Object Oriented Paradigm (OOP). Students are encouraged to define and use objects whenever possible. Python's standard library seems nothing but objects. Java is the same. Newer technologies, like SOAP/Microsoft
.Net/blahh are the apex of this concept.
When I refer to the OOP, I mean the drive to decompose all programming into components, not necessarily the individual concept of having classes with methods and constructors and context-sensitive results, etc
Application developers accept the OOP as the only way and consider those who refuse it to be uncivilized coder barbarians. Clearly, one can only bring sanity to programming via the OOP. But what is it really bringing?
Most of the ideas that the OOP promotes are good programming practice anyway. That is absolutely not what I hate about the OOP.
In the very ideal cases, you can create a reusable object/module that other people can enjoy. This is very rare, though. UNIX is a good example of an easy to use interface that allows for massive code reuse. The Win32 API, while affording code reuse, has a miserable interface that makes Windows programming a chore.
Without going into a huge tirade; Modularity on that level is good. It's worth it to struggle with the interface, because the alternative is 100 man-years worth of functionality that you need to implement. On a much reduced level, trying to deal with the OOP just doesn't seem worth it.
The problem with the OOP is that it encourages all code to be tiny little modules with it's own unique domain, which helps complicate the code both visually and in terms of execution.
For every beautifully designed reusable component, you have a thousand more that are confined to a single project and do nothing but add complexity and visual noise to an otherwise simple idea.
The Objects Everywhere philosophy seems to promote complexity, rather than simplicity. The less code, the easier it is to understand, the better off it'll be. Python does achieve many of these goals, but I can't understand why the push to OO'ize it all.
Bad programmers can write bad code no matter what, and there's a vast army of bad programmers out there, but I'm not sure I've ever seen good code that employs the Objects Everywhere ideal.
Does this make sense? What are your thoughts?
He didn't. (Score:1)
Python is my favorite language, btw.
Re:Performance (Score:1)
Actually neither type inference or static typing is required for a compiled implementation of a language. Common Lisp requires neither, though you can declare type information for greater efficiency. Instead of variables having an intrinsic static type, values have a type, and variables can refer to any kind of value. Typically the type of the value is encoded in the reference to it. So you might use the top three bits of a word to encode the type and the lower 29 to be a pointer to the value. Explicit declared typing information does help the compiler though- you can sometimes double the performance of a compiled Common Lisp program by using type declarations.
Re:Indentation? (Score:2)
That's really the beautty of Python's whitespace blocks. Both the programmer and the parser are looking at the same cues for block nesting. I am sure you have debugged C code that was missing a brace (or worse that had one misplaced) but was still indented "correctly." Your mind thinks that everything is hunky dory because the code "looks" right. This doesn't happen very often if you are a skilled C coder (with an intelligent text editor), but it does happen. And it happens a lot with newbie programmers. I was teaching my little brother Perl at one point, and he had all sorts of trouble with braces. However, when we switched to Python there was no longer any need for him to think about which braces matched up. I didn't believe that Python's significant whitespace was a good idea either, at first, but I am a believer now.
I am not a vi user, so I can't help you there.
Incompability w/ GNU GPL: Any chance to resolve it (Score:1)
Python has licence, that is incompatible
with GNU GPL. I know that RMS himself has tried to
negotiate to rectify that problem. But what is
current situtation? Do you see any chance to resolve the problem? How likely is it, that the
problem will be resolved?
garbage collection and Python (Score:1)
I am a long time Python developer and fanatic. I have long enjoyed using python because of its Object Oriented nature and its faster and more open development process than its main competitors.
While I believe Python is a great language, there is one thing that I really am missing from Python. Currently, Python uses a very antiquated reference counting method that is less than ideal. Are there any plans to re-implement the garbage collection mechanism for Python in the future? May I suggest using the more advanced generational methods of garbage collection?
Good work so far, and thanks for all you have done!
Jonathan LaCour
Developer, Student
standard packages and organization (Score:1)
Guido,
Python is great, and I use it all the time, but I have an annoyance that I would love to see corrected.
Currently, Python's standard modules provide much functionality, but are a mish-mash of submitted modules that are largely uncategorized. Java provides a much better organization and naming scheme that could be carried over to Python.
For example, when importing the Python HTTP modules (httplib), currently, I do one of the following:
import httplib
from httplib import *
Java has a categorization structure imposed to make things a bit clearer. I would prefer if this same kind of structure was imposed in python. So, the above would then become something like one of the following:
import python.net.http
from python.net.http import *
I think that this could really enforce a cleaner organization and make it easier to identify where modules belong, and what they do, just by looking at their organizational location.
What do you think? =)
Jonathan LaCour
Developer, Student
Other languages (Score:2)
TheNewWazoo
Python directions (Score:1)
Thanks for a great language.
Re:Data Structures Library (Score:2)
Re:Garbage Collection (Score:2)
Stackless Python? (Score:4)
Re:Komodo (Score:2)
Chris Cothrun
Curator of Chaos
Re:Indentation? (Score:1)
Re:Ruby (Score:1)
I've already downloaded the source and compiled it on Cygwin. Flawless and easy install.
Re:Ruby (Score:1)
It wasn't from your particular link, however, but I thank you for your gracious help.
Ruby (Score:5)
Getting your company to use Python vs. ... (Score:1)
What are the five most compelling arguments that _you'd_ offer to a company doing web development, system administration, etc... to use Python over other interpreted languages such as Perl, TCL, etc...
Thanks!
Emacs, Python, and Tabs (Score:1)
Nah. Not if you have emacs configured correctly. Unfortunately I'm in Windows right now (long story) so I can't refer to my own Emacs settings. If you have a non-ancient version of Python mode, Emacs actually handles the Python whitespace rather well.
And make sure when you move a block horizontally you make the block the emacs region then hit (I think) Ctrl-C then < or >. It's also on the Python mode menu.
One good tip for maintaining sanity in a professional Python dev shop is to have EVERYONE USE TABS, always, all the time. One tab character == 1 Python indentation level. Then each person can set their tabs to 4 or 8 or whatever space for visual display, and everyones happy. Just make sure peoples editors are set to keep those as tabs and not convert back to spaces. If you set up Emacs properly (very easy) then this becomes a no-brainer. Hitting Tab on a line should (almost always) produce the right indentatin for a given context.
Mixing up 4-spaces-as-indentation and tabs in a single file is a recipie for disaster (subtle bugs.) Aside from these issues, I actually like Pythons use of whitespace. I find it easier for long term maintainability not to mention the initial conceptualization / prototyping.
.emacs settings to work with Python and tabs properly.
---
Thoughts on US vs Europe? (Score:1)
I was wondering: why did you do it? How do The Netherlands (or Europe for that matter) and the US compare? Don't you miss the good bakeries, cannabis and licquorice? Do you experience Americans as being shallow (I've heard that comment more than once)? Or is this just a case of "Cherchez la femme?"
That's a lot questions together, but I'm not so much interested in specific answers. I'd like to hear your general experience of US vs. Europe.
microthreads, stackless python (Score:2)
-
Why is Python not whitespace-ignorant? (Score:1)
In my opinion, one of the most awful features of Python as a language is the fact that it thinks of whitespace as a highly significant feature in programs, so much so that you always have to properly indent all blocks of code that are under a particular control structure (such as if statements or for loops), instead of having a 'begin'-'end' token pair to do the job, such as what we have in C, Perl, Java, Pascal, and almost every other block structured programming language I know about. It takes away the programmer's freedom to style his or her code, forcing them to conform to somebody's idea about how programs ought to visually look like. I've heard of "bondage and discipline" languages, but this is arch-B&D... not even Pascal is so anal!
Conflict with GPL (Score:5)
So, my question is a two parter:
ObJectBridge [sourceforge.net] (GPL'd Java ODMG) needs volunteers.
Re:Python 3000 (Score:1)
Re:Python 3000 (Score:1)
JPython rocks. Working with JPython in Java rocks. When, oh when, will the C implementation of Python compare favorably to the Java version?
None of you who have worked with both C and Java Python can tell me that there is any comparison at the API level. JPython rocks all over CPython in that regard.
Re:Python 3000 (Score:1)
Reading the Zope list, and searching the archives, you will see Python's poor threading support bemoaned repeatedly as a roadblock to scaling a single Zope process on multi-processor systems.
Python 3000 (Score:5)
Why do you care so much for GPL compatibility? (Score:1)
The Apache people seem to have given up on ever getting their license compatible with the GPL since it seems to much work to get the language about the trademarked words right. So they just accept that people writing GPLed software can never use code distributed under the Apache license. It does not seem to hurt the Apache project to much.
Why do you care so much about Python being GPL compatible? And what work should still be done?
I loved the original CWI license by the way, it was short and to the point. Is there any way to get that back as standard license? And is was GPL compatible as a nice bonus.
How will nested scopes affect performance? (Score:2)
Reading "What's New in Python 2.1", I'm curious about nested scopes. Given that name lookup has always been the cause of poor performance in Python (or so I've heard), it would initially seem that introducing nested scopes would further reduce the speed at which Python scripts run if you use this feature.
Is there any information available about Python's performance with this addition?
Structured Design. (Score:5)?
Thanks.
Why such weak lambdas? (Score:1)
Oh, and many many thanks for a beautiful language.
(jfb)
Re:Jython (Score:1)
Peace,
(jfb)
Re:Python's 2 biggest shortfalls (Score:1)
Let's not forget the language that made multiple dispatch popular (for certain values of popular): Common Lisp. CLOS is still the best expression of multiple dispatch around (although Dylan sure is nifty.)
Peace,
(jfb)
Re:Language Specification (Score:1)
Re:Structured Design. (Score:2)
Well, that's the answer, i'm not sure why it isn't acceptable. One of the main stated goals with Python is that they didn't want a language that had completely different formatting depending on who wrote it, so they made formatting part of the language. This makes it much easier for non-programmers (like me) and beginning programmers to pick it up.
I find, because of my background, it is much easier to read code that uses braces
but someone with no programming backgound wouldn't have that bias, so if you're inventing a new language, why feel hindered by older syntactic conventions?
---------------------------------------------
Re:Structured Design. (Score:1)
Would you allow a junior programmer joining your team to write code like this?
I certainly wouldn't. In c (or c++, or java, or whatever language that snippet was written in), whitespace is significant, but it is significant ONLY to the human reading the code, not to the compiler.
If I could, I'd ask the compiler (or the source-code-control checkin program) to require that the indentation match the braces. That would prevent stupid stuff like the above, and also prevent the more insidious errors like this:where my failure to use {} around the for() clause has created an error (ie, new_x += v should be inside the loop, and you can TELL that from the indentation).
So in python, you get exactly this feature. The language verifies that the ACTUAL block structure of the compiled code equals the INTENDED block structure as indicated by the programmer:
In my opinion, the python code will hold up BETTER than over long life spans than c-style code, at least if you consider only the effects of whitespace-based block structure. I say this because the use of indentation to indicate block structure is older and more widespread than the use of braces for that purpose -- compare Algol, Lisp, APL, and nearly everything else except early (column-sensitive) Fortran and assembler.
Of course you ALSO said that you liked having the braces, because it makes it easier for you to read. Fortunately, braces ARE allowed in python! The following example demonstrates their use.
;-)
-- Michael Chermside
GUI? Tkinter? (Score:3)
Any movement away from Tkinter, and toward something else, as the pretty-much-standard programming interface for graphical user interfaces?
Any movement towards a Tk library that *doesn't* use Tcl?
Scare Quotes (Score:1)
Good call.
Hi, I've never heard of you (Score:1)
Re:Performance (Score:1)
Legacy vs. Ease and Cleanliness (Score:2)
I'm interested, though, in the conflict between library design and legacy habits. Would you suggest that C-isms like "popen2", "execlp", "sys.argv", and "socket(AF_INET, SOCK_STREAM)" really belong in a "clean" language in the long run?
Is there any chance that we'll someday see a standard library extension that (much like Java's libraries) allows developer to program in English rather than UNIXglish?
Thanks!
--JRZ
Ruby (Score:2)
Re:Structured Design. (Score:2)
The tool can convert back and forth to allow for use in indentation hostile environments.
Python and UML (Score:2)
I have seen a couple of Java based Unified Modeling Language [omg.org] tools but no Python support or implementation. It would seem natural to develop in python based on UML, so this must be a large gap in the python suite. What do you think of designing with UML and implementing in python?
Thorn [xaan.com] is an opensource UML editor written in Java with JPython scripting but no python code generation.
ArgoUML [tigris.org] is an opensource UML editor written in Java with no current python code generation
macro viruses (Score:2)
Blind people? (Score:2)
Re:Conflict with GPL (Score:2)
--
Re:Komodo (Score:2)
even compared to Visual Basic it really sucks... like.. REALLY sucks. I would be embarrased to ship a program built with that IDE builder.
--------------------
Would you like a Python based alternative to PHP/ASP/JSP?
Python IDE (Score:3)
--------------------
Would you like a Python based alternative to PHP/ASP/JSP?
Performance (Score:4)
Re:Structured Design. (Score:2)
I like Python's style and I like the ALGOL-derived style as well.
Re:Why is Python not whitespace-ignorant? (Score:2)
There have been a few other posts about this. See my earlier response to another post about that here [slashdot.org].
I'll answer your post with a question. Why should a programmer be free to style their code anyway they want?
The point of a programming language is to communicate instructions to a computer in human-readable format. I still maintain that people who complain about being forced to write readable code are the ones who write the most unreadable code. TMTOWDTI, Perl's motto, is the main reason that when the first Obfuscated Perl Code contest was announced, many Slashdotter's joked that it was redundant. Consistent style is a necessity for maintainability. It helps to allow others (and maybe yourself a year later) to understand what you were doing when you wrote a piece of code.
Honestly, if you think everyone should be able to write code in whatever style they see fit, you've never worked on a large project before. Languages with more freedom just force people to place other personal standards on how their code must be formatted within their project or lose readability of code as multiple programmer styles conflict. Python forces a consistent standard across all development, making it an great relief to maintain.
Re:Structured Design. (Score:5)
I fail to see why there would be any other reason. Furthermore, I fail to see why there should even need to be a better reason. Why do you have whitespace at all? There are only 2 real answers: easy parser writing and human readability.
Python's style makes it easy to see blocks of logic. It also forces you to think about how your code is organized by exposing these blocks to you at all times. Braces, parentheses, brackets, etc. are easy to lose track of in complex single-line statements. You have to spend too much time thinking about whether or not you've got your puncuation matched up properly. Python eliminates this confusion by exposing logical blocks. Besides, properly formatted and readable C code should already be spaced out like a Python program. Python just eliminates the redundant punctuation.
Typically, the people who complain the loudest about enforcing spacing in syntax are the same people who write those tangled, dense, single-line statements in C and Perl that inspired their respected obfuscated code contests. You don't need the ability to cram 5 lines of Python in 1 line of Perl. It just hurts maintainability, and there's really no compelling argument for keeping source code dense and compact anymore if it doesn't add speed and remove bloat. (Forgive me if I have unfairly tarred you with this brush, but this has been my general experience.)
(In response to another post:)
Also, I've never seen a source-control system mess with the spacing of a file before. That's just odd. Be consistent with using either spaces OR tabs and your Python code will be much easier to store. I'm not saying it doesn't happen. I'm just saying that bugs in certain tools that weren't written with Python in mind shouldn't be a black mark against the whole language.
Implementing Everything in Python (Score:2)
One thing I see in Python-land is that there is a tendency to implement everything in Python. I just submitted a design for a program that I want to write in Python and I used Sketch for diagrams, despite having CorelDraw for Linux right here. It seems that no Python programmer is happy with having a component written in another language. Many other languages don't interoperate as well as in Python but those programmers seem happy with mixing Perl and C, for example. Look at Zope. It has it's own web server. I know it's faster, but why do you think this is happening with Python specifically?
Strangest use of Python (Score:5)
What use of Python have you found that surprised you the most, that gave you the strongest "I can't believe they did that" reaction?
Re:Performance (Score:2)
Re:efficient compilation and standardization (Score:2)
Re:Python 3000 (Score:2)
Re:Data Structures Library (Score:2)
Re:[j | c]Python (Score:2)
Re:Conflict with GPL (Score:2)
Re:Stackless Python? (Score:2)
self (Score:2)
wxPython (Score:3)
Every language needs a CPAN. (Score:2)
Re:Structured Design. (Score:2)
Example:
if ($foo):
while ($fee):
buncha code
endwhile;
endif;
If the buncha code fills up your screen it's easy to grok what's going on at the end of control structures. For every control structure php provides a keyword for the end.
Re:Structured Design. (Score:2)
Oh man I can't resists...
Microsoft
Where I work
Slashdot
United States of America
Washington DC
Komodo (Score:2)
[j | c]Python (Score:5)
sean
Static typing (Score:2)
It seems that (optional) static types would enable the creation of practical python compilers, and could also provide much more in the way of pre-execution error detection.
I've heard rumours that static typing might be in the pipeline for Python. Is there any truth to these rumours, and if so, how might they be implemented?
Why "None"? (Score:3)
I have long wondered why the value None in python is named "None". It's pretty common in other languages to call that thing (or something very similar) "NULL". Were you trying to differentiate None and NULL in some way, or do you just like the way "None" sounds as you read code?
does Python need a CPAN? (Score:5)
Do you see things in a similar way? If so, why has Python not evolved something similar or better, and what can I do to help it along in this realm?
Politeness (Score:2)
What is your secret for keeping your cool when discussions get heated, particularly when techies tend to be very loyal to their causes?
Honestly, now (Score:2)
In all seriosity (?) are there times when you overload on Python and just have to get away for a while?
-DA
Development of Language Bindings (Score:4)
Thanks.
Re:Data Structures Library (Score:2)
You can look up data structures anywhere, but developing clean algorithms takes "skills".
bash-2.04$
Data Structures Library (Score:5)
bash-2.04$
Re:Python's Relation to Knuth's Conjecture (Score:2)
Re:Python's Relation to Knuth's Conjecture (Score:2)
Language Specification (Score:3)
Are there any plans to set some kind of standard language specification that will hold for a while?
Fat snakes don't hunt (Score:2)
Python's Relation to Knuth's Conjecture (Score:2)
In the upcoming volume IV of Knuth's TAOCP, Seminumerical Searches for Hoaring Triplets, he conjectures the following about the Theory of Programming Languages:
Along these lines, I pose the following questions:
Thank you.
What is *your* idea of Python and its future? (Score:5).
What is bad about python ? (Score:2)
What are the bad points in Python ?
What kind (or size) of project should not be written in Python ?
When should one use a different language ?
Thanks.
Indentation? (Score:2)
In Python, indentation is the token. What's the rationale for this? Do you get a lot of flack from people who prefer the old-fashioned way?
Oh yeah, and since the Vim % command (jump to matching bracket) doesn't work with Python code, do you know of a macro to replace it?
__
Re:Remapping % in Vim (Score:2)
Now all I need is a macro to actually do the function I described! That's the easy part, of course!
__
Follow-up Questions (Score:2)
What's your favorite Monty Python Quote and Movie?
python versus perl (Score:2)
(2) who speaks more languages, you or (that supposed linguist) larry wall?
(3) if you could eliminate one planet from the solar system (besides the earth), which one would it be?
(4) how do you feel about the euro?
Python (Score:2)
.
-- Floyd
Re:Python (Score:2)
If you were stuck on a desert island... (Score:2)
Question about the personal side (Score:4)
Yours,
Bob
Re:What is *your* idea of Python and its future? (Score!
efficient compilation and standardization (Score:4)
Re:Conflict with GPL (Score:2)
-- | https://developers.slashdot.org/story/01/04/16/231235/ask-guido-van-rossum | CC-MAIN-2016-40 | refinedweb | 4,944 | 72.97 |
Re: Stefano Zacchiroli 2012-06-25 <[🔎] 20120625165835.GB20683@upsilon.cc> > Making this even clearer with a *.incubator.debian.org namespace might > be a good idea. (Modulo some transition time, doing so will eventually > replace *.debian.net, if I got that right.) > - I've already discussed in a related thread of a few months ago how I > think the current distinction between debian.net and debian.org should > be documented, incidentally resolving other visibility problems of > those services. Not that the dnsZoneEntry LDAP entry is publicly > available, we should have an automated generated index of debian.net > services, with pointers to the responsible DD. I think it'd be a good > idea to have such index live at together with an > explanation of the debian.net/.org distinction. I don't think *this > part* of the confusion is enough to justify changes of the current > scheme (but see below for another possible reason). I agree that "debian.net" and "debian.org" are a tad too similar such that an outsider can clearly see that the former is "in incubation", but that's what we have at the moment, and I'd rather not replace it by something more ugly. Let's just document it more prominently. Maybe .debian.net owners should be encouraged to put a note on the website, or something like that. > Generally speaking, every time we add an approval step I start to fear > bottlenecks and the creation of new mighty powers; avoiding that is > one of the key advantages of the current scheme. If the main problem .debian.net is very useful in that it enables DDs to get things done. Let's not put in more bureaucracy in front of it. > is "squatting", then I see two possible solutions: > > 1) be liberal by default, but empower someone to decide that a name is > not acceptable. I think DSA would be a reasonable choice, as you > already decide on *.debian.org, but I suspect DSA would not want to > have this veto power (choice which I respect) Afaict there's no written rule that says "don't put your private homepage there" or similar. Actually "should be useful for Debian" should be enough of a rule. With that, someone can slap the offenders, e.g. DSA or DAM. > 2) find some clear cut rule. One I've proposed in the past is that for > any *.debian.org entry, the corresponding *.debian.net should not > exist (or point to the debian.org ones, depending on the protocol). > This one will still give some sort of veto power to DSA, but it > will come with the factual justification of an existing homonymous > service I've seen .debian.net used for testing .debian.org services, but that's mostly confusing to users. I wouldn't put in an official "must not exist" rule there, but an "should not exist or redirect to debian.org" makes sense. Btw, what would actually be an improvement would be shared debian.net entries, i.e. entries that anyone can edit. (Maybe that should even be the default.) Christoph -- cb@df7cb.de |
Attachment:
signature.asc
Description: Digital signature | https://lists.debian.org/debian-project/2012/06/msg00156.html | CC-MAIN-2016-44 | refinedweb | 523 | 68.57 |
java.lang.Object
org.netlib.lapack.Dlassqorg.netlib.lapack.Dlassq
public class Dlassq
Following is the description from the original Fortran source. For each array argument, the Java version will include an integer offset parameter, so the arguments may not match the description exactly. Contact seymour@cs.utk.edu with any questions.
* .. * *. * * Arguments * ========= * * N (input) INTEGER * The number of elements to be used from the vector X. * * X (input) DOUBLE PRECISION array, dimension (N) * The vector for which a scaled sum of squares is computed. * x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. * * INCX (input) INTEGER * The increment between successive values of the vector X. * INCX > 0. * * SCALE (input/output) DOUBLE PRECISION * On entry, the value scale in the equation above. * On exit, SCALE is overwritten with scl , the scaling factor * for the sum of squares. * * SUMSQ (input/output) DOUBLE PRECISION * On entry, the value sumsq in the equation above. * On exit, SUMSQ is overwritten with smsq , the basic sum of * squares from which scl has been factored out. * * ===================================================================== * * .. Parameters ..
public Dlassq()
public static void dlassq(int n, double[] x, int _x_offset, int incx, doubleW scale, doubleW sumsq) | http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/Dlassq.html | CC-MAIN-2017-51 | refinedweb | 190 | 56.55 |
Review: WWE Smackdown Vs. Raw 2007 (XB360). It scratches the itch of being an arcade wrestling game while offering just enough simulation aspects so as not to bore the hell out of me. But, and I can’t imagine I’m alone in this feeling, it seems to me that the franchise has become somewhat stale in recent years, due in part to a lack of innovation from THQ and Yukes. 2K6 did some new things right, yes, but not nearly enough to really spike interest in the title, and with 2K7 being the eighth game in the series, some changes were definitely needed to keep interest strong.
Still, SvR2K7 IS a next-gen title, and is appearing for the first time on a Microsoft console. Not only that, but the wrestling landscape has been somewhat barren as of late, both on the 360 and otherwise; Rumble Roses XX is the only competing title on the system as of yet, and with the Def Jam franchise moving into a “fighting game” direction (because THAT’S fresh and original, let me tell you), it may well be the ONLY competing title for a long time. So long as the parent companies addressed the very real interests and desires of the fan base, it seemed to me, they would easily have a killer app on their hands, and even with the minutest changes, so long as they were in the areas people wanted, the game would easily be the best of the bunch. So, is this so? Let’s take a look and see.
1. STORY/GAME MODES
Second verse, same as the first. The storylines in SvR2K7 are about on par with the storylines in 2K6; that is to say, they’re wrestling stories. Storylines like “Trish Stratus helps Chris Masters win the World Title (god help us if THAT ever happens), so she becomes the world champion” and “Triple H asks you to beat up some enemies in return for various stipulations in your World Title match” are commonplace, and they’re about as good as you’d expect. On the upside, character dependent storylines make their return (as noted last year, if you play as a character who should be featured in the storyline you’re about to participate in, you are provided an alternate storyline), but on the downside, the stories themselves seem less involving than in previous years. Your character of choice speaks less than in 2K6, which I must admit plays a part in that; In my first four hours of play, my character spoke, oh, once. This really lends the feeling that there’s even less to the story mode than in previous years, which makes playing through it vaguely depressing; you can’t even unlock infinite CAW points by completing Season Mode anymore (that honor goes to winning a year in GM mode).
The various gameplay modes are identical to last year’s offering, though there is one new match type: Money in the Bank. In terms of actual gameplay, it’s fundamentally similar to a six person ladder match, so it’s not THAT special or anything, but it does the job well enough. In return, the “Fulfill Your Fantasy” match has been excised; on one hand, this was really the only Diva-specific match of the group, but on the other, it sucked, so it won’t be missed. GM mode makes a triumphant return of sorts, as does online play, though for some obscenely stupid reason, female wrestlers are not eligible to be used online. No, really. I’m serious. In other words, one new match type, one removed match type, women no longer allowed for online play, ergo, lower score than last year. This, you will note, is the beginning of a trend.
Story Rating: 2/5
Game Modes Rating: 2/5
2. GRAPHICS
The graphics in SvR2K7 are, for the most part, really impressive. The characters look surprisingly realistic, and from the top tier guys like John Cena and Triple H to the lower card guys like Davari and Lance Cade, they’re all quite realistic and true to life. Custom characters look a LOT better here, which is damn cool, and clothing is no longer “skinned”ÂÂÂ; you can see noticeable space between clothing and arms or legs or whatever, which is a good thing to see. The environments are also well done and realistic to how one would expect them to look, though the fans could use some added depth. Clipping is still present, especially with hair and through the ropes and such, though it seems reduced from last year. Overall, the visuals are really good, and minor gripes aside, this is easily the best looking WWE game ever made, and one of the better looking games on the console.
Graphics Rating: 8/10
3. SOUND
The in-game music is a standard mix of rock and rap music, just like in 2K6. Bands like Godsmack and Nonpoint contribute songs to the game soundtrack, which can also be used as entrance music if you so desire. The various superstar theme songs are also, for the most part, completely accurate.
The voice acting is about as good as you’d expect from it; the wrestlers deliver their lines exactly as they would if they were on TV, which is either good (Triple H) or bad (Masters) depending upon the wrestler in question. The commentary is something of a retread from last year, though that’s certainly understandable; the commentary worked last year, so simply adding to it instead of completely changing it is wise, though if I hear JR brag about having a pinfall over The Game one more time, I’m going to vomit. The various sound effects are, as always, high quality and mimic the sounds of the squared circle appropriately. All told, SvR2K7 delivers an aural experience that’s consistent and works well, though it’s nothing you haven’t seen in previous versions of the game, all in all.
Sound Rating: 7/10
4. CONTROL/GAMEPLAY
This is the area in which most of the major changes have been applied, so get ready for a lot of reading. Again.
SvR2K7 brings with it a new control schematic, which will most likely feel familiar to fans of the Fight Night franchise; instead of using the buttons to perform grapples, grapples can now be initiated with the right stick. This feels like an improvement at first, but after playing with both control schemes, it’s not really substantially different or exciting. You aren’t required to press a direction on the left stick/pad to perform grapples, so one less thing needs to be done to grapple and such, but otherwise, the control scheme largely feels similar to the standard button setup. It’s not worse, but it’s not really better, either. Also new to the game is the Ultimate Control system; when engaged in a grapple, one presses the right stick in instead of performing a standard grapple attempt, which instigates a conditional grapple of sorts. From here, the character can do various things to vary up the move; say if you have someone in a suplex, you can drop them over the rope or rail instead of complete the move, or you can repeat a powerbomb motion multiple times, etc. It’s an interesting addition that shows promise, but there really aren’t a lot of moves available in the choices as of yet, so it doesn’t feel wholly complete at this point. Otherwise, the game plays as you might expect; you can still run, strike, perform finishers, and counter at the press of a button (or two, occasionally), and everything is largely intuitive and easy to pick up. The stamina system is still around (stop to breathe or your character gets more blown up than the Ultimate Warrior… well, ever), as is the momentum/finisher system (build momentum to perform finishers). Indeed, most of the things that players saw in 2K6 make a return in 2K6, though it seems that pre-match mini-games have taken a powder, but that’s not so bad; they won’t really be missed.
GM mode makes a return as well, which is essentially a “General Manager simulator”, as it was last year. You can now recruit storyline writers to develop stories for wrestlers to work with, which is an interesting bit of variety… but, seeing as you can’t dictate the ending of matches, the game still works within this sort of “worked shoot” style, where angles, feuds, and such are at your control, but match results are kayfabed (IE, “real”ÂÂÂ). As a game mode, GM mode is prettier than, say, EWR, but it’s still not terribly as deep or strong as it should be, so while it might offer players some sort of diversion, it won’t keep hardcore fans entertained for very long.
Create-a-Character makes a return, as expected, and also as expected, it’s as good as ever. Every aspect of your character, from top to tail, is completely customizable, and while certain elements seem less functional than they used to be (you can’t have your character wear a different shirt for backstage bits versus during matches, as an example), overall CAC is still as strong as always, and characters, as noted, look better to boot. Create-an-Entrance returns as well, only this time it’s actually a lot stronger. You can customize virtually everything about a character’s entrance, from lighting and camera angles to pyro timing to name plate appearance, and it’s all very simple to work with. Some entrances are less friendly than others to customization than others, of course (put a piece of the Undertaker’s intro with anything else and watch yourself wear a cowboy hat for, oh, ten seconds… yeah), but by and large it’s leaps and bounds better than it used to be. Online play is still as strong as it has been, especially with Xbox Live support, and the standard Ranked and Unranked match-ups are available as always. You can use your created (male) characters online (so long as the match creator allows this), and pretty much every match type is available for play without issue. Create-a-Belt is also still around, and works as well as always, and you can still defend your title online without issue, which is good.
That said, there are still problems, and they’re many of the same ones. In the review of 2K6, I had noted, “Collision detection is still spotty, especially during autocombo moves, like the Dragon Whip for example, so you’ll see moves connect without actually doing what was intended. Running moves still require you to be almost spot-on to hit with them properly, as do several of the aerial attacks.“ Well, guess what? SAME PROBLEM. I also noted, “SvR 2006 continues the Smackdown tradition of making sure to exclude female players from having any fun with the game whatsoever. There’s no Season Mode option for female characters, and assuming you want to play as one, you won’t be able to participate in over half of the available match types with them.“ Guess what? SAME PROBLEM, ONLY WORSE; as I noted previously, you can’t even play as female wrestlers online, at ALL. I mean, if all the Divas are going to do is serve as managers and eye candy, screw it, don’t even offer the title as an actual title in the game anymore guys, okay? Just openly admit, “we don’t give a shit about women or their opinion of our game, we intend to cater exclusively to males, and if you’re a female player, sucks to be you, why don’t you go play something like Barbie Horse Adventures instead?”; at least THAT would be honest. I am no longer willing to play nice with this; I think it honestly flat-out sucks, and I refuse to pretend I don’t. Sorry. And to round it all out, GM Mode is still largely as shallow as ever, and still dictates match endings based on how popular your wrestlers are unless you personally influence the matches otherwise, which was tolerable when it was in its infancy, but is not so much a year later. The roster is out of date, and several key wrestlers (Spirit Squad? The ECW roster?) are missing. And despite the great ECW experiment, speaking of such, ECW isn’t really given any sort of a presence, unless one counts RVD and Tazz (as a Legend) as a “presence”, so to say. No Sabu, no Sandman, no Kevin Thorne or Ariel, nada. Way to pimp the brand, guys.
Overall, SvR2K7 is still a largely playable and enjoyable experience, but this is largely due to what has always been right with the series as opposed to what has always been WRONG with it. The core gameplay is still entertaining, online play is still strong and worthwhile, and the Create-a-whatever modes are still as strong as ever. Nothing that was broken has really been fixed, not very much new has been added to the experience, and the game is even more chauvinistic than ever, but it’s still an entertaining, if wholly unoriginal, experience. Fans will find 2K7 just as interesting, play wise, as 2K6… but that’s about all they’ll find it. Those who’ve never played a Smackdown game before, however, will find 2K7 as good a place to start as any; it’s not anything different, but it’s easily accessible and easy enough to play to bring new players into the fold without problems. The controls and gameplay are still as solid as ever, and while the ancillary stuff isn’t as strong as it could be, the game itself is still just fine… same as last year.
Control/Gameplay Rating: 6/10
5. REPLAYABILITY
As always, there are plenty of reasons to return to SvR2K7. Lots of unlockables, including Legends, moves, and other things await your… um, unlocking, and there are a substantial amount of matches to keep you coming back. Create-a-Character is still as interesting as ever, though the couple of removed features combined with the lack of custom theme song options make the feature less interesting than it ought to be. Online play is as strong as ever and between that and standard multiplayer features, you’ll have plenty of reasons to come back for more. That said, if you’re a Smackdown vet, there’s nothing in 2K7 that makes it any more replayable than, say, 2K6, so if you played that one to death, you might not be so willing to do the same this time around.
Replayability Rating: 6/10
6. BALANCE
SvR2K6, as always, features multiple different difficulty modes, ranging from being Easy like Lita to hard like Viscera (Ha, thought I was gonna reuse the Val Venis gag, didn’t you), so that seasoned vets and newcomers alike have a solid challenge awaiting them. The AI can be a small bit unreasonable at times with its reversals, but this isn’t wholly unforgivable, and can be worked around well enough. The balance online is, as always, dependant upon both your skill and the skill of your opponents, but the various characters are solidly balanced to one another, and as no one character is better than any other, it all comes down to skill, which leaves the game, well, about as balanced as it was last year.
Balance Rating: 7/10
7. ORIGINALITY
The sum total amount of changes to SvR2K7 amount to a modified control scheme, a roster update (that’s still outdated), some minor tweaks to the interface and GM mode, and a new grapple type. Everything else in the game, and I mean EVERYTHING, has appeared in one of the seven other Smackdown titles that have come out in the past not-quite-a-decade. There are no major overhauls, no features that are a dramatic change from previous games, just some modifications and tweaks to the same game as last year. Granted, you’re not really going to play a game like SvR2K7 expecting anything but Smackdown goodness, but some originality would be nice once in a while.
Originality Rating: 2/10
8. ADDICTIVENESS
As last year, most of the addictiveness in 2K7 comes from the sheer amount of stuff you have available to you. Season Mode and GM Mode offer a lot to do, and Create-A-Character is as robust as ever, though the lack of custom soundtrack support keeps you from giving, say, your created Goldberg, Sting, or Natural Disasters tag team the finishing touches you might want. The game is still as easy as ever to pick up, too, which helps to get you into the game that much more. If you’ve been playing the games since the beginning, though, you might find yourself less addicted than you might like; there’s really not anything new to keep your interest that you won’t have seen before, save for the Ultimate grapples, and the new control scheme isn’t really enough to make the game as addictive as it was the first time around.
Addictiveness Rating: 6/10
9. APPEAL FACTOR
Well, it appears both of my predictions last year were wrong (thankfully), so the game retains what appeal it has always had. That is to say, if you’re a wrestling fan, you’ll have plenty of reasons to want to play SvR2K7, though if you’re a wrestling fan, most likely you’ve been playing Smackdown titles for a while. If that’s the case, you might not find this any more desirable than, say, 2K6, save for the roster updates. If you’re not a wrestling fan, 2K7 is still an enjoyable, entertaining experience, but it’s one you might not really get or care about, which will most likely turn non-wrestling fans off from the get-go.
Appeal Rating: 6/10
10. MISCELLANEOUS
Well, SvR2K7 is certainly the best wrestling title on the 360, but it’s not like the competition was stiff or anything (what with Rumble Roses XX being the only competitor and all, and no, no pun was intended). It’s not really significantly better than 2K6, however, which still puts it in the same place it ended up last year: not the best, but not really the worst. The Smackdown franchise has hit something of a wall, it seems: until the known and obvious clipping, AI, and collision detection issues are repaired, the GM mode is fleshed out more (and not kayfabed as much as it is), it won’t be a competitor for “best wrestling franchise” any time soon. The lack of custom ring entrance theme music is also somewhat of a major oversight, as well; I know I’ve harped on that a bit here, but when games like RAW 2 (an inferior product, though it was still enjoyable) and Rumble Roses XX (also an inferior product) offer such support, and this doesn’t, that hurts a bit, and it’s pretty depressing to see such an oversight. 2K7 is still an enjoyable product, but it’s too similar to last year’s offering, and doesn’t offer enough to make it really “next gen”.
Miscellaneous Rating: 6/10
The Scores:
Story: 2/5
Game Modes: 2/5
Graphics: 8/10
Sound: 7/10
Control/Gameplay: 6/10
Replayability: 6/10
Balance: 7/10
Originality: 2/10
Addictiveness: 6/10
Appeal: 6/10
Miscellaneous: 6/10
Overall Score: 5.8/10
Final Score: 6.0 (FAIR).
Short Attention Span Summary. | http://diehardgamefan.com/2007/01/10/63654/ | CC-MAIN-2022-40 | refinedweb | 3,326 | 61.19 |
Wiki 101
Contents
- 1 Learning and thinking
- 2 Wiki 101
- 2.1 Prerequisites
- 2.2 MediaWiki Handbook
- 2.3 Namespaces
- 2.4 Text formatting
- 2.5 Linking pages
- 2.6 Lists and listings
- 2.7 Table basics
- 2.8 Templates
- 2.9 Advanced editing
- 3 See also
teaching - learning - discussing - creating - thinking
Learning and thinking
Wikiversity seeks to engage participants in explorations of those topics that they are most interested in. Wikiversity seeks to collect and organize information and make it accessible to learners, but Wikiversity is not just concerned with a collection of facts. Each domain of human knowledge and each collection of facts can be explored by making use of various organizational strategies and patterns of thinking. Wikiversity seeks to make explicit and learnable the patterns of thought that that experts find useful in the study of different subjects. Wikiversity is not about tests and grades. So how is anyone to judge if learning is taking place, if learners are thinking at Wikiversity?
Wiki 101
Wikiversity is devoted to the idea that Wikiversity participants should be active learners. In a wiki, a major activity is editing wiki pages. The wiki editing interface can be a source of confusion for new users. "Wiki 101" is a Wikiversity project devoted to the task of providing new Wikiversity editors with everything they need to start editing Wikiversity pages.
It is through the editing of wiki pages that we can, as a learning community, judge if learning is taking place within Wikiversity. Did something you saw at Wikiversity make you think? If so, share your thoughts and experiences by being a wiki editor.
Prerequisites
- Introduction to Wiki - this project aims to function as a service project for the Wikiversity community and provide learning resources that will aid new Wikiversity editors.
- Wikiversity:Guided tour - Take this tour to get an overview of how Wikiversity works.
MediaWiki Handbook
The definitive guide to editing pages at Wikiversity or any of the Wikimedia projects is the MediaWiki Handbook. MediaWiki is the software that runs Wikiversity servers. You can open the handbook in a separate browser window or tab keeping it handy while editing away at Wikiversity.
Namespaces
Namespaces are ways to keep large sections of content organized. The following are some that Wikiversity editors should become familiar with:
- Main Namespace - This is where lessons and shared learning materials reside. These are the only content titles without prefixes.
- Help Namespace - Prefixed with Help:, this namespace has a top-level table of contents at Help:Contents which links to other help pages. The Help link appears in the left navigation panel on every Wikiversity page.
- User Namespace - Prefixed with User:, this namespace is where your userpage resides if you have created an account and logged in. Creating an account gives MediaWiki a way to provide you with a Watchlist, keep track of your contributions and many other features.
- Special Namespace - Prefixed with Special:, this namespace contains many types of pages like Special:Recentchanges, Special:Allpages and many others. Just click on Special:Specialpages to see.
- Category Namespace - Prefixed with Category:, This is how things are classified and organized at Wikiversity.
- Template Namespace - Prefixed with Template:, this namespace allows pieces of content to be used on several pages for messages, navigation aids, or other reusable information. A template is "called" by placing a tag like {{SomeTemplate}} in the page you are editing.
- Image Namespace - Prefixed with Image:, this namespace holds pictures and image files that anyone can Upload to Wikiversity. See Special:Newimages for examples.
- Talk namespaces - Prefixed with Talk:, this namespace is for the discussion area that goes with each article in the main namespace. For prefixed pages, the prefix is appended with _talk to link to its discussion page. Examples: User talk:CQ (my user talk page), Template talk:Translators, Image talk:Wiki.png, ...
- Wikiversity namespace - Prefixed with Wikiversity:, this namespace is for pages that are about Wikiversity and its administration. It is known also as the project namespace. Examples: Wikiversity:About, Wikiversity:Welcome, newcomers, Wikiversity:Introduction, ...
- Portal namespace - Prefixed with Portal:, this namespace is for navigating general areas of interest through what we call portals. Examples: Portal:Education, Portal:Practical Arts and Sciences, ...
- School namespace - Prefixed with School:, This namespace is for major areas of interest and general study organized in a more traditional form. Examples: School:Medicine, School:Computer Science, etc.
- Topic namespace - Prefixed with Topic:, This namespace is for Department, Divisions or specialized areas of interst or study. They are usually linked to Schools and/or Portals. Examples: Topic:Web Design, Topic:Translation, Topic:Public International Law, etc.
Learning to work within and among namespaces is essential to understanding how Wikiversity is built, organized and maintained.
Text formatting
Text formatting is easy with MediaWiki:
'''Bold''' renders Bold ''Italic'' renders Italic '''''Bold Italic''''' renders Bold Italic
Adding a space before some text renders:
A space before some text renders the text in a gray box like this one
See the MediaWiki Handbook for much more information about starting new pages, text formating, creating sections and subsections, and all sorts of tips and tricks.
Linking pages
Linking pages is usually as simple as surrounding a word with square brackets: [[Some word or phrase]]. If you link to a page that does not exist, you produce a red link. Clicking on a red link automatically opens the editor at that page. If the page exists, you will see a blue link.
Make sure you are linking to the correct page. For example,
[[Public International Law]]
produces a red link because the actual article is at Topic:Public International Law. You can hide the fact that it is in the Topic namespace by adding a pipe (|) at the end like this:
[[Public international law|]]
causing it to appear like this:
Public International Law.
Sometimes it is necessary to create a redirect from one page to another. For example, [[Wikiversity]] links to Wikiversity which is a REDIRECT to Wikiversity:About. Notice that when you get to Wikiversity:About you see "Redirected from Wikiversity" which is the #REDIRECT page.
You can link to articles outside of Wikiversity.
Wikipedia - [[w:Some Wikipedia article]] Meta-Wikimedia - [[m:An article at Meta]] Wikibooks - [[b:A title at Wikibooks]]
This is called Interwiki linking is an easy way to link to existing articles at Wikiversity sister projects.
Finally, you can link to external resources like this:
[ Google]
Which renders:
Notice that we use one square bracket instead of two and that the url can contain no spaces. The first space encountered acts to separate the url from the face that we want to appear. Always use courtesy and common sense when linking to outside sites. See external link for more info
Lists and listings
You can add a bullet to an item by simply adding an asterisk (*) to a new line:
- Bulleted Item
You can create a bulleted list like this:
*Item *Another item *Yet another item
Renders:
- Item
- Another item
- Yet another item
A numbered list is created using:
#Item #Another item #Yet another item
Which renders:
- Item
- Another item
- Yet another item
It is customary to make lists with descriptions:
- Item - Description of item
- Another item - More detailed description of a numbered item that may use more than one line.
- Yet another item - Very terse and lengthy description of yet another item that may include a number of sentances. You may not add a line break or paragraph break and expect your numbering to be continued. It will start over.
- Still yet another item - Not starting a new paragraph or break allows this numbered listing to continue.
- Item - A paragraph break restarted the numbering
- Nested item 1 - nested item using ##
- Nested item 2 - another nested item using ##
- Another Item - counter returns to higher level with #
- Start a set of nested bulleted items using ##
- nested bulleted item using ##*
- nested bulleted item using ##*
- Start another set of nested bulleted items using ##
- nested bulleted item using ##*
- nested bulleted item using ##*
- Yet another Item - Counter keeps its place in a mixed hierarchy of items
These are some commonly used listing basics. See the MediaWiki Handbook for much more about lists and listings .
Table basics
Tables are frames that can be easily created using wiki syntax to make sets of data more logical and aesthetically pleasing. The basic syntax is:
{| |+ Simple Table !heading 1 !! heading 2 !! heading 3 |- |data A1 || data A2 || data A3 |- |data B1 || data B2 || data B3 |}
Which renders:
Not too pretty yet. MediaWiki includes some table attributes using a predefined classes, such as class="wikitable" that we add to the table's opening tag:
{| class="wikitable"
By simply adding the wikitable class, the same code gives us:
A bit nicer, eh? If we really want to get fancy, we can customize with more table and style attributes:
{| cellpadding="4" cellspacing="1" style="text-align:center; font-weight:bold; font-size:120%" |+ Not-so-simple Table |-style="background:Black; color:White" !heading 1 !! heading 2 !! heading 3 |- style="background:FireBrick" |style="color:LightYellow"|data A1 |style="color:AliceBlue"|data A2 |style="color:MistyRose"|data A3 |- |- style="background:MidnightBlue" |style="color:LightYellow"|data B1 |style="color:AliceBlue"|data B2 |style="color:MistyRose"|data B3 |}
Which renders:
These color atrributes were made with Named Colors, but other web colors and methods can be used. A host of other attributes can be used to alter the look and feel of a table. There are as many ways to make tables as there are Wiki editors! See the MediaWiki Handbook for more.
Explore
Take a look at the code used on the Wikiversity:Main Page and its subpages:
- Wikiversity:Main Page/Welcome
- Wikiversity:Main Page/Communications and community
- Wikiversity:Main Page/Related links
Use the edit tab, but please don't change these without clearance. Look for table elements and how they work together to form the Main Page at Wikiversity.
Don't be shy about studying the code that drives Wikiversity, just hit cancel when you are done. It's best not to edit high-traffic pages but if you do accidently "mess up" a page, notify one of the Wikiversity:Custodians. (...and be more careful next time).
Templates
Sometimes it is desirable to create templates that can be reused on many pages. These are created in the Template namespace and can be quite complex for even experienced editors.
One of the simpler types is a reusable list. Template:Wikiversitysister-list is an example of a handy way to show all of Wikiversity's sisterprojects. Simply add the code {{Wikiversitysister-list}} to a page. It renders:
Referring to a template
A way to refer to a template and the tag that calls it without transcluding it is like this:
{{tl|Wikiversitysister-list}}
which renders:
{{Wikiversitysister-list}}
Notice that the text inside the curly brackets links to Template:Wikiversitysister-list.
Page templates
Sometimes it is handy to create whole pages from templates called "boilerplates". These are usually used for Schools, divisions and departments. See Category:Page creation templates for ideas on how to create whole pages from templates.
Explore
Go to Template:Wikiversitysister-list and click edit. Notice the combined use of table attributes, interwiki links, embedded HTML tags and other tricks to get the list to render the way its author intended. Please do not make any changes to this template. Hit cancel after youve had a long look.
If you want, you can copy and paste the code into the Wikiversity:Sandbox or a subpage of your user page. (See m:Sub pages and Wikiversity:Userboxes for more about subpages and userboxes.
Template documentation
Instructions on how and where to use a template should appear on its associated Template talk: page. Example: Template talk:Wikiversitysister-list. Unfortunately, many Wikiversity templates remain undocumented.
Userboxes
Userboxes are a popular tradition around Wiki sites. They are often artistic, witty and complex to create. {{User oops}} is a cute one:
Explore that one. Notice the extensive use of MediaWiki variables such as {{TALKSPACE}} and {{{1|{{PAGENAME}}}}}.
Template Taskforce
If you wish to learn more about creating and using templates, consider joining the Wikiversity Template Taskforce.
Advanced editing
This lesson touched on some basic editing principles. When you want to go further, See (and help to develop) more Wiki and MediaWiki lessons.
See also
- Wiki - a project devoted to learning how to use wiki technology to facilitate online learning.
- Topic:MediaWiki - an advanced exploration of the MediaWiki software suite. (Wiki 101 is a recommended prerequisite)
- Wikipedia guides to editing | https://en.wikiversity.org/wiki/Wiki_101 | CC-MAIN-2019-09 | refinedweb | 2,078 | 54.83 |
17 May 2010 09:57 [Source: ICIS news]
By Mahua Chakravarty
MUMBAI (ICIS news)--The start up of new benzene and paraxylene (PX) plants and strong demand for toluene will maintain aromatics growth at 7-10% for India and at 2-4% in the Middle East through 2010, an industry executive said late on Friday.
“The happy story [about the Middle East] is that volumes are growing, margins are healthy,” said Yogesh Mehta, managing director of distribution company Petrochem, referring to the start up of new plants producing benzene and PX in Oman and Kuwait since 2009.
New downstream styrene monomer (SM) plants in Kuwait and Iran had resulted in an increase in benzene consumption in the region, Mehta told ICIS news on the sidelines of 2010 ?xml:namespace>
“The market dynamics is changing in the Middle East with new players coming in, and as distributors we see this as a great opportunity because we have more products to serve the market growth,” Mehta added.
“Benzene is a big product in Iran and Saudi Arabia but it goes into captive consumption [mostly],” he said.
Iran is a net exporter of benzene to Asia and Europe, but a lot of benzene exported by Iran is expected to be channeled for captive purposes with the start up of PARS, a 600,000 tonnes/year SM plant, from the first quarter of 2010.
The recovery in economic growth in 2010 was also a key factor in the increased net demand for toluene and xylenes in the Middle East and India, Mehta said.
“The Middle East market has been growing exponentially despite the debacle of 2008. If you traced a pattern from 2004, there was a growth of 12-15% every year in the Mid East area [until 2008],” he added.
Markets in the Middle East had recovered considerably and demand for toluene and xylenes was expected to increase 2-4% in 2010, he said.
Regional downstream factories in the solvents sector, which had started up before 2008, had increased production figures following the economic recovery thereby increasing the demand, Mehta said.
In the Gulf Cooperation Council (GCC) region, toluene demand was estimated to be about 75,000 tonnes/year, while in India net import demand was estimated at nearly 110,000 tonnes/year.
In India, toluene is produced by Reliance, the major supplier, and a second producer in southern India, but the output was not enough to match the growing local demand, Mehta said.
The steady economic growth in the Indian market would continue to keep demand for toluene in the 7-10% bracket in 2010, he added.
“India has been growing at the rate of 7-8% and for us India has been the biggest growth market because of per capita growth, good geopolitics and good demand,” he said.
However, this growth could be derailed by political issues in the Middle East and the danger that supply may outpace demand in the middle term, Mehta said.
“…We live in an area troubled by geopolitics. The geopolitics does hurt us and sanctions are not good for business,” he added.
Despite the economic sanctions, Mehta believes that Iran would continue to impact the global aromatics trade equation.
The country has 14 refineries and a number of them are now producing benzene, toluene, SM, and would soon have products like phenol and acetone, he said.
“Iran is a major player, and like it or not Iran will always be part of the equation. It’s a monster for the chemical industry that’s going to wake up very soon,” he added. | http://www.icis.com/Articles/2010/05/17/9359900/aromatics-in-mid-east-india-to-grow-on-demand-new-units.html | CC-MAIN-2014-42 | refinedweb | 596 | 61.7 |
Let’s BUIDL: SmartWeave Contracts
projects.
The first difference between Ethereum smart contracts and SmartWeave (SW) contracts is that SmartWeave contracts are coded in JavaScript, you don’t need to learn a new programming language like you had to do with Solidity. If you know how to build a website or a Node.js project, then you know how to build a SmartWeave contract.
This also makes it super flexible, since you can use a SmartWeave contract to do pretty much anything you can do with JavaScript.
Another huge difference between the two contract types is that on Ethereum, the client that updates to the latest state the contracts are the miners, while on Arweave, the states are updated every time on the client, which most of the time is the visitor’s web browser. This is something very important to keep in mind while building a SmartWeave contract — they are not your only option, and shouldn’t be used for everything.
Since the SW contract itself is updated on the client, to get the latest state of a contract, the client needs to go through each interaction to find its latest valid state. It can be slow compared to other options like using ardb to grab transactions from Arweave.
An example of that are the Opportunities on CommunityXYZ. Opportunities are normal transactions, which makes them much faster to load since we only have to do a request which returns all the necessary fields without having to go through multiple transactions to find it. While loading a Community takes longer, we had to set a cache in place to help with that one.
How SmartWeave contracts are built
One thing that is always hard to understand for new devs working on top of Arweave is that a SmartWeave contract is separated into three pieces:
- The contract source
- The state
- The executor (SmartWeaveJS)
The contract source
The contract is the code itself, written in JavaScript. This is the contract that will be run on the client (by the executor) to update the states and get the latest and valid one.
The contract source never changes, this is what guarantees your users that what they are using today, will always be true. It’s always good, as a dev user, to read the contract source, so we know what the owner (or anyone else) can do with the projects you’re using.
Multiple projects can use the same contract source. An example of that are Profit Sharing Communities, by creating a Community on you’re using the same contract source as all the others, even CommunityXYZ itself uses the same contract source. However, each is separated by their own states and that state is deployed by the founder of that Community.
Let’s BUIDL!
The state is normally the first thing we write, but the contract should be the first thing we think about, since this defines what the project will be, and what you want it to do.
In this test, let’s write some simple code which will increase the caller’s balance every time they call the
increment function. Caller is the wallet address that interacts with this contract source.
export function handle(state, action) {
const balances = state.balances;
const input = action.input;
const caller = action.caller;
if(input.function === 'increment') {
// If the caller already is a key of balances, increment, if not, set it to 1.
if(caller in balances) {
balances[caller]++;
} else {
balances[caller] = 1;
}
}
}
All the SmartWeave contracts must start with
export function handle(state, action){} since this is the function that is called by the executor. Everything else should be inside that
handle function. Right now the
handle itself is confusing since we don’t know what the
state and
action params are. Let’s first explain the action.
The action param
The action param is the action that you send while executing a SmartWeave contract, every time you want to do an update on a SW contract you need to send an input transaction, this one normally includes a function name
input.function, and any other params that you need to send with it. In this case we don’t need to send anything else, but for example we could send
input.qty to specify the quantity we want to increment our balance, this also needs to be specified on the contract source code for it to work. Remember that this is controlled by the wallet owner, so we need to always have conditions when receiving data from the user, to prevent anything unwanted.
We will see the
input again when talking about the executor (SmartWeaveJS).
The action param also has the
caller as a key of that object. The caller, again, is who is running the function. These are the two only keys in
action:
input and
caller.
The state
The state is the contract state, which lets users know what the updates of your contract are, and where it is at, at the moment of execution. This get’s updated over time (on the client), while the contract source never changes.
When we first create a contract, we also need to send a state with it, which is the initial state.
Let’s BUIDL!
We can see on our contract source that the state is expecting a
balances object which includes wallet address (
caller) as keys, and each caller key has a number as its value. In this example let’s add to ourselves some balances as the initial state, the state is a JSON object:
{
balances: {
"BPr7vrFduuQqqVMu_tftxsScTKUq9ke0rx4q5C9ieQU": 1000
}
}
And this means that when the first person goes and reads our contract, the first state is that we have 1,000 of this token balance.
Both the state and the contract must be separate transactions sent to Arweave, and both are deployed only once. After that, the state is updated by sending little transactions that includes
input interactions.
Deploying
Before talking about the executor, let’s first see what we should do with the contract source and the initial state. Both of these are just normal transactions, but with some special tags. We could use SmartWeaveJS as a CLI tool to deploy these contracts, but since we are here to learn, let’s do it manually by using ArweaveJS to create these transactions. If you don’t know what ArweaveJS is or how to use it, click here to read the docs.
import Arweave from 'arweave';const arweave = Arweave.init({
host: 'arweave.net',
protocol: 'https',
port: 443
});async function createContract() {
// Let's first create the contract transaction.
const contractTx = await arweave.createTransaction({ data: contractSource }, wallet);
contractTx.addTag('App-Name', 'SmartWeaveContractSource');
contractTx.addTag('App-Version', '0.3.0');
contractTx.addTag('Content-Type', 'application/javascript');
// Sign
await arweave.transactions.sign(contractTx, wallet);
// Let's keep the ID, it will be used in the state transaction.
const contractSourceTxId = contractTx.id;
// Deploy the contract source
await arweave.transactions.post(contractTx);
// Now, let's create the Initial State transaction
const initialStateTx = await arweave.createTransaction({ data: initialState }, wallet);
initialState.addTag('App-Name', 'SmartWeaveContract');
initialState.addTag('App-Version', '0.3.0');
initialState.addTag('Contract-Src', contractSourceTxId);
initialState.addTag('Content-Type', 'application/json');
// Sign
await arweave.transactions.sign(initialState, wallet);
const initialStateTxId = initialState.id;
// Deploy
await arweave.transactions.post(initialState);
}
createContract();
Congratulations! You have just deployed your first SmartWeave contract.
What we will use to interact with your newly-created SW contract is that last
initialStateTxId, so make sure to keep it somewhere safe, since we will need it later.
Next time, we have to learn how “the executor” works, since this is what we need to use to read our contract’s latest states, and also to update the states by sending transactions to Arweave with it..
—
EDIT: Second part is out. Keep reading here: | https://cedriking.medium.com/lets-buidl-smartweave-contracts-6353d22c4561 | CC-MAIN-2021-31 | refinedweb | 1,296 | 63.09 |
Updated 2009/10/17
WARNING: this post is obsolete; go read this one instead.
JavaServer
Faces components generate their own HTML element
id
attributes. How to work with these generated IDs is a source of much
confusion among JSF neophytes. This post aims to explain what is going
on and provides sample code that should make working with IDs a little
bit easier.
Example JSF control in a JSP:
<h:inputText
How the control might be rendered in the markup:
<input id="j_id_jsp_115874224_691:table1:0:foo1" name="j_id_jsp_115874224_691:table1:0:foo1" />
The
id attribute rendered in the browser is
obviously not the same as the value set in the JSP. This new
id
is the
clientId and is produced by the UIComponent.getClientId(FacesContext)
method.
If you want to skip all the explanations and just get
something running, read How to get a
clientId
from an
id using a TLD function and then go download the Sample Code.
Topics:
- Why doesn't JSF just emit the ID that is set on the control?
- How to get a
clientIdusing backing beans
- How to create a generic class for component binding
- How to get a
clientIdfrom an
idusing a TLD function
- How to cache a
clientIdfrom an
idusing a TLD function
- Sample Code
- End Notes
Why doesn't JSF just emit the ID that is set on the control?
The problem is that the HTML ID must be unique, but the JSF component might render itself multiple times in a given request.
As a child of a data table,
foo2 may render a text
input field to the page any number of times:
<h:dataTable <h:column <h:inputText </h:column> </h:dataTable>
The underlying control for data tables (UIData)
is a NamingContainer.
It is possible for
NamingContainers to control the state of
their children and affect how the
clientId is generated.
NamingContainers are not the only things that affect
the
clientId. In a portlet container, it
is possible for a JSP to be rendered more than once in the same HTML
page. Therefore, the
clientId of the view
root will be namespaced to the portlet instance.
Ultimately, the exact form of a
clientId is an
implementation detail. Hard-coding a
clientId (e.g. in
JavaScript) is a potential source of bugs.
The nature of the
clientId mechanism imposes
restrictions on when and where you can invoke the
UIComponent.getClientId(String)
method. For example, for the data table above, it would be an error to
invoke the method on
foo2 outside
col1.
How to get a
clientId using backing beans
One way to get a component's
clientId is via a
property on a managed
bean. A managed bean containing the code below could return the
clientId
via the EL expression
#{someBean.fooClientId}.
WARNING: this component finding method
findComponent
(which is also used in the functions) was implemented based on the
incorrect assumption that IDs must be unique in the view. What the
specification says is this:
If a component has been given an identifier, it must be unique in the namespace of the closest ancestor to that component that is a NamingContainer (if any).
If you use the code, ensure that your component IDs are unique to the view. An alternative approach can be found here.
Note: It isn't possible to pass arguments to methods on
object instances (e.g.
action="#{bean.method('id')}").
Support for this should be in JEE6 (via JSR 245).
The above code walks the component tree to find the component. It is possible to avoid this by using the binding attribute to bind the component to the managed bean, as shown in this code:
The JSF lifecycle will perform the binding when the view is created or when the view is restored.
This solution works, but it means creating a bean instance and
defining a new method for every component for which the
clientId
is required.
How to create a generic class for component binding
Rather than create a bean for each page and define methods for
every component, it is possible to bind everything via a single object.
This bean can be used to bind any component and provide its
clientId:
This bean should also be bound to
request scope. It
is unwise to keep a reference to a component beyond the scope of a
request. Multiple views/pages are accommodated as the view may change
during the request. Here is the
faces-config.xml
definition:
<managed-bean> <managed-bean-name>lookup</managed-bean-name> <managed-bean-class>pagebeans.ComponentLookup</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>
This JSP code shows the binding of a button to the bean, and a
text field displaying the button's
clientId:
<h:commandButton <h:outputText
The downside of this approach is that if a component is to be looked up, it must be bound to the managed bean.
How to get a
clientId from an
id
using a TLD function
A generic way to define the lookup functionality is via custom
tag library (TLD) functions. This is a mechanism that allows you to
define function expressions that resolve to
public static
Java methods.
<function> <name>clientId</name> <function-class>demo.faces.ClientIdUtils </function-class> <function-signature>java.lang.String findClientId(java.lang.String)</function-signature> </function>
Example JSF control calling the function in an EL expression:
<h:commandButton
See Sample Code for an example implementation.
Since there is no binding information, this code will walk the view to find the components. This cost may be negligible, so the benefit of scripting simplicity may outweigh the cost. There is also the benefit of not needing managed bean artifacts. See the next section for a discussion on improving performance by caching.
How to cache a
clientId from an
id
using a TLD function
It is tempting to try to cache
clientIds to avoid
walking the component tree every function call. Caching the result
without component binding is difficult:
- The relationship between an instance of
UIComponentand the
clientIdcan be
1:N. The return value from
getClientIdcan be context-sensitive.
- The lifetime of a
UIComponentinstance probably won't exceed the request. Some implementations of StateManager can be configured to save the view state in the session, in which case the lifetime of the objects might be longer, but making your code rely on this makes it fragile and it would be easy to introduce memory leaks. Keeping a reference to a
UIComponentinstance is a bad idea.
- Views can be dynamic. Admittedly, this is an edge case, but it is possible to add, remove and move components programmatically.
The only relatively safe caching mechanism I can think of is to cache the path to the component based on its position within the UI tree. Components can contain a map of facets and/or a list of children. The path to a component in the header of a data table column might look like this:
view.children[0] -> table.children[0] -> column.facets['header'] -> panel.children[2]
This approach assumes that the tree structure is static.
A sample implementation (see below) is called via an EL expression like this:
<h:commandButton
The information is cached in the application map, so it is quickly available to all callers of a JSP page. Caching has a cost. How effective it is depends on the size and structure of the JSF view. Only select the caching method after proving it is beneficial by profiling.
If performance is a problem, consider supporting different tree traversal algorithms as an alternative.
Sample Code
A pre-built library containing the TLD functions mentioned above
is available as a download: clientId_2.0.1.zip.
This contains a JAR that can be placed in the
WEB-INF/lib
directory of JSF web applications. The taglib namespace is.
Example JSP file that imports the functions:
<?xml version="1.0" encoding="UTF-8" ?> <jsp:root xmlns: <jsp:directive.page <jsp:text> <![CDATA[<?xml version="1.0" encoding="UTF-8" ?>]]> </jsp:text> <jsp:text> <![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> ]]> </jsp:text> <html xmlns=""> <head> <meta http- <title>clientId demo</title> </head> <body> <f:view> <h:form> <h:commandButton </h:form> </f:view> </body> </html> </jsp:root>
All the sources are available in a public Subversion repository.
Repository:
License: MIT
Project: JsfClientId
End Notes
Another way to work with the
clientId is to write a
custom
component that emits markup via a renderer. This avoids working with the
clientId in the JSP. An example of a control that does this
is the output
label (see the
for attribute). This approach may be too
heavy-weight for one-off pieces of functionality. Also, it doesn't lend
itself to working with expressions in component attributes.
There are a number of places where it would be possible to plug
in functionality to build a request-scope component map without
explicitly binding components. See the ViewHandler
class; the PhaseListener
interface; etc. These can be configured with replacement or decorator
classes via
faces-config.xml. Whether the convenience of
this versus the cost of doing it for every control on every page pays
off depends on how many lookups are required. Again, this works better
for static trees of components and special handling would likely be
needed (probably via the Application.createComponent*
methods) for controls that were added outside the normal phases.
This article assumes the use of Java EE 5. JEE5 specifies JSF version 1.2.
how would this work with dataTable rows where ClientId also cosist of row index? This would always return clientId of first row.
If you are referring to the clientId value being cached - it is not, or you would have the problem you point out! It is the route to the component that is cached. You can see an example of using the code in a table in JSF: using component IDs in a data table (h:dataTable vs clientId).
I would really like to use a generic class for component binding. but I need to bind components inside iterative components like icefaces seriesPanel. Is a similar technique to the one described above possible?
Going purely on the documentation for panelSeries, it suggests it is possible. It will probably depend on the context (where) you end up invoking the getClientId method.
2 tables on page and input text must have same id in both tables. Rich function clientId return wrong id for second table. Any chance for workaround?
rich:dataTable id="a" value=...
rich:column
h:inputText id="input/
#{rich:clientId('input')}
/rich:column>
/dataTable>
rich:dataTable id="b" value=...
rich:column
h:inputText id=input/
{#rich:clientId('input')}
/rich:column
/dataTable
Yes.
As the first line of the post says...
...this post is obsolete; go read this one instead.
Click the link.
Hi McDowell,
I need to get the clientId for a cell in a table. I don't know how to do it because I cannot create a binding to the cell (or i don't know how to do that). Could you give some advice on how to do that?
Thanks in advanced!
Sa
Since the dataTable does not emit clientIds for UIColumn children, you cannot refer to the element directly. The best approach is probably to get a reference to a child element and walk up the parents to find the TD element.
If you use jQuery, the closest() method would be one way to do this.
Thanks for your reply. As for the "child element" you mentioned here, do you mean the row of the table? As for the "TD element", do you mean the column? Could you elaborate a little bit?
I'm actually using Oracle ADF. Do you have any idea how to do it in this framework?
Thanks!
Sa
Column children (e.g. outputText controls) can be used to emit elements with IDs. A TD element represents a table cell - I suggest familiarising yourself with the tables section of the HTML spec. A dedicated Q&A site like stackoverflow.com would be better suited for solving problems like this. | http://illegalargumentexception.blogspot.com/2009/02/jsf-working-with-component-ids.html | CC-MAIN-2017-30 | refinedweb | 2,014 | 55.84 |
I deploy directly from Visual Studio. There isn’t a button in the site collection features to let you enable this.
If you were on-premises, you’d just run Enable-SPFeature:
Enable-SPFeature e374875e-06b6-11e0-b0fa-57f5dfd72085 –url
However, we can’t do that with SharePoint Online as the PowerShell cmdlets don’t expose the ability to turn features on and off. There are a few ways to do this by taking advantage of the Client Side Object Model.
Using PowerShell
One way would be to install the excellent (and free!) SharePoint Client Browser for SharePoint 2010 and 2013. It includes an extremely useful feature to open up PowerShell with the CSOM already loaded.
Using that PowerShell window, you could then easily use the client side object model (CSOM) to enable the developer feature.
$ctx.Load($ctx.Site); $ctx.ExecuteQuery(); $guid = [System.Guid]"e374875e-06b6-11e0-b0fa-57f5dfd72085" $ctx.Site.Features.Add($guid,$true,[Microsoft.SharePoint.Client.FeatureDefinitionScope]::None) $ctx.ExecuteQuery();
Too easy.
Creating an App
Of course, I am lazy and I don’t want to have to dig up that PowerShell code each time I do this. I want to be able to just click a button like I do in the site collection features dialog. I can do that by creating a simple SharePoint hosted app. In Visual Studio, create a new app for SharePoint. Replace the contents of app.js.
'use); }); });
Go to the appmanifest for your app and request Manage permission for the site collection.
Package the app and then add the .app package to the app catalog for your tenant. Now you can go to any site in your tenancy where you are a site collection administrator and add the app. Click on the app to execute the code above, and then optionally uninstall the app from that site so that other users don’t feel compelled to click on it.
Now it’s as simple as add the app, execute it, then uninstall the app. You might add additional capabilities, such as a toggle button to enable/disable the feature, but I’ll leave that as an exercise to the reader.
Excellent post! it is really helpful.
What method should call (instead of Site.Features.Add) if i want to disable a feature instead of enabling?
$ctx.Site.Features.Add($guid,$true,[Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)
Never tried it, but try the Remove method to see if that works for you.
msdn.microsoft.com/…/jj246446(v=office.15).aspx
Kirk,
Very helpful and I appreciate this post; and sad at the same time how difficult Microsoft has made it to develop against SharePoint. Magic Guid values galore, and people having to create tools whose livelihood is purely SharePoint (Bram de Jager — shout out. Great tool.)
great article.
Is there an way to get the names of all the activated features on a particular site collection using an app?
thanks in advance
@gautam – I'm honestly not sure, if you find an answer please do post and let the community know!
Do you know of any way to do this that doesn't require a paid version of Visual Studio? I don't have enough other use to justify buying it, but this would be really valuable functionality.
@Ryan – use PowerShell or use the System.IO.Packaging namespace to package the .app file. I don't have source or a link for you to show how to use System.IO.Packaging, but it can be used with Mono. | https://blogs.msdn.microsoft.com/kaevans/2013/10/05/enabling-the-developer-site-collection-feature-in-sharepoint-online/ | CC-MAIN-2019-43 | refinedweb | 587 | 65.22 |
FREELANCER SITE - repost
This project received 14 bids from talented freelancers with an average bid price of $1957 USD.Get free quotes for a project like this
Skills Required
Project Budget$750 - $1500 USD
Total Bids14
Project Description
I need a provider that have experience in freelancer site. I need the site with the feature from GAF but for music. The site will have many category such as musician search, Gig location, Music distribution, E-commerce online store. The site will have shopping cart such as paypal and authorized.net. The feature will be able to protect both the buyer and provider interest. User can listen to the song, but can not download until get a permission from seller. The site will have 2 language Thai/ English. The site will have the following category below
Bidding like freelancer
Musician search
Gig Location
Music distribution - sent file to itune, emusic
Best voted music
Sell song/ buy song
Become a star
Testimony
News
Event calendar
Best selling song
Agent & broker
Affilate
integrated with myspace, hi5, facebook, twistter
import contact
Classified ad
Hit song of the month
join mailing list
tell a friend
Employment
investor relation
live chat
Dispute | https://www.freelancer.com/projects/PHP-Website-Design/FREELANCER-SITE-repost/ | CC-MAIN-2016-40 | refinedweb | 196 | 58.32 |
Hi,
I'm doing this little program, and i need help.
well, I want to make the calculator program where you can add more than 2 numbers.
example:
Enter your 1st number:
Enter your 2nd number you want to add to 1st number:
the answer is:
do you want to continue? [y]/[n]?
If yes:
Enter your __th/nd/rd number:
Here is where i need help:
how do i program it so that when a user enters yes, it will display the suffix after it, and the number increases after each loop, till termination.
like for the first time, it will be:
Enter your 3rd number:
2nd time it will be:
Enter your 4th number
Enter your 5th number
etc etc.
ive tried doing it, but... i get an error message saying:
Linker error undefined reference to WinMain@16
here's what i've tried:
Code:#include <iostream> #include <stdlib.h> #include <cmath> using namespace std; // Variables: double number1, number2; //variable declared for basic functions double answer = 0; // variable declared for basic functions and initialised double memory; // variable declared for memory functions double value; // variable declared for memory functions double numba; // variables declared for memory functions double binary; // variables declared for binary functions int numberX; int valueX = 3; char additional; //variable declared for loop [basic functions] char clear2; // variable declared for loop [memory function] string suffix; //function for addition //basic void addition() //function start for addition { //basic system("cls"); //clears screen cout << "*------------*\n"; cout << "| Addition |\n"; cout << "*------------*\n"; cout << "Please Enter 1st Value: "; cin >> number1; cout << "Please Enter 2nd Value: "; cin >> number2; cout << "The Answer is: " << number1 << " + " <<number2 << " = " << number1 + number2 <<".\n"; answer = number1 + number2; //adding additional numbers do { //adding additional number loop begins cout << "\n\n"; cout << "Do you want to continue?[y/n]: "; cin >> additional; switch(additional) { //switch begins //If user inputs [y] case 'y': if (valueX%10 == 1) suffix = "st"; else if (valueX%10 == 2) suffix = "nd"; else if (valueX%10 == 3) suffix = "rd"; else suffix = "th"; cout <<"Enter the" << valueX << suffix << "to add onto the answer."; cin >> numberX; cout << "The Answer is: " << answer << " + " << numberX << " = " << answer + numberX <<".\n"; answer = answer + numberX; break; //If user inputs [n] case 'n': system("PAUSE"); cout << "\n"; break; default: //validation cout << "Uh-Oh...You typed something wrong..Please Try again. Thank You ^-^\n"; }}while (additional != 'n'); //loops till 'n' is entered } | https://cboard.cprogramming.com/cplusplus-programming/59108-suffix-help.html | CC-MAIN-2017-30 | refinedweb | 389 | 56.59 |
I run a small contest to see what can be done in five lines of code or less. While all JS can be slapped into one line of code, the point of this is to use actual line breaks as needed but to have your app do as much as possible in those five lines.
There's a few rules that I wont go into as the point of this is to show that you can assign variables inside of an array for use elsewhere.
Take a look at the following code:
setInterval(function() { console.log([s = [86400000, 3600000, 60000, 1000]][0].map(function(t) { return ("0" + [(t===s[0] && (remaining = (future - ~~(+new Date()/1000))*1000)), left = ~~(remaining/t), remaining -= left*t][1]).slice(-2); }).join(':')); }, [1000, future = +new Date()/1000 + 100000][0]);
This really isn't practical for real development use, in fact please don't use it ever outside of code contests. | https://coderwall.com/p/pybueq/need-to-use-less-lines-of-js-assign-variables-inside-arrays | CC-MAIN-2020-29 | refinedweb | 154 | 77.57 |
Thin DSL for creating time scheduling specifications
Project description
A DSL to assist with writing specifications describing intervals and durations of time with filters.
Why the name?
Because time_spec was uninspiring and a good friend suggested timepiece.
Naming things is difficult!
But why?
Because I wanted to represent when scheduled actions should take place and I was starting to have too many columns in my database representing everything I wanted to be able to do.
Installation
Use pip!:
pip install timepiece
Or if you’re developing it:
pip install -e . pip install -e ".[tests]"
Usage
Just create the timepiece and give it a specification!
from timepiece.spec import make_timepiece from datetime import datetime timepiece = make_timepiece() obj = timepiece.time_spec_to_object("between(start: now()) & interval(every: amount(num:1 size: hour))") print("Next time is: ", obj.following(datetime.utcnow()))
See The docs at for more information!
Tests
To run the tests in this project, just use the helpful script:
./test.sh
Or run tox:
tox
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/timepiece/ | CC-MAIN-2019-30 | refinedweb | 189 | 59.6 |
Tutorial: Getting Started with Redux and TypeScript
- 8/15/2016
- ·
- #redux
- #typescript
- #howto
Redux is trending, and a number of applications I’ve encountered recently are built around its central dogma of pure functions and unidirectional dataflow. These projects grow with mixed results, but the ones with the happiest teams attached share certain similarities in their clear delineation between state in actions and stores; their well-documented central store; and the obvious relationships they establish between the store and its reducers.
First, some context. Redux shares a common motivation (and a diminished-but-not-entirely-eliminated volume of boilerplate) with Facebook’s flux architecture, but centralizes application state and adopts a functional approach to managing it. As Redux applications grow, however, a central, organically-evolving store can grow into a big problem.
In a weakly-typed language like JavaScript, it’s not always obvious what certain variables represent. That’s true for even the simplest objects, but take a reasonably complex one–the monolithic store at the heart of a large-ish web application, say–and saddle up those gumshoes for some serious sleuthing.
You already have a large-ish redux application? No problem. Its reducers can be decomposed to specific concerns and gradually extracted to separate applications. But recalling the central role of clarity in developer happiness, the biggest problem may not be the size of the application but simply understanding the shape and provenance of the state inside it.
Over the past few years, the browser-side ecosystem has grown a host of projects focused on improved type-safety for frontend applications. From Flow annotations through typed supersets like TypeScript or entirely new languages like Dart, strong types no longer need to be the second-class citizens of the browser.
Let’s take a look at the patterns that emerge as we formalize the types inside a Redux application. We can somewhat arbitrarily start with TypeScript, but similar approaches carry over to Flow, Dart, or any other flavors of the week. JavaScript works. Redux works with JavaScript. We’re not adding anything except formality–but in the right setting, with visibility on the line, that’s worth something.
If you’re just interested in the results, check out the finished counter over on github. Otherwise, it’s time to get to work.
Setting up
It would hardly be a JavaScript project if it began without at least a few
dependencies. We’ll need the
typescript compiler,
webpack and the
ts-loader for bundling, and
redux for the application itself.
$ npm install -g typescript webpack $ npm install --save-dev redux ts-loader
There’s also some initialization, as we need to tell the typescript compiler about the project:
$ tsc --init message TS6071: Successfully created a tsconfig.json file.
Manually edit
tsconfig.json to enable JSX and include the root typings
definition:
{ "compilerOptions": { "outDir": "./dist/", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "ES5" } }
We’re almost ready to roll. All that’s left is to configure the webpack build.
There’s a detailed guide on this over in the typescript
handbook, but just use the following
webpack.config.js:
module.exports = { entry: './src/index.ts', output: { filename: './dist/bundle.js', }, resolve: { extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'] }, module: { loaders: [{ test: /\.ts$/, loader: 'ts-loader' }] } };
The Counter Application
Phew, setup. Take a quick water-break, catch your breath, and when you’re back we’ll implement a small application. Counters are simple. Let’s do a counter. Press a button, watch a number increase–it’s hardly the definition of excitement, but illustration’s sake it will do.
Note that the webpack configuration above had made a couple of assumptions that we’ll need to meet:
- Files with the
.tsextension will be pushed through TypeScript
- The project will be compiled from the
srcdirectory
In other words, we’ll wind up with a directory structure like this:
├── dist └── src ├── actions │ └── index.ts ├── index.ts └── reducers └── index.ts
Actions
In Redux, actions are events that can update application state. Redux’s default
typings describe actions in terms of a minimal inteface with a
type (what the
action is):
interface Action { type: any }
Since our application will be well aware of each of its actions, however, we can
redeclare
Action as a union of explicit types that each implement redux’s
interface:
export type Action = { type: 'INCREMENT_COUNTER', delta: number, } | { type: 'RESET_COUNTER', } export const incrementCounter = (delta: number): Action => ({ type: 'INCREMENT_COUNTER', delta, }) export const resetCounter = (): Action => ({ type: 'RESET_COUNTER', })
There are several patterns of interest here. Note how:
We’re using
type(rather than
interface) to close
Actionfor extension. It’s done.
Providing a string literal
typefor each action will enable checking (and, critically, narrowing) of possible action types elsewhere in the application. This will prove particularly useful when extracting action contents in our reducers.
Both the
Actiontype and various action creators are declared and exported here. That’s fine for a simple application, but as its complexity increases it may make sense to move the various action creators to separately imported (read: maintained) modules.
Note also that the action creators are declared with more type information than we really need, which will be a recurring theme throughout this project. Even where types can be inferred, full definitions may help improve legibility and clarify intent. They’re a tool, not a hard requirement. If you’ve been here before, just ignore them.
Now that we have something together, let’s pause for just a moment to see TypeScript in action.
Since this code eventually needs to run in a browser, and since browsers know nothing about the strange type annotations now littering our code, the annotations will stick around only long enough for the type-checker to sign off. Let’s compile the action:
$ tsc src/actions/index.ts
We can now find the JavaScript output in
src/actions/index.js:
function (delta) { return ({ type: 'INCREMENT_COUNTER', delta: delta }); };; exports.incrementCounter =
Once our implementation has percolated through the compiler, it arrive back at JavaScript–and likely the same JavaScript we would have written if TypeScript weren’t in the mix at all. Everything added–types, interfaces, casts, and so on? That’s for our benefit.
But that’s just TypeScript. On to the store.
Store
This is why we’re here. Redux relies on a central store; leave it unattended, and the result trends towards an ominous black box. But by preemptively declaring what’s inside, we can avoid the mystery and enlist the type-checker in ensuring that it doesn’t creep back in.
Of course, the store behind our counter isn’t very complex:
export namespace Store { export type Counter = { value: number } export type All = { counter: Counter } }
As with the actions, this structure belies a few deliberate decisions about the store. In particular, note that:
A single, finalized type–
Allin the example above–is exposed to describe the store’s complete structure. When a Redux application shares the store, it shares all of it. In cases where we need less state–the arguments to named reducers, for instance–we may only want a subset of the state. That’s fine; other types within the
Storecan be exposed as needed.
The
Storeoccupies its own namespace, which could live in a top-level
.d.tsdeclaration, or within a module somewhere near the reducers. Both work. It’s likely a good idea to import the
Storewhile starting out to keep dependencies explicit, but as the application grows, it may be convenient to allow global, implicit references to the
Storetype.
All types in the store are declared within its namespace. Even though action payloads and component props may closely resemble data-structures that live within the store, as the application grows it will be clearer to define the store’s state separately from other, transient state within the application.
For all that, we haven’t really added anything new. We’ve just taken the data structures that would already exist inside a Redux application and laid out their shape in formal terms.
“But wait!” you’re thinking. “You haven’t even initialized the store! All we’ve got is a lousy type definition”. And you’re right: though it’s useful to look at its structure now, we won’t be able to implement the store until we’ve written a reducer.
Reducers
Now that we have actions and a store–or at least its shape–we can get ready
to update it. Here’s a simple reducer that will consume the
IncrementCounter action and update the counter accordingly:
import { Action } from '../actions' const initialState: Store.Counter = { value: 0, } function counter (state: Store.Counter = initialState, action: Action): Store.Counter { const { value } = state switch (action.type) { case 'INCREMENT_COUNTER': const newValue = value + action.delta return { value: newValue } case 'RESET_COUNTER': return { value: 0 } } return state }
This is standard Redux. Blink, and you could miss the modicum of type-safety
that we’ve now sprinkled around the edges. We now expect the same type
(
Store.Counter) coming in and going out; we expect an
Action corresponding
to each change, and by switching on the action’s
type TypeScript can determine
the action format and allow us access to its content. This is a powerful
business, as it allows the type system to verify that the action matches a known
type:
case 'INCREMENT': // error: `type 'INCREMENT' is not comparable to type ...` // ...
As an added bonus, once the
type is known, TypeScript can narrow the type
definition to verify access to action contents:
case 'INCREMENT_COUNTER': const { delta } = action // OK! // ... case 'RESET_COUNTER': const { value } = action // error: `Property 'value' does not exist...` // ...
Redux + TypeScript
In any case, we have a complete reducer and we’re finally ready to put it all together. Here’s how it looks:
import { createStore, store as ReduxStore } from 'redux' import { reducers, Store } from './reducers' const store: ReduxStore<Store.All> = createStore(reducers)
Ready to try it out? In
index.ts, let’s set up a store and fire off some
updates:
store.subscribe(() => { console.log(store.getState()) }) store.dispatch(incrementCounter(1)) // { counter: { value: 1 } } store.dispatch(incrementCounter(1)) // { counter: { value: 2 } } store.dispatch(incrementCounter(1)) // { counter: { value: 3 } }
It may not look like much, but from here on out the counter application will be working with statically-checked actions, reducers, and store. So far, we’ve seen structure and definitions of:
an application-specific
Actiongeneric, as well as a pattern for defining actions and their companion action creators that implement it
a shared
Storecontaining the application state
a reducer consuming the actions to populate a portion of the store
Sound a bit like Redux?
TypeScript formalizes patterns already living inside Redux applications | https://rjzaworski.com/2016/08/getting-started-with-redux-and-typescript | CC-MAIN-2019-51 | refinedweb | 1,769 | 54.93 |
Editor’s note: This post was last updated on 30 August 2021 to improve code, images, and any outdated information. However, it may still contain information that is out of date.
A progress bar, sometimes referred to as a progress indicator, is a visual representation of a task’s progress. This can include operations like downloading, file transfers or uploads, installations, program executions, or completed steps in profile setup.
Software with a UX that integrates progress bars lets users know if there are processes running, expected run times, and when portions of work are complete.
Progress bars can be determinate or indeterminate. Determinate progress bars show completed and incomplete data while indeterminate progress bars are used when metrics can’t be immediately determined.
In this article, we will learn how to build a determinate progress bar for React Native.
While there are a few React Native packages for progress bars already, such as
react-native-progress-bar-animated and
react-native-progress, ultimately, it comes down to personal preferences and creating something that you can tweak to meet your requirements.
React Native also has a progress bar component,
ProgressBarAndroid, which is only available for Android. If you want your iOS app to have a progress bar, you must use an existing npm package or build one yourself.
Getting started building the progress bar
This article assumes that you are familiar with React Native or, at the very least, React, and React Hooks.
To get started, use Expo CLI or React Native CLI to bootstrap your project. For the purposes of this article, we will use Snack, which allows us to try React Native directly in a web browser.
We will make our changes in the
App.js file. Let’s clear what we already have and add the following code to
App.js:
import React, { useEffect, useState, useRef } from 'react'; import { Text, View, StyleSheet } from 'react-native'; import Constants from 'expo-constants'; const App = () => { return ( <View style={styles.container}> <Text> We Will Start Here </Text> </View> ); } export default App; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, }, });
This renders the
View component with some text in it. The device simulator should update automatically.
Building the progress bar
Before we start building the progress bar, we must determine what it will look like and what we need to show. A simple progress bar usually has descriptive text, like loading, and the actual bar representing the progress of the operation.
We must also add some text that shows what percentage of the operation is complete. Let’s create the skeleton of our progress bar. In our
App.js, change the text in our
Text component to
<Text> Loading..... </Text>
Styling the React Native progress bar
We want the
Loading..... text to be above the progress bar and the completion percentage below the bar. So, change the container styling to align the child components in a column.
Let’s add the
flexDirection: 'Column' property to our container styles. Below this, add the following styles to a new
styles object called
progressBar:
<View style={styles.container}> <Text> Loading..... </Text> <View style={styles.progressBar}></View> </View> const styles = StyleSheet.create({ container: { flex: 1, flexDirection: "column", //column direction justifyContent: 'center', alignItems: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, }, progressBar: { height: 20, width: '100%', backgroundColor: 'white', borderColor: '#000', borderWidth: 2, borderRadius: 5 } });
To display the current progress of a task’s execution, add a text field with the percentage completion below the progress bar. We can hardcode it at 50% for now:
<View style={styles.container}> <Text> Loading..... </Text> <View style={styles.progressBar}></View> <Text>50%</Text> </View>
Here is what our progress bar should look like so far:
We can now start working on the actual progress bar. By adding a child
View to the
View progress bar container, the child
View shows the percentage of progress. Since we must align the child
View across the horizontal plane, the progress bar container needs the styling property
flexDirection:"Row".
Add this property to the
progressBar styles. In the end, your
progressBar styles should look like this:
progressBar: { height: 20, flexDirection: "row", width: '100%', backgroundColor: 'white', borderColor: '#000', borderWidth: 2, borderRadius: 5 }
Our objective is to have an animated View that will use the
StyleSheet.absoluteFill object. This creates an overlay with position
absolute with zero positioning.
Moreover, we must give the
View a fill color. We’ll use a shade of green and add a width of 50%:
<View style={styles.progressBar}> <Animated.View style={[StyleSheet.absoluteFill], {backgroundColor: "#8BED4F", width: “50%”}}/> </View>
Here, we used the
Animated.View component, meaning this element can perform animations.
Our app now looks like this:
Adding the progress counter
For our progress bar to show changing completion, we must add a counter. The easiest way to do this is by using
setInterval:
const countInterval = useRef(null); const [count, setCount] = useState(0); useEffect(() => { countInterval.current = setInterval(() => setCount((old) => old + 5), 1000); return () => { clearInterval(countInterval); //when user exits, clear this interval. }; }, []);
In this piece of code, we told React to increment the
count Hook by 5 every second. This occurs as soon as the component mounts to the DOM.
How do you animate a progress bar in React Native?
To begin animating our progress bar, we must create an animated value by using the useRef Hook. This will help in animating our loader value:
const loaderValue = useRef(new Animated.Value(0)).current; const load = (count) => { Animated.timing(loaderValue, { toValue: count, //final value duration: 500, //update value in 500 milliseconds useNativeDriver: true, }).start(); };
In this block of code, we used the Animated API to change the value of
loaderValue to
count in half a second. The
Animated.timing() method takes the current value of the animation ref and a configuration object. The animation then runs by calling
start(). Furthermore, we also used the
useNativeDriver property, which provides a smoother user interface.
Next, add the following snippet:
useEffect(() => { load(count) if (count >= 100) { setCount(100); clearInterval(countInterval); } }, [count]);
A few inferences from this code:
- When the value of
countchanges, invoke the
loadmethod to run the animation
- We checked if the
countHook exceeded 100. If this condition is true, React removes this interval and stops incrementing the state variable
Next, set a width for the progress bar by creating an interpolated value from the animation:
const width = animation.current.interpolate({ inputRange: [0, 100], outputRange: ["0%", "100%"], extrapolate: "clamp" })
The
inputRange property represents the range of values that we receive from the progress. The
outputRange defines the range of values that output.
Typically, an interpolation maps input ranges to output ranges using a linear interpolation. By default, it extrapolates the curve beyond the ranges given. To ensure that the output values do not extend beyond the provided range, we pass a property extrapolate
"clamp" to the configuration object.
Now, pass out the interpolated width to the animated progress bar:
<View style={styles.progressBar}> <Animated.View style={[StyleSheet.absoluteFill], {backgroundColor: "#8BED4F", width }}/> </View>
The percentage progress value that we hardcoded earlier must now match the updating progress bar. Since our values range from 0 to 100, let’s construct the text using a template string:
<View style={styles.container}> ... <View style={styles.progressBar}> ... </View> <Text>{`${progress}%`}</Text> </View>
And there we have it; our progress bar is complete!
Find the final product here.
Conclusion
This is by no means a perfect progress bar and there are many improvements that can be made to it, especially regarding animation. To challenge yourself further, you can try uploading a file and displaying the progress.
If you have any questions, comments, or feedback, please let me know. You can find me on Twitter. “Build a React Native progress bar”
Nice, but would be great to see someone try to tackle this with `useNativeDriver`, because otherwise the animation will just be choppy | https://blog.logrocket.com/build-react-native-progress-bar/ | CC-MAIN-2022-05 | refinedweb | 1,310 | 55.95 |
chmod g[+-][rwx]
Andreas Grünbacher is the author of the Extended Attributes (EA) and Access Control Lists (ACL)
code for EXT2/EXT3 filesystems. The homepage is to be found at
acl.bestbits.at. As far as I can tell, meanwhile even
XFS' and JFS' implementations of ACLs are based on Grünbacher's code.
(Please correct me if I'm wrong.)
I'll describe how to get this stuff working on a Debian Woody based machine while trying to stick to DEB-packages as much as possible.
Before you proceed any further: Download and read the ACL section from SUSE's Admin-Guide, linked to from the ACL about page at bestbits.at. It really enhanced my understanding of what is to be used in which way.
Patch a fresh linux-2.4.20 from kernel.org using ea+acl-0.8.56 ():
cd /usr/src/ patch -p0 < ea+acl-2.4.20-0.8.56.diff
Recompile the kernel, using the following options in section "File system":
[*] POSIX Access Control Lists [this option might not work in "make xconfig", use "make menuconfig" if selection isn't possible] [...] <*> [...]
Patch a fresh linux-2.4.21 from kernel.org using ea+acl+nfsacl-2.4.21-0.8.60.diff ():
cd /usr/src/ patch -p0 < ea+acl+nfsacl-2.4.21-0.8.60.diff
Recompile the kernel, using the following options in section "File system":
File systems ---> <*>
If you also want NFS to support ACLs:
File systems ---> Network File Systems ---> <*> NFS file system support [*] Provide NFSv3 client support [*] Solaris ACL RPCs <*> NFS server support [*] Provide NFSv3 server support [*] Solaris ACL RPCs Library routines ---> <*> Quick Sort
I'm sorry, I haven't checked out the NFS options yet. Update as soon as possible.
The patch for 2.4.24 is available and fixes a possible file system corruption bug.
Add option "acl" (and/or "user_xattr") to /etc/fstab:
/dev/md1 / ext3 defaults,acl 0 1
Install the kernel and reboot.
In order to set ACLs on a file/directory, simply install the package "acl" using apt-get. This provides the programs "setfacl" and "getfacl":
Set ACL for "extrauser": setfacl -m u:extrauser:rw acl-file.txt Set ACL for "extragroup", recursive: setfacl -Rm g:extragroup:rwx directory/ Set Default ACL, recursive: setfacl -Rdm g:extragroup:rwx directory/
Oh, and don't forget the man-pages! :)
In order to get the Debian-package fileutils_4.1.8-0.1_i386.deb compiled later on,
first install automake1.6 on a Woody-machine.
As automake1.6 only exists for Debian Sarge and later, use "apt-get source automake1.6" on Sarge machine to get the source, and use "dpkg-buildpackage" afterwards on a Woody machine to get a working automake1.6 package for Woody.
Here is my .deb-file: automake1.6_1.6.3-5_all.deb.
(Mind: it's some time since I've built this stuff and I didn't double check while writing this. If this is not the correct package, please mail me...)
Update -- 2004-02-15:
Debian Sarge's "coreutils" package, which includes "fileutils", features ACL/EA support as of 5.0.90-3. (Thanks to "undefined" for the exact link.)
Patching the package "fileutils" is necessary in order to get a visual indication of ACLs set for files/directories when listing a directory using "ls -l" (the visual indication is a "+" after the access-rights-block) and - even more important - to have ACLs being copied using the command "cp -p". Using the standard-fileutils, the ACLs will be lost after copying the file(s).
My work here is based on stuff I found on the homepage. Many thanks to its creator Philipp Matthias Hahn!
Before continuing: If you want to compile the package yourself, you'll need automake1.6.
I downloaded the files fileutils_4.1.8.orig.tar.gz, fileutils_4.1.8-0.1.diff.gz and fileutils_4.1.8-0.1_i386.changes.
Execute: # tar xzf fileutils_4.1.8.orig.tar.gz # mv fileutils-4.1.8.orig/ fileutils-4.1.8 # gunzip fileutils_4.1.8-0.1.diff.gz # patch -p0 < fileutils_4.1.8-0.1.diff # cd fileutils-4.1.8/ # chmod +x debian/rules Add to lib/acl.c: #ifndef NULL #define NULL 0 #endif Edit aclocal.m4: Change "1.6" to "1.6.3" three times.
Editing aclocal.m4 is necessary in order to have "make" succeed and not exit with an error telling you that the aclocal-version used is 1.6.3 and not the 1.6 which was used previously to build the file aclocal.m4. The "make"-output tells you to run "aclocal" (followed by "make" again), but running "aclocal" seems to break a lot of things ... so just pretend aclocal.m4 was built with the version you have installed (as 1.6.3 is Debian Woody's version).
A "dpkg-buildpackage" might result in "Unmet build dependencies" again, so just install the needed packages.
(In my case, this was apt-get install gettext groff. Two of the most important packages you will need
are "acl-dev" and "attr-dev".)
Run "dpkg-buildpackage" again. If it returns with value "0" (check this by running "echo $?" directly after the program returns), everything should have worked fine and you should be able to install the .deb-file.
So, the only thing left here is to install the package: dpkg -i fileutils_4.1.8-0.1_i386.deb.
Of course, you should test it:
# ls --version ls (fileutils) 4.1.8acl Written by Richard Stallman and David MacKenzie. [...] /tmp# ls -l total 8 -rw-rw-r--+ 1 max max 34 Apr 7 14:35 acl-test.txt /tmp# cp -p acl-test.txt acl-test_COPY.txt /tmp# ls -l total 16 -rw-rw-r--+ 1 max max 34 Apr 7 14:35 acl-test.txt -rw-rw-r--+ 1 max max 34 Apr 7 14:35 acl-test_COPY.txt
You can see the "+", indicating that both files acl-test.txt and its copy have ACLs set.
Here's my .deb-package: fileutils_4.1.8-0.1_i386.deb.
(Mind: it's some time since I've built this stuff and I didn't double check while writing this. If this is not the correct package, please mail me...)
Woody uses version 1.27.
Since version 1.28, the e2fsprogs support ACLs by default, so let's upgrade to a newer version than Woody's: Sarge's 1.32.
On the Sarge-machine, run "apt-get source e2fsprogs" and copy the stuff over to a Debian Woody machine.
On the Woody-machine, run "dpkg-buildpackage" again. (Again, you might have to resolve "Unmet build dependencies", in my case this was "texi2html".)
dpkg-buildpackage creates the following files: -rw-r--r-- 1 root root 39160 Apr 14 14:40 comerr-dev_2.0-1.32-2_i386.deb -rw-r--r-- 1 root root 239358 Apr 14 14:40 e2fsck-static_1.32-2_i386.deb -rw-r--r-- 1 root root 113242 Apr 14 14:40 e2fslibs-dev_1.32-2_i386.deb -rw-r--r-- 1 root root 175944 Apr 14 14:40 e2fsprogs-bf_1.32-2_i386.deb -rw-r--r-- 1 root root 118146 Apr 14 14:40 e2fsprogs-udeb_1.32-2_i386.udeb -rw-r--r-- 1 root root 2102 Apr 14 14:40 e2fsprogs_1.32-2_i386.changes -rw-r--r-- 1 root root 365102 Apr 14 14:40 e2fsprogs_1.32-2_i386.deb -rw-r--r-- 1 root root 13862 Apr 14 14:40 ss-dev_2.0-1.32-2_i386.deb -rw-r--r-- 1 root root 13408 Apr 14 14:40 uuid-dev_1.2-1.32-2_i386.deb
As I had only "e2fsprogs" installed already, this was the only package
I upgraded using "dpkg -i e2fsprogs_1.32-2_i386.deb".
Here's my .deb-package: e2fsprogs_1.32-2_i386.deb.
(Mind: it's some time since I've built this stuff and I didn't double check while writing this. If this is not the correct package, please mail me...)
"star" is a program similar to "tar", but which takes care of ACLs too... just run "apt-get install star".
There is no direct way of correctly backing up your data with your ACLs as most backup software
does not take care of ACLs.
Nevertheless, there's a workaround: Install the Debian package "acl" (if not already done). It provides the programs getfacl and setfacl. These can be used to get the current ACLs respectively change them or set new ones.
getfacl *
setfacl -m u:ursula:rw file1
(Here is the man-page for setfacl.)
Backing up:
Choose whether you want to back up all your system's ACLs to one file, or whether you want several split lists. (I chose to back up ACLs separately for each filesystem, as it should be a bit easier to recover from a fatal system crash). For each directory tree you want to back up, issue a command like the following:
root@t4u:/home # getfacl -R --skip-base . > backup.acl
The `--skip-base' option excludes all files that only have the three base ACL entries (user, group and other). You do not need to back these up separately as the base ACL entries correspond to the file mode permission bits, which I assume your backup utility handles already. The `-R' option tells getfacl to recurse into subdirectories.
Restoring:
The data written to the backup file is the same output you are used to from using getfacl all the time. The setfacl utility is able to parse this output, and restore all the all permissions (including the owner and owning group, if you have privilege to change these). For restoring the backup from above, type:
root@t4u:/home # setfacl --restore=backup.acl
Personal add-on:
The package "acl" also provides "chacl" which is an SGI program in order to change ACLs.
"chacl -l" and "chacl -r" are Linux-only options and might also do something similar to the backup process described above. ( linking to.)
In order to solve problems with NFS using ACLs, you need to apply the nfsacl-patch
available at acl.bestbits.org.
It is for the kernel NFS daemon only.
More info can be found here.
chmod g[+-][rwx]
Bear in mind that, with all ACL-patches and packages in place, the functionality of
chmod g[+-][rwx] changes: For files that have no ACLs set (but
use the normal user/group/others -rights only), running something like
chmod g+w upload-dir/
changes the access rights to allow the group to write to this directory. This is the normal behaviour.
As soon as a file/directory has any ACL(s) set, the behaviour of
chmod g[+-][rwx] changes: The command does not change
the access-rights of the actual group the file belongs to, but it rather changes the "ACL mask" entry.
While it is possible this way to non-intrusively revoke write-access
for all parties at once (except for the user itself)
and re-grant it later on, I definitely would have liked a specific command or option to
setfacl
better in this case: The (IMHO) problem with the implemented behaviour is that it is not possible
to widen access rights with something like
chmod g+w beyond the state the file/directory
had set when the first ACL was added to it. This means that for example directories, that are usually
created "750" and for example have Apache's "www-data" set for the group, can not be changed
by the user via FTP to allow Apache to write into this directory. While this is often used for file-upload
or similar, and with the situation that the users do not have shell-access (but FTP/Web only),
it would be necessary for the user to tell the network admins about their need and for the network admins
to manually run the corresponding
setfacl command to grant Apache write-access. :(
(While the FTP client invokes sth. like
chmod g+w upload-dir/, this only
changes the ACL mask, but it does not change the group's initial "r-x" in any way, resulting in no change
of the access-rights for the group "www-data", effectively. Furthermore, it would not make sense
to create the directory with "770" in the first place, set the mask to "750" and add recursive ACLs
to allow your network's staff-/admin-group full access, as the latter would not have write-access either
because of the "750" mask bits...)
See this thread on the ACL mailing-list for more information.
If you know of a solution to this problem, pleeeze let me know! | http://max.home.subnet.at/fs/ext23_acl.php | CC-MAIN-2018-05 | refinedweb | 2,097 | 65.93 |
I am a new programmer and I'm reading the "Sams Teach Yourself Java in 24 Hours" and I'm doing a chapter on the color class. The program displays two rectangles on blue and on a random color I made and also a string which is red. But when I run it the only thing that comes up is the frame. I'm using NetBeans in linux. Here is the code for a class I named Peach and for a class named eric(I know there dumb names but they are just random names I thought of.) Can someone tell me why it doesn't work. It works in the book but not for me.
Peach class
Code :
import java.awt.*; import javax.swing.*; public class Peach extends JPanel{ public void paintComponet(Graphics g){ super.paintComponent(g); this.setBackground(Color.WHITE); g.setColor(Color.BLUE); g.fillRect(25, 25, 100, 30); g.setColor(new Color(190, 81, 215)); g.fillRect(25, 65, 100, 30); g.setColor(Color.RED); g.drawString("this is text", 25, 120); } }
eric class
Code :
import javax.swing.*; public class eric{ public static void main(String[] args){ JFrame f = new JFrame("Title"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400,250); Peach p = new Peach(); f.add(p); f.setVisible(true); } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/4330-simple-grahpic-porgram-wont-work-printingthethread.html | CC-MAIN-2015-22 | refinedweb | 214 | 68.26 |
Using Amazon Login with Windows Azure Access Control
Using Amazon Login with Windows Azure Access Control
Join the DZone community and get the full member experience.Join For Free
Discover a centralized approach to monitor your virtual infrastructure, on-premise IT environment, and cloud infrastructure – all on a single platform.
One of the services provided by the Windows Azure cloud computing platform is the Windows Azure Access Control Service (ACS). It is a service that provides federated authentication and rules-driven, claims-based authorization. It has some social providers like Microsoft Account, Google Account, Yahoo! and Facebook. But what about the other social identity providers out there? For example the newly introduced Login with Amazon, or LinkedIn? As they are OAuth2 implementations they don’t really fit into ACS.
Meet SocialSTS.com. It’s a service I created which does a protocol conversion and allows integrating ACS with other social identities. Currently it has support for integrating ACS with Twitter, GitHub, LinkedIn, BitBucket, StackExchange and Amazon. Let’s see how this works. There are 2 steps we have to take:
- Link SocialSTS with the social identity provider
- Link our ACS namespace with SocialSTS
Link SocialSTS with the social identity provider
Once an account has been created through, we are presented with a dashboard in which we can configure the social identities. Most of them require that you register your application with them and in turn, you will receive some identifiers which will allow integration.
As you can see, instructions for registering with the social identity provider are listed on the configuration page. For Amazon, we have toregister an application with Amazon and configure the following:
- Name: your application name
- Application return URL:
If we do this, Amazon will give us a client ID and client secret in return, which we can enter in the SocialSTS dashboard.
That’s basically all configuration there is to it. We can now add our Amazon, LinkedIn, Twitter or GitHub login page to Windows Azure Access Control Service!
Link our ACS namespace with SocialSTS
In the Windows Azure Access Control Service management dashboard, we can register SocialSTS as an identity provider. SocialSTS will provide us with a FederationMetadata.xml URL which we can copy into ACS:
We can now save this new identity provider, add some claims transformation rules through the rule groups (important!) and then start using it in our application:
Enjoy! And let me know your thoughts on this service.
Learn how to auto-discover your containers and monitor their performance, capture Docker host and container metrics to allocate host resources, and provision containers. }} | https://dzone.com/articles/using-amazon-login-windows | CC-MAIN-2018-47 | refinedweb | 431 | 52.9 |
?
-- SJS
Hey, SJS. Say, you weren’t by any chance at the Columbia Athletic Club this past weekend, were you? We didn’t think so, but we thought we should ask. On Saturday the Scripting Guy who writes this column and the Scripting Son went to the gym to play basketball. As they stepped inside some stranger began glaring at the Scripting Guy who writes this column, as if to say, “Listen, buddy, there’s no way that both of us are leaving this gym alive.” At first the Scripting Guy who writes this column didn’t pay much attention; having never seen this guy before, he assumed the man must be glaring at someone else. But then the Scripting Son spoke up:
“So Dad: are you gonna fight that guy over there?”
“Well, it kind of looks that way, doesn’t it?”
In fact, the man in question glared at the Scripting Guy who writes this column as he and the Scripting Son checked in, and continued glaring as the two walked through the exercise room and headed for the basketball court.
Yes, very strange. Not that the Scripting Guy who writes this column isn’t used to people glaring at him with looks of utter hatred and disgust; he gets that at work pretty much every day. But it was a bit unusual for someone to glare at him at the gym. At the gym people are much more likely to giggle when he walks by.
And then burst out laughing when he tries doing the bench press.
At any rate, the Scripting Guy who writes this column spent the weekend wondering why a total stranger would glare at him like that. At first he couldn’t come up with any reason. And then he thought, “Hmmm, maybe that guy wanted to know how to do something like, say, filter Outlook email messages by email address. Maybe he wrote to Hey, Scripting Guy! and we haven’t answered him yet. Maybe we should answer his question and see if that makes him happy.”
If you were the angry guy at the gym, SJS, we hope this helps, and we apologize for taking so long to get around to your question. And if you weren’t the angry guy at the gym, well, do us a favor, OK: if you happen to run into the crazy guy, please don’t tell him that we answered your question instead of his?
Here’s how you (or the angry guy, for that matter) can filter Outlook email messages by email address:("[SenderEmailAddress] = 'kenmyer@fabrikam.com'")
For Each objMessage In colFilteredItems
Wscript.Echo objMessage.Subject
Whoa, don’t look at us like that; we were just about to explain how the script works. (Really.) We start out by defining a constant named olFolderInbox and setting the value to 6; that tells the script which Outlook folder (in this case the Inbox folder) we want to work with. Next we create an instance of the Outlook.Application object and bind to the MAPI namespace. We then use this line of code and the GetDefaultFolder method to make a connection to the Inbox folder:
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)
Now for the good stuff. The first thing we do is use this line of code to return a collection of all the items (that is, all the email messages) found in the Inbox folder:
Set colItems = objFolder.Items
And you’re right: we don’t want all the items in the Inbox, do we? Instead, we want only those emails that were sent by kenmyer@fabrikam.com. That’s what this line of code is for:
Set colFilteredItems = colItems.Restrict("[SenderEmailAddress] = 'kenmyer@fabrikam.com'")
All we’re doing here just grabbing a subset of the items found in the Inbox. To do that we call the Restrict method, passing the method two parameters:
Ah, that’s a good question: can we include multiple criteria in a filter? You bet we can. For example, here’s a filter that returns emails sent by kenmyer@fabrikam.com or by packerman@contoso.com:
Set colFilteredItems = colItems.Restrict _
("[SenderEmailAddress] = 'kenmyer@fabrikam.com' OR [SenderEmailAddress] = 'packerman@contoso.com'")
One thing to keep in mind here is the fact that, because we are dealing with email addresses, Outlook security might kick in when we run this script. That means that a dialog box might pop up telling us that someone (or something) is trying to access email addresses; in turn, we’ll have to use that dialog box to explicitly grant the script access to the data. For more information, see our original article on filtering email messages.
After applying the filter we then set up a For Each loop to walk through all the items in the filtered collection. In this sample script all we do is echo back the value of the Subject property; however, you can echo back the value of any (or all) of the properties of the MailItem object.
And there you have it, SJS: that should be enough to put a smile on anyone’s face.
We hope.
Speaking of which, the trip to the gym turned out to be somewhat anticlimactic: by the time the Scripting Guy and Scripting Son finished playing basketball the angry man had left the building. Was the Scripting Guy who writes this column shaken by this experience? What, are you kidding? The Scripting Guy who writes this column doesn’t know the meaning of the word fear.
It’s just a coincidence that he sent the Scripting Son out to start the car.
thanks
Just read your article on filtering email, but what I more interested in is filtering by domain or even IP addresses to reduce or even stop spam. Understanding that spammer uses many different email addresses, they can usually get around filters by simply spamming with a different prefix; example changing Joeblow@whatever.com to Joeblo@whatever.com would bypass any filter I may have set to stop Joeblow, thus making it necessary to create another filter for Joeblo. I would much rather block his entire domain, thus any pefix used by him would get trapped by my filter. What suggestions if would you recommend to achieve this?
Hey, i want to highlight the filtered ones in yellow and more over executing the above ends like object required for Wscript. Please help | https://blogs.technet.microsoft.com/heyscriptingguy/2007/04/10/how-can-i-filter-outlook-messages-by-email-address/ | CC-MAIN-2018-26 | refinedweb | 1,068 | 71.14 |
Created on 2018-07-23 12:09 by chetankolhe, last changed 2020-09-20 22:37 by iritkatriel.
Hi,
Currently, there is no support for whether the logger object is present or not.
when logging module imported in current namespace all logger object get imported. which uses the memory.
Add the option explicitly to delete the logger object.
e.g logging.deletLoger("name for logger object")
This seems related :
Hi
Loggers are static objects managed by the module itself. When you create one, it won't be removed until you leave the shell
all logger instance is stored in this location.
"Logger.manager.loggerDict" which is the dictionary.
we can delete logger instance using that dictionary.
so why don't we give the support for deleting the logger object?
Scenario:-
I am writing the one Django project which consists produce the number of logger object depending on the requirement to store the log properly. Currently, I am using "Logger.manager.loggerDict" to delete unnecessary logger object using this dictionary. Currently, i have written code which deletes the parent to child logger object depending on their name. Storing those unrequired logger object in the current namespace is better to delete the logger object explicitly. | https://bugs.python.org/issue34199 | CC-MAIN-2021-21 | refinedweb | 203 | 58.79 |
I
A lot of work has happened since the Beta 1 towards bringing Qt 5 closer to a final release. One of the biggest differences is that this Qt 5.0 release includes not only the Qt libraries, but also the tools. Qt Creator 2.6 based on Qt 5.0 is now bundled together with Qt 5.0 to make it a full complete release. It also helps us in testing and verifying the quality of Qt 5.
This release will only support Qt 5.0, but we will later examine whether and how we can add Qt 4.x support to it.
In addition, it shows that Qt 5 is a good and mature release with a very high degree of compatibility with Qt 4.x. Qt Creator can currently be built both against Qt 4.8 and 5.0 from a single code base. This proves that Qt 5.0 is almost fully source-compatible with Qt 4.8..
Woohoo !
That’s AMAZING!!!!!!!!!!!!!! Qt is the future!!!!
Yay
A little request to all who find issues with the Qt Creator that is included in this release: In your bugreports on bugreports.qt-project.org, please state in the Environment field that this is the Qt Creator bundled with the Qt5 beta2 release. So we have a hint if issues might be related to Qt5 or not
Another beta instead of the scheduled final release? Also, any word on MSVC2012 compatibility?
Not Tier 1 as of now:
Happy beta release day everyone !
btw is there a livestream to the ongoing conferences ?
Btw the links were broken so i had to download from here:
Nice, but where did Qt3D go?
yeah this is good question, where did Qt3D go?
It moved to playground:
So Qt3D along with sensors, location, all of which pretty much vital for modern app development are being removed from Qt5 just because Nokia kicked out their maintainers and Digia has not figured out those people should be hired back?
I guess nobody will stop _you_ from hiring these people.
Great! No Winx64? Hmm, have to compile 32-bit until final release then….
I want compiled win64 VC++ version of QT5 too…
Uber cool, it doesn’t work.
QtCreator didn’t detect MSVC 2010 compiler
Congratulations with the release!
@Kaoxyd
Did you check the known issues page? It mentions a workaround for an issue when using “Visual Studio C++ 2010 Express on Windows 7 64 bit”.
Yep, but still not work. When i want to compile, Qtcreator say : “:-1: erreur : Qt Creator needs a compiler set up to build. Configure a compiler in the kit options.”
Does it include mingw (4.7?) that permit to build project under windows without msvc10?
Is msvc express compatible with this release or we need the pro version?
In the future, when Qt 4.8.x will be added, will be added a compatible version of mingw as well?
For now, if i would like to compile with mingw 4.7, I need to download Qt sources(4.8 or 5) and compile it myself, is right?
I read that TDM GCC can be used:
But is not clear to me if is ok the 64 bit version or if it include a qtcreator compatible, phyton enable, gdb!
Another doubt is how to compile a single Qt tree for release and debug version of the libraries (with the appended “d” at the end of lib file) tha can link automatically the right version when I build a .pro project in release or in debug.
I now…too much questions…but I don’t know how will be the appropriate setup for the near future….
With the Beta only MSVC binaries are provided. You should be able to compile the beta with MinGW on your own though except for the qtwebkit module, which fails to compile right now on MinGw. But if you don’t need that you should be fine … Debug and Release versions of the libs should be automatically generated if you configure with -debug-and-release (default on Windows).
Is Qt 5 even compatible with MinGW 4.7? I hope that it is at least compatible with MinGW 4.6.2…
BTW How long would it take to compile Qt 5 on something like Core i5 and 4Gb RAM?
I’d recommend a recent mingw-w64 based toolchain with at least gcc 4.7. I’m using mingw-builds personally … from time to time I also compile with latest mingw.org (gcc 4.7.0), also works (except webkit and angle). What matters actually is not so much the compiler version, but the Windows API that is covered, which is also why you should use mingw-w64 instead of mingw.org.
If you want to compile all of Qt 5, do it over night 😉 mingw32-make -j still has problems sometimes, AFAIK …
I compile Qt 4.8.3 on Linux with an asus eeepc 900a, take me about one night. :-DDD
I don’t need webkit for now but I hope the problem will be fixed.
Ok, thank you, so if i go with the default “-debug-and-release” on “make install” I can expect the generation of a *single* Qt libs tree with the debug libraries filename with the leading “d” and iin qtcreator the appropriate files are linked for debug and release right? And under Linux?
Under Linux, in Qt-4.8.3 “./configure –help” command show the default to “release” and the option “-debug-and-release” is marked “Mac Only”
So I don’t know how to generate a single tree with release and debug version to have “switchable” linking from debug to release when i build project.
Note that for Linux the link on the download page does not privide any precompiled version but piunt simply to the source package…
Should I use the same -prefix of the release build for the debug build and use the following configure option?
-qtlibinfix d
Does it include mingw (4.7?) that permit to build project under windows without msvc10? => Nope
Is msvc express compatible with this release or we need the pro version? => Yes it is, it’s include with QT 5 libs
For now, if i would like to compile with mingw 4.7, I need to download Qt sources(4.8 or 5) and compile it myself, is right? => Yes
For the other questions, I don’t have answers
Thank you for answers.
I really hope the next bundle will include binary of Qt 4.8 and Qt5 for both msvc and mingw 4.7 and that the used version of mingw will be included (better if the one that can build both 32 and 64 bit).
Otherwise I think that will be not exactly a negligible effort to compile ourself each time, including the high number of options and parameters for Qt and different compiler version and so on.
I have found a Python enable gdb binaries here:
…
But I’m always in doubt about MinGW versions I can use for both the last 4.8 and 5.
It is a Visual C++ version… 😉
I really find it strange why would Qt be priority on VC++
Me too…
Because it’s good, and it works. The VC++ user-interface alternatives have issues.
Excuse me, this is not clear to me: is mingw not “good”? If is this the case for what reason?
And can you briefly explain some issues you spoke about?
Just for better understand your comment.
I wanted to foollw along and let you know how great I valued discovering your website today. I’d consider it a good honor to work at my place of work and be able to make real use of the tips contributed on your website and also take part in visitors’ comments like this. Should a position involving guest article writer become on offer at your end, make sure you let me know.
Congrats on getting this beta out.
Quick question – is it still the plan to reintroduce QT 3D in the 5.1 release?
Kind regards
Yes. And Qt3D is not dissappearing for 5.0 users either, its just not bundled in the package. It is available for 4.8 and can be used with 5.0 as well. It is an important module, and we want to have it properly maintained, developed further and into 5.1.
. It is available for 4.8 and can be used with 5.0 as well.
——————
I doubt it! You can’t run any examples with Angle on Windows now. So, It’s fully broken on Windows, and I have to give up.
If it’s only angle, configure Qt with ‘-opengl desktop’.
If that’s the case it should be easily fixable, Qt3D is designed to support both OpenGL ES 2 and desktop OpenGL.
“It is an important module, and we want to have it properly maintained, developed further and into 5.1.”
Excellent, thank you.
I’d be delighted to see Qt 3D become a core and maintained module in 5.1, in time for adoption into KDE.
Kind regards
i think, that’s very sad that qt3d isn’t part qt5 anymore…
Furthermore i tried to build the master-tree of qt3d with qt5beta2 in the qtcreator2. I just opened the project file in the qt3d directory with QtCreator and built it. But after building i can’t open the qt3d examples, it always displays that qtquick3d.dll is missing and another problem is, that i can’t import qt3d to QML. I tried qmlRegisterType but it didn’t help.
Can someone help me and give me a hint how to build the qt3d properly?
Best regards and sorry for missplacing this issue here.
Let’s do the Qt4 dance !
Where’s the old open source self-updating SDK?
I was using the old one and it looks like it’s gone. Bring it back, please.
Fantastic. I really do hope the final release comes with gcc 4.7 support out of the box. That would be so helpful.
Yeah
This is great news! I’m excited to try Qt Creator based on Qt 5.
I did notice with beta2 one thing that has broken is the availability of the qmake $$PWD variable. I was using this variable, together with .qmake.cache, on my project to copy include header files as the first step in my build. I got around the issue by using $$_PRO_FILE_PWD_ instead.
One other comment: I noticed the Qt Creator bundled with this release uses a KDE-like style on my Ubuntu machine. Is there by chance an easy workaround for this?
fonzi337, could you file bugs for both things you mentioned ($$PWD and KDE-like style on Ubuntu) on ? Just mention that this is a problem in the Qt 5 beta 2 package … Thanks.
Sure Kai, I have filed them here () and here ().
Hello!
I tried to build my software with the qt 5 beta 2. But it doesn’t found the QSqlDatabase. But this is a module of the Essentials modules isn’t it? Do i have to rebuild from source to get this feature?
-Max
When Will be ready the Mingw version of qt5 beta2?
When somebody is so nice to do it :). I am not doing it. I am afraid to try it. I’ve tried it once and it failed… so now I am in the waiting game too.
Why doesn’t this release include the QML WebView, i really need it for an app which uses oAuth, and I though it would be in the release, since it is a ‘as complete as final’ release, at least in the number of modules point of view…
So how can I have a Webkit integration into my QML2 app ?
Which package are you using ?
import QtWebKit 3.0
WebView {
}
works for me .
I met a problem with qmake on Ubuntu 12.04. The qmake program from the 5.0.0 beta 2 produces Makefile with -lGL instead of -lQtOpenGL. Could anyone check it??
It seems the qml2puppet is still not present in Qt Creator 2.6. I cant find a way to use the QML Designer in QtC. Is this just me or this is a mayor setback for QML ?
I’m having the same issue with the QML designer. I get 2 pop up boxes one saying that it can’t find qml2puppet in the bin folder and the second saying the qt version is not supported…
It may be actually unsupported by Qt Creator yet
Eike Ziller says:
November 12, 2012 at 12:00
Qt Quick Designer doesn’t support Qt Quick 2 (yet). The qml code editor in Qt Creator 2.6 does.
Are there any plans on a fix in close future? It’s quite limiting right now as I want to have use of the new QT Quick 2 after been inspired by the Conference in Berlin but also the designer….
Would be nice if you make QtSDK installer to support both 32 & 64 bit in one installation.
This would almost double the size of the installer executable. Just install them side by side.
Not present and not mentionned: what about QtHelp? (which I use for embedded doc).
Does not compile well on Windows 7 x64 + VS2010.
I execute configure.bat and I get this error:
d:\Qt500b2_x64>configure.bat
+ d:/Qt500b2_x64/qtbase/configure
“d:\Qt500b2_x64\qtbase\\configure.exe” no se reconoce como un comando interno o
externo, programa o archivo por lotes ejecutable.
*** qtbase/configure exited with non-zero status.
See known issues. Workaround is to create a file “.gitignore” in qtbase directory.
thx a lot :p
Just read about new features in Qt 5: after a year or so with it, I’m more and more happy with this framework!
A question… does the Beta 2 support VS2010 plugin? The 1.1.11 gives me a “This Qt version uses an unsupported makefile genrator ( used: , supported: MSVC.NET, MSBUILD )”
Thank you for that =) It’s very important to me!
anyone knows how to cross compile to raspberry pi (from windows or linux)? and any raspberry pi image (that works) with this version? thanks!
@lolo
So far VS2010 addin 1.1.11 works for me (using QTDIR including qtbase).
Is the Qt Multimedia Widgets module part of the release too?
@lolo
Same problem here, using qtaddin 1.2 beta, with vs2010 sp1
@Philippe
What do you mean using QTDIR including qtbase?
Qt Qml, Qt Quick, Qt Declarative…Three modules around (i think) the same technology: which are the differences between these packages (who does what)?
Qt Declarative contains Qt Quick 1.0, Qt Quick contains Qt Quick 2.0.
I’m not very sure how Qt QML fits into the picture, but you can have a look at:
QtQml – Qt Quick 2, infrastructure (non GUI)
QtQuick – Qt Quick 2, GUI items
QtDeclarative – Qt Quick 1 compatibility module (to allow easy porting of Qt 4.x applications)
Thanks!
@Emanuele:
When running Visual Studio, the system varialbe QTDIR must be properly set. In my case, this is:
C:\Qt\5.0.0\qtbase
Also, the following registry keys must be properly set at:
HKEY_CURRENT_USER\Software\Trolltech\Versions\
BTW, where do you get qtaddin 1.2 beta ?
@Philippe
Qt 5.0 Beta 2 is nice to have, but where is Qt 4.8.4 that is supposed to fix the nasty Drag&Drop regression (Windows) introduced in Qt 4.8.3? I hope the devs won’t forget to fix Qt 4.8 while finalizing Qt 5. Qt 4.8 will be used in production for quite some time…
Not to worry
Ahhh, good to hear
WARNING(!)
1. QtCreator 2.6 contained in this package (based on qt5) has not working CDB debugger. There are not any messages on informative error codes. Only “Debug starting… Debug error.” in output pane.
2. Also for correct compiling of ANY project (old or just created with the wizards provided) at least, we need set MSVC environment before starting qtcreator.exe (all previous version didn’t needed it at all).
All of these was tested on Windows 7 x86 platform with correctly installed “Debugging Tools for Windows (x86)” and “Microsoft Windows SDK 7.1”. Before installing “qt5 beta 2” package all was accuratly cleaned after previous versions of qt.
After installing common build of “QtCreator v2.6” (bases on 4.8.3), downloaded from common link, provided on main download page ( ) — ALL WORK FINE!.
So it looks like as regressions in qtcreator that built with qt5 libraries… It seems that as was said in the site news, QtCreator 2.6 based on qt5 is only for wondering how Qt Creator 2.6 runs on Qt 5….
Hi Vasily, there’s indeed a problem with the creator shipped and CDB debugging. Workaround is to rename “Tools\Qt Creator” to “Tools\QtCreator” (see also Known Issues). You’re also right that the MSVC toolchain has to be registered by hand if cl.exe isn’t found in the path.
That aside, this is a Beta package, mainly for getting feedback. So bear with us if some things to not always work out of the box.
Oк, i understand that it’s “beta” yet, it was just my report and notice about the issue…
This real issue is fixed now (change 7b000a056).
I would like to signal a possible problem in the Qt-5beta2 build procedure.
I’m building Qt-5beta2 with MinGW 4.6
configure -prefix %CD%\qtbase -debug-and-release -opensource -openssl -icu -no-sse2 -qt-pcre -qt-style-windowsce -qt-style-windowsmobile -nomake tests -platform win32-g++
First problem:
___________
I needed to add -no-sse2 due to a not find header file intrin.h : this file is not present in the MS Platform SDK, neither in MinGW includes. (anyway, if i well understand the MS SDK must be not used for MinGW builds).
Second problem:
______________
After the “configure” procedure, some of the Makefile.release and Makefile.debug, (in particular those for the
following project: moc rcc doc uic) are generate with duplicated -L[…] entry and the second have the “” removed!
##################
LIBS =
##################
PLEASE NOTE that my environment for the LIB variable ALREADY INCLUDE “” around path containing space!
#################
LIB=C:\Qt\mingw32-qtproject\lib;”C:\Program Files\Microsoft Platform SDK\Lib\.”;”C:\Program Files\Microsoft DirectX SDK (June 2010)\Lib\x86″;C:\Qt\OpenSSL-Win32\lib;C:\Qt\icu\lib
##################
I know, paths is better when do not contain spaces, but those are MS defaults and need to work!
Better willl be if modified duplicated -L[…] are not added, and also better will be if I do not need
to add “” in my LIB variable.
I modified files by hand adding “” aroeund the duplicated entry and now is compiling….
Bye, Fabio.
Ah!
“Obiovusly” the problem is that with -L[…] entry(s) not between “” and containing space,
the mingw32-make command exit with an error, for example:\rcc.o rcc.cpp\main.o main.cpp
g++ -Wl,-s -Wl,-subsystem,console -o ..\..\..\bin\rcc.exe tmp/obj/release_shared/rcc.o tmp/obj/release_shared/main.o
g++: error: Files\Microsoft: No such file or directory
g++: error: Platform: No such file or directory
g++: error: SDK\Lib\.: No such file or directory
g++: error: Files\Microsoft: No such file or directory
g++: error: DirectX: No such file or directory
g++: error: SDK: No such file or directory
g++: error: (June: No such file or directory
g++: error: 2010)\Lib\x86: No such file or directory
mingw32-make[5]: *** [..\..\..\bin\rcc.exe] Error 1
mingw32-make[5]: Leaving directory `C:/Qt/qt-everywhere-opensource-src-5.0.0-beta2/qtbase/src/tools/rcc’
mingw32-make[4]: *** [release] Error 2
mingw32-make[4]: Leaving directory `C:/Qt/qt-everywhere-opensource-src-5.0.0-beta2/qtbase/src/tools/rcc’
mingw32-make[3]: *** [sub-rcc-make_first] Error 2
mingw32-make[3]: Leaving directory `C:/Qt/qt-everywhere-opensource-src-5.0.0-beta2/qtbase/src/tools’
mingw32-make[2]: *** [sub-tools-make_first] Error 2
mingw32-make[2]: Leaving directory `C:/Qt/qt-everywhere-opensource-src-5.0.0-beta2/qtbase/src’
mingw32-make[1]: *** [sub-src-make_first] Error 2
mingw32-make[1]: Leaving directory `C:/Qt/qt-everywhere-opensource-src-5.0.0-beta2/qtbase’
mingw32-make: *** [module-qtbase-make_first] Error 2
I WAS compiling… :-((((((
In file included from ..\..\..\3rdparty\angle\src/libEGL/Display.h:25:0,
from ..\..\..\3rdparty\angle\src/libGLESv2/Blit.h:21,
from ..\..\..\3rdparty\angle\src\libGLESv2\Blit.cpp:9:
..\..\..\3rdparty\angle\src/libEGL/Config.h:97:5: error: a class-key must be used when declaring a friend
..\..\..\3rdparty\angle\src/libEGL/Config.h:97:5: error: friend declaration does not name a class or function
cc1plus.exe: warning: unrecognized command line option “-Wno-delete-non-virtual-dtor” [enabled by default]
cc1plus.exe: warning: unrecognized command line option “-Wno-maybe-uninitialized” [enabled by default]
cc1plus.exe: warning: unrecognized command line option “-Wno-narrowing” [enabled by default]
mingw32-make[6]: *** [tmp/obj/release_shared/Blit.o] Error 1
No luck.
In first time I added to configure command “-no-angle -no-opengl”
..\..\..\3rdparty\angle\src/libEGL/Config.h:97:5: error: a class-key must be used when declaring a friend
..\..\..\3rdparty\angle\src/libEGL/Config.h:97:5: error: friend declaration does not name a class or function)
Then I added -no-sse2 as well but another error that now i’ve lost regardig the definition of BYTE_MUL_SSE2 macro raised.
Then the last configure parameters i tryied included all the following:
-no-sse2 -no-sse3 -no-ssse3 -no-sse4.1 -no-sse4.2 -no-avx -no-avx2 -no-angle -no-opengl
Complete:
configure -prefix %CD%\qtbase -debug-and-release -opensource -openssl -icu -no-sse2 -no-sse3 -no-ssse3 -no-sse4.1 -no-sse4.2 -no-avx -no-avx2 -no-angle -no-opengl -qt-pcre -qt-style-windowsce -qt-style-windowsmobile -nomake tests -platform win32-g++
But this, another time, raise an error:
kernel\qplatformopenglcontext.cpp:87:5: error: ‘QOpenGLContext’ does not name a type
kernel\qplatformopenglcontext.cpp: In constructor ‘QPlatformOpenGLContextPrivate::QPlatformOpenGLContextPrivate()’:
kernel\qplatformopenglcontext.cpp:85:39: error: class ‘QPlatformOpenGLContextPrivate’ does not have any field named ‘context’
kernel\qplatformopenglcontext.cpp: At global scope:
kernel\qplatformopenglcontext.cpp:90:1: error: ‘QPlatformOpenGLContext’ does not name a type
kernel\qplatformopenglcontext.cpp:95:1: error: ‘QPlatformOpenGLContext’ does not name a type
kernel\qplatformopenglcontext.cpp:104:1: error: ‘GLuint’ does not name a type
kernel\qplatformopenglcontext.cpp:109:1: error: ‘QOpenGLContext’ does not name a type
kernel\qplatformopenglcontext.cpp:115:6: error: ‘QPlatformOpenGLContext’ has not been declared
kernel\qplatformopenglcontext.cpp:115:41: error: variable or field ‘setContext’ declared void
kernel\qplatformopenglcontext.cpp:115:41: error: ‘QOpenGLContext’ was not declared in this scope
kernel\qplatformopenglcontext.cpp:115:57: error: ‘context’ was not declared in this scope
kernel\qplatformopenglcontext.cpp:121:6: error: ‘QPlatformOpenGLContext’ has not been declared
mingw32-make[4]: *** [tmp/obj/debug_shared/qplatformopenglcontext.o] Error 1
For each attempt I edited the Makefile.[debug|relese] for moc rcc doc and uic projects.
For now I drop by the wayside. Suggestion are welcome.
Failed to build Qt5.0 beta2. I need some hints what’s wrong (or reminds that it’s only beta
)
Platform is Windows 7 x86 with “Microsoft Windows SDK 7.1″. All setting are according to except configuring with “-debug-and-release” flags in configure.exe (also tried “-release”).
Here is my bat-file:
PATH=c:\Program Files\Microsoft Visual Studio 10.0\VC\bin;%PATH%
call "c:\Program Files\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat"
set QTDIR=
set PATH=c:\Python27\;c:\Perl\bin\;%CD%\qtbase\bin;%CD%\qtrepotools\bin;%PATH%
set QMAKESPEC=win32-msvc2010
set CL=/MP
configure -prefix %CD%\qtbase -debug-and-release -static -opensource -confirm-license -nomake examples -nomake tests -no-icu -opengl desktop -platform win32-msvc2010
nmake
And here is log with build errors:
qdesigner_toolwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QDesignerPropertyEditorInterface * __cdecl QDesignerComponents::createPropertyEditor(class DesignerFormEditorInterface *,class QWidget *)" (__imp_?createPropertyEditor@QDesignerComponents@@SAPAVQDesignerPropertyEditorInterface@@PAVQDesignerFormEditorInterface@@PAVQWidget@@@Z) referenced in function "class QWidget * __cdecl createPropertyEditor(class QDesignerFormEditorInterface *,class QWidget *)" (?createPropertyEditor@@YAPAVQWidget@@PAVQDesignerFormEditorInterface@@PAV1@@Z) qdesigner_toolwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QDesignerActionEditorInterface * __cdecl QDesignerComponents::createActionEditor(class QDesignerFormEditorInterface *,class QWidget *)" (__imp_?createActionEditor@QDesignerComponents@@SAPAVQDesignerActionEditorInterface@@PAVQDesignerFormEditorInterface@@PAVQWidget@@@Z) referenced in function "class QWidget * __cdecl createActionEditor(class QDesignerFormEditorInterface *,class QWidget *)" (?createActionEditor@@YAPAVQWidget@@PAVQDesignerFormEditorInterface@@PAV1@@Z)
qdesigner_toolwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QDesignerObjectInspectorInterface * __cdecl QDesignerComponents::createObjectInspector(class QDesignerFormEditorInterface *,class QWidget *)" (__imp_?createObjectInspector@QDesignerComponents@@SAPAVQDesignerObjectInspectorInterface@@PAVQDesignerFormEditorInterface@@PAVQWidget@@@Z) referenced in function "class QWidget * __cdecl createObjectInspector(class QDesignerFormEditorInterface *,class QWidget *)" (?createObjectInspector@@YAPAVQWidget@@PAVQDesignerFormEditorInterface@@PAV1@@Z)
qdesigner_toolwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QDesignerWidgetBoxInterface * __cdecl QDesignerComponents::createWidgetBox(class QDesignerFormEditorInterface *,class QWidget *)" (__imp_?createWidgetBox@QDesignerComponents@@SAPAVQDesignerWidgetBoxInterface@@PAVQDesignerFormEditorInterface@@PAVQWidget@@@Z) referenced in function "class QWidget * __cdecl createWidgetBox(class QDesignerFormEditorInterface *,class QWidget *)" (?createWidgetBox@@YAPAVQWidget@@PAVQDesignerFormE
ditorInterface@@PAV1@@Z) qdesigner_toolwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QWidget * __cdecl QDesignerComponents::createResourceEditor(class QDesignerFormEditorInterface *,class QWidget *)" (__imp_?createResourceEditor@QDesignerComponents@@SAPAVQWidget@@PAVQDesignerFormEditorInterface@@PAV2@@Z) referenced in function "public: __thiscall ResourceEditorToolWindow::ResourceEditorToolWindow(class QDesignerWorkbench *)" (??0ResourceEditorToolWindow@@QAE@PAVQDesignerWorkbench@@@Z)
qdesigner_toolwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QWidget * __cdecl QDesignerComponents::createSignalSlotEditor(class QDesignerFormEditorInterface *,class QWidget *)" (__imp_?createSignalSlotEditor@QDesignerComponents@@SAPAVQWidget@@PAVQDesignerFormEditorInterface@@PAV2@@Z) referenced in function "public: __thiscall SignalSlotEditorToolWindow::SignalSlotEditorToolWindow(class QDesignerWorkbench *)" (??0SignalSlotEditorToolWindow@@QAE@PAVQDesignerWorkbench@@@Z)
qdesigner_workbench.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static void __cdecl QDesignerComponents::initializePlugins(class QDesignerFormEditorInterface *)" (__imp_?initializePlugins@QDesignerComponents@@SAXPAVQDesignerFormEditorInterface@@Object * __cdecl QDesignerComponents::createTaskMenu(class QDesignerFormEditorInterface *,class QObject *)" (__imp_?createTaskMenu@QDesignerComponents@@SAPAVQObject@@PAVQDesignerFormEditorInterface@@PAV2@DesignerFormEditorInterface * __cdecl QDesignerComponents::createFormEditor(class QObject *)" (__imp_?createFormEditor@QDesignerComponents@@SAPAVQDesignerFormEditorInterface@@PAVQObject@@@Z) referenced in function "public: __thiscall QDesignerWorkbench::QDesignerWorkbench(void)" (??0QDesigne
rWorkbench@@QAE@XZ) qdesigner_actions.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static struct QMetaObject const qdesigner_internal::QDesignerFormWindowManager::staticMetaObject" (__imp_?staticMetaObject@QDesignerFormWindowManager@qdesigner_internal@@2UQMetaObject@@B) referenced in function "class qdesigner_internal::QDesignerFormWindowManager * __cdecl qobject_cast(class QObject *)" (??$qobject_cast@PAVQDesignerFormWindowManager@qdesigner_internal@@@@YAPAVQDesignerFormWindowManager@qdesigner_internal@@PAVQObject@@@Z) qdesigner_actions.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static bool __cdecl qdesigner_internal::CodeDialog::showCodeDialog(class QDesignerFormWindowInterface const *,class QWidget *,class QString *)" (__imp_?showCodeDialog@CodeDi
alog@qdesigner_internal@@SA_NPBVQDesignerFormWindowInterface@@PAVQWidget@@PAVQString@@@Z) referenced in function "private: void __thiscall QDesignerActions::viewCode(void)" (?viewCode@QDesignerActions@@AAEXXZ) newform.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QImage __cdecl qdesigner_internal::NewFormWidget::grabForm(class QDesignerFormEditorInterface *,class QIODevice &,class QString const &,class qdesigner_internal::DevicePr
ofile const &)" (__imp_?grabForm@NewFormWidget@qdesigner_internal@@SA?AVQImage@@PAVQDesignerFormEditorInterface@@AAVQIODevice@@ABVQString@@ABVDeviceProfile@2@@Z) referenced in function "public: static class QImage __cdecl NewForm::grabForm(class QDesignerFormEditorInterface *,class QIODevice &,class QString const &,class qdesigner_internal::DeviceProfile const &)" (?grabForm@NewForm@@SA?AVQImage@@PAVQD
esignerFormEditorInterface@@AAVQIODevice@@ABVQString@@ABVDeviceProfile@qdesigner_internal@@@Z)
newform.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QDesignerNewFormWidgetInterface * _
_cdecl QDesignerNewFormWidgetInterface::createNewFormWidget(class QDesignerFormEditorInterface *,class QWidget *)" (__imp_?createNewFormWidget@QDesignerNewFormWidgetInterface@@SAPAV1@PAVQDesignerFormEditorInterface@@PAVQWidget@@@Z) referenced in function "public: __this
call NewForm::NewForm(class QDesignerWorkbench *,class QWidget *,class QString const &)" (??0NewForm@@QAE@PAVQDesignerWorkbench@@PAVQWi
dget@@ABVQString@@@Z) d:\SDK\Qt5.0\qtbase\bin\designer.exe : fatal error LNK1120: 14.
Help please!
Forgot some additions:
1. Before this i had errors “duplicate symbols detected” while building ActiveQt module and i disabled it before next building qt5.
2. Important difference from guide is also that i used “-static” (I’ll try to build without it and report here).
3. And i tried both – qt5beta2 sources from download sections and fresh sources from git://gitorious.org/qt/qt5.git.
Result is the same yet.
Thank you all for the feedback! This is the comment #100 to this post already
But, please use bugreports.qt-project.org for reporting issues. We are actively monitoring that to fix issues found in the beta 2.
What’s happened to the qt_mac_set_dock_menu function? My app won’t compile on the Mac without this as I used it to replace the clumsy notification icon. This will be a major disadvantage if it is taken out for good.
Also, I need a way to detect X11 now that the Q_WS_X11 define is gone – right now, I define it myself (if Q_OS_UNIX is defined but not Cygwin or Mac). Admittedly Wayland will make that more complicated, but I do need a way of detecting a straight Unix system now, because just using #ifdef Q_OS_LINUX won’t work on Solaris, FreeBSD etc.
I notice that the extern function I mentioned in my last comment is mentioned in the documentation (exportedfunctions.html), but it doesn’t link when I try to compile. I haven’t found any explanation as to if or why the function is not in the beta – is it planned for the final release?
Hi Matthew, please post questions about feature development at the Development mailing list (). Similarly, you can ask questions about using Qt at the Interest mailing list () or the forums (). Through those channels, your questions are more likely to be seen by someone who knows the answer.
Are you going to include a “porting a Qt 4.8 app to Qt 5” ?
I had to figure myself a lot of things while going from Qt 4.8 MingW to Qt 5 MSVC, like:
-“QT += widgets” is now required (before the implicit gui module was enough)
-EACH kind of widget must have its own header specifically included (before, #include was enough). Is that normal ???
-Q_EXPORT_PLUGIN2 has been replaced by Q_PLUGIN_METADATA
-…
Replying to myself: no need to include each widget header, #include is enough
QtGui->QtWidget (for some unknown reason the quotes were removed in my comment)
Yes. Migrating from Qt 4 to 5 is very important and we want to provide good support material for this.
Norton detects as Suspicious.Cloud and goes into infinite loop.
just to inform you, Qt 5.0 Beta 2 dose not support retina display.
You’ve made some decent points there. I looked on the internet for more info about the issue and found most people will go along with your views on this site. | http://blog.qt.io/blog/2012/11/13/qt-5-0-beta-2-is-out/ | CC-MAIN-2015-48 | refinedweb | 5,005 | 50.33 |
I have a point feature class with over 80 million features that need to have fields added to include both the lat/long coordinates in two different fields. While it is easy to calculate this in ArcMap, I need to write a script that will write both to the table then round to within 3 of the decimal point. I have tried using both
InsertCursor and
UpdateCursor and have failed to be able to write to the fields. However when I use the
SearchCursor I can retrieve the values I am just unable to write them to the fields.
Here's what I am working with so far:
import arcpy from arcpy import env env.workspace = 'C:\Users\Testing' env.overwriteOutput = True inFeatures = "ras2point.shp" cursor = arcpy.da.InsertCursor(inFeatures, ["[email protected]"]) for row in inFeatures: X = row[0] cursor.insertRow([X]) del row del cursor print 'FINISHED' | http://www.howtobuildsoftware.com/index.php/how-do/uUm/python-gis-arcpy-writing-lat-long-geometries-to-a-feature-class-field | CC-MAIN-2017-04 | refinedweb | 148 | 74.69 |
Copyright (c) 2002 Paul `Rusty' Russell, IBM. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections being LIST THEIR TITLES, with no Front-Cover Texts, and with no Back-Cover Texts.
Abstract
The Linux Kernel contains 5 million lines of source. It is difficult to know where to start, when you want to modify it in some way. This tutorial will cover various kernel programming conceps in depth: you will gain an appreciation for the Linux kernel by reading some of the code some of the great programmers, including of Linus Torvalds and Ingo Molnar, and an insight into Linux kernel development methods and politics (this is a preliminary version, the final version for the Congress may still suffer some changes. The Editors).
Table of Contents
linux-2.5.3 |------ Documentation |------ arch | |------ ... | |------ i386 | | |------ boot | | | |------ compressed | | | `------ tools | | |------ kernel | | | `------ cpu | | |------ lib | | |------ math-emu | | |------ mm | | `------ pci | |------ ... |------ drivers |------ fs |------ include | |------ ... | |------ asm-i386 | |------ ... | |------ linux | |------ ... |------ init |------ ipc |------ kernel |------ lib |------ mm |------ net |------ scripts |------ security `------ sound
17 architectures
12,000 files, 5,000,000 lines of code
drivers/: 3,200 files, 2,300,000 lines of code
arch/: 2,900 files, 990,000 lines of code
fs/: 660 files, 330,000 lines of code
net/: 450 files, 230,000 lines of code
init/ kernel/ lib/ mm/: 100 files, 46,000 lines of code
We will NOT be covering all these today!
Kernel is written in GNU C & inline assembler (arch specific code).
static inline int foo(void) { return -ENOMEM }
Global address space. No memory protection: you can destroy everything.
int *foo = NULL; *foo = 1; /* BOOM! */
No libc in the kernel: only a small subset.
malloc(), strtoul()
No floating point or MMX usage.
int x = foo * 2.5; /* BOOM! */
Limited stack space (shared with interrupts on some archs)
char buffer[4096]; /* BOOM! */
Platform independence: 64-bit clean, endian-clean, char-signed clean
int foo = (int)&ptr; /* BOOM! */ char *firstbyte = (char &)&foo; /* BOOM! */ if (*firstbyte < 0) /* BOOM! */
arch/<arch>/kernel/head.S
init/main.c
calls module_init( ) and __setup( ) functions
mounts root filesystem
execs init process
arch/<arch>/kernel/entry.S Hard-coded table of functions
Functions called from here must be declared asmlinkage.
Negative return sets errno, eg "return -ENOENT;"
Traps are similar to asynchronous system calls. eg. page fault, segmentation fault
We call these "user context"
Doing work for a particular process
Process accessed using the "current" global variable
We can switch to other tasks voluntarily, by calling "schedule()". Sometimes called "sleeping".
We can be preempted by other tasks, too.
request_irq( ) registers your hardware interrupt handler
arch/<arch>/kernel/irq.c:do_IRQ( ) calls your handler.
Interrupts are disabled while your handler is running, so be quick!
Three types: softirqs, tasklets, bottom halves.
Marked (usually by hardware interrupt handlers) to do more work.
Timer functions (add_timer et al) run as bottom halves.
Run on return from hw handlers
... and from ksoftirqd if very busy.
See simultaneous.eps
Soft Interrupts User- User- Bottom Tasklet Softirq IRQ space context Half
Same one runs No No No No Yes No simultaneously on other CPU?
Same type runs Yes Yes No Yes Yes Yes simultaneously on other CPU?
Interrupted by same type? Yes Yes* No No No No
Interrupted by Yes Yes No No No No soft interrupts?
Interrupted by Yes Yes Yes Yes Yes No hard interrupts?
Problems:
Shared address space: all using the same global & static variables.
Other functions can interrupt at any time
Maybe multiple CPUs (SMP)
We need ways to protect data from simultaneous access.
We call these multiple accesses at the same time "Race Conditions"
foo.c:
/* Increment i by 1 */ i++;
foo.s:
lwz 9,0(3) # Load contents of R3 + 0 into R9 addi 9,9,1 # Add one to R9 stw 9,0(3) # Put contents of R9 back into R3 + 0
Three flavours of race conditions in the Linux Kernel:
lwz 9,0(3) # Load contents of R3 + 0 into R9 ***** INTERRUPT ***** ... lwz 9,0(3) # Load contents of R3 + 0 into R9 addi 9,9,1 # Add one to R9 stw 9,0(3) # Put contents of R9 back into R3 + 0 ... ***** RETURN FROM INTERRUPT ***** addi 9,9,1 # Add one to R9 stw 9,0(3) # Put contents of R9 back into R3 + 0
lwz 9,0(3) # Load contents of R3 + 0 into R9 ***** PROCESS 1 KICKED OFF CPU. PROCESS 2: ***** ... lwz 9,0(3) # Load contents of R3 + 0 into R9 addi 9,9,1 # Add one to R9 stw 9,0(3) # Put contents of R9 back into R3 + 0 ... ***** PROCESS 1 RETURNS TO CPU ***** addi 9,9,1 # Add one to R9 stw 9,0(3) # Put contents of R9 back into R3 + 0
CPU 1 CPU 2 ... lwz 9,0(3) ... addi 9,9,1 lwz 9,0(3) stw 9,0(3) addi 9,9,1 ... stw 9,0(3) ...
Protect from interruption by hardware interrupts:
local_irq_disable(int irq) & local_irq_enable(int irq)
Protection from software interrupts:
local_bh_disable(void) & local_bh_enable(void)
Protection from other CPUs:
spin_lock(spinlock_t *) & spin_unlock(spinlock_t *)
Preemption by other user contexts:
preempt_disable(void) & preempt_enable(void)
Combinations:
spin_lock_bh & spin_unlock_bh spin_lock_irq & spin_unlock_irq spin_lock_irqsave & spin_unlock_irqrestore
Reader-writer:
read_lock*/write_lock* & read_unlock*/write_unlock*
We cannot call any function which might sleep (schedule()) while using ANY of these.
There are special primitives for protecting from other user contexts while in user context: they sleep if they have to wait:
down_interruptible(struct semaphore *) & up(struct semaphore *)
down_read(struct rw_semaphore *) & up_read(struct rw_semaphore *) down_write(struct rw_semaphore *) & up_write(struct rw_semaphore *)
kernel/softirq.c
/* * linux/kernel/softirq.c * * Copyright (C) 1992 Linus Torvalds * * Fixed a disable_bh()/enable_bh() race (was causing a console lockup) * due bh_mask_count not atomic handling. Copyright (C) 1998 Andrea Arcangeli * * Rewritten. Old one was good in 2.2, but in 2.3 it was immoral. --ANK (990903) */
#include <linux/config.h> #include <linux/mm.h> #include <linux/kernel_stat.h> #include <linux/interrupt.h> #include <linux/smp_lock.h> #include <linux/init.h> #include <linux/tqueue.h> #include <linux/percpu.h> #include <linux/notifier.h>
/* - No shared variables, all the data are CPU local. - If a softirq needs serialization, let it serialize itself by its own spinlocks. - Even if softirq is serialized, only local cpu is marked for execution. Hence, we get something sort of weak cpu binding. Though it is still not clear, will it result in better locality or will not.
Examples: - NET RX softirq. It is multithreaded and does not require any global serialization. - NET TX softirq. It kicks software netdevice queues, hence it is logically serialized per device, but this serialization is invisible to common code. - Tasklets: serialized wrt itself. - Bottom halves: globally serialized, grr... */
irq_cpustat_t irq_stat[NR_CPUS];
static struct softirq_action softirq_vec[32] __cacheline_aligned_in_smp;
/* * we cannot loop indefinitely here to avoid userspace starvation, * but we also don't want to introduce a worst case 1/HZ latency * to the pending events, so lets the scheduler to balance * the softirq load for us. */ static inline void wakeup_softirqd(unsigned cpu) { struct task_struct * tsk = ksoftirqd_task(cpu);
if (tsk && tsk->state != TASK_RUNNING) wake_up_process(tsk); }
asmlinkage void do_softirq() { __u32 pending; long flags; __u32 mask; int cpu;
if (in_interrupt()) return;
local_irq_save(flags); cpu = smp_processor_id();
pending = softirq_pending(cpu);
if (pending) { struct softirq_action *h;
mask = ~pending; local_bh_disable(); restart: /* Reset the pending bitmask before enabling irqs */ softirq_pending(cpu) = 0;
local_irq_enable();
h = softirq_vec;
do { if (pending & 1) h->action(h); h++; pending >>= 1; } while (pending);
local_irq_disable();
pending = softirq_pending(cpu); if (pending & mask) { mask &= ~pending; goto restart; } __local_bh_enable();
if (pending) wakeup_softirqd(cpu); }
local_irq_restore(flags); }
/* * This function must run with irqs disabled! */ inline void cpu_raise_softirq(unsigned int cpu, unsigned int nr) { __cpu_raise_softirq(cpu, nr);
/* * If we're in an interrupt or bh, we're done * (this also catches bh-disabled code). We will * actually run the softirq once we return from * the irq or bh. * * Otherwise we wake up ksoftirqd to make sure we * schedule the softirq soon. */ if (!in_interrupt()) wakeup_softirqd(cpu); }
void raise_softirq(unsigned int nr) { long flags;
local_irq_save(flags); cpu_raise_softirq(smp_processor_id(), nr); local_irq_restore(flags); }
Even middle point is stable (eg. 2.4.17).
Bug fixes
New drivers
Odd is unstable (eg. 2.5.3).
Everything can change
Unstable becomes stable every few years.
-pre or -rc kernels are designed for testing only.
Currently playing: 2.5. Linus et. al.
Stable: 2.4. Marcelo et al.
Kernels come from
Download patches and apply them by hand:
cp -al linux-2.5.30 linux-2.5.31 cd linux-2.5.31 zcat ../patch-2.5.31.gz | patch -p1
Recommended method (if editor breaks hardlinks!):
cd ~/kernel-sources wget grab-kernel 2.5.3 . cp -al linux-2.5.3 working-2.5.3-myhacks cd working-2.5.3-myhacks
To produce a patch:
cd ~/kernel-sources diff -urN -X ~/dontdiff linux-2.5.3 working-2.5.3-myhacks | grep -v Binary
Make sure you read the patch before you send it out!
More hints can be found:
Named structure initializers
struct foo bar = { .func = myfunc, };
inline functions
static inline int myfunc(void) { return -ENOSYS; }
Variable argument macros
#define DEBUG(x,...) printk(KERN_DEBUG x , __VA_ARGS__)
Statement expressions ({ and })
#define get_cpu() ({ preempt_disable(); smp_processor_id(); })
__builtin_constant_p()
#define test_bit(nr,addr) (__builtin_constant_p(nr) ? constant_test_bit((nr),(addr)) : variable_test_bit((nr),(addr)))
wait_queue_head_t: DECLARE_WAIT_QUEUE_HEAD( )/init_waitqueue_head( ) wait_event_interruptible(wq, condition) wake_up(wait_queue_head_t *)
HZ & jiffies add_timer( ) & del_timer_sync( )
struct completion: DECLARE_COMPLETION( )/init_completion( ) wait_for_completion(struct completion *) complete(struct completion *)
kernel/sched.c
/* * kernel/sched.c * * Kernel scheduler and related syscalls * * Copyright (C) 1991-2002 Linus Torvalds * * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and * make semaphores SMP safe * 1998-11-19 Implemented schedule_timeout() and related stuff * by Andrea Arcangeli * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar: * hybrid priority-list and round-robin design with * an array-switch method of distributing timeslices * and per-CPU runqueues. Cleanups and useful suggestions * by Davide Libenzi, preemptible kernel bits by Robert Love. */
#include <linux/mm.h> #include <linux/nmi.h> #include <linux/init.h> #include <asm/uaccess.h> #include <linux/highmem.h> #include <linux/smp_lock.h> #include <asm/mmu_context.h> #include <linux/interrupt.h> #include <linux/completion.h> #include <linux/kernel_stat.h> #include <linux/security.h> #include <linux/notifier.h> #include <linux/delay.h>
/* * Convert user-nice values [ -20 ... 0 ... 19 ] * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ], * and back. */ #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20) #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20) #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
/* * 'User priority' is the nice value converted to something we * can work with better when scaling various scheduler parameters, * it's a [ 0 ... 39 ] range. */ #define USER_PRIO(p) ((p)-MAX_RT_PRIO) #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio) #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
/* * These are the 'tuning knobs' of the scheduler: * * Minimum timeslice is 10 msecs, default timeslice is 150 msecs, * maximum timeslice is 300 msecs. Timeslices get refilled after * they expire. */ #define MIN_TIMESLICE ( 10 * HZ / 1000) #define MAX_TIMESLICE (300 * HZ / 1000) #define CHILD_PENALTY 95 #define PARENT_PENALTY 100 #define EXIT_WEIGHT 3 #define PRIO_BONUS_RATIO 25 #define INTERACTIVE_DELTA 2 #define MAX_SLEEP_AVG (2*HZ) #define STARVATION_LIMIT (2*HZ)
/* * If a task is 'interactive' then we reinsert it in the active * array after it has expired its current timeslice. (it will not * continue to run immediately, it will still roundrobin with * other interactive tasks.) * * This part scales the interactivity limit depending on niceness. * * We scale it linearly, offset by the INTERACTIVE_DELTA delta. * Here are a few examples of different nice levels: * * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0] * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0] * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0] * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0] * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0] * * (the X axis represents the possible -5 ... 0 ... +5 dynamic * priority range a task can explore, a value of '1' means the * task is rated interactive.) * * Ie. nice +19 tasks can never get 'interactive' enough to be * reinserted into the active array. And only heavily CPU-hog nice -20 * tasks will be expired. Default nice 0 tasks are somewhere between, * it takes some effort for them to get interactive, but it's not * too hard. */
#define SCALE(v1,v1_max,v2_max) (v1) * (v2_max) / (v1_max)
#define DELTA(p) (SCALE(TASK_NICE(p), 40, MAX_USER_PRIO*PRIO_BONUS_RATIO/100) + INTERACTIVE_DELTA)
#define TASK_INTERACTIVE(p) ((p)->prio <= (p)->static_prio - DELTA(p))
/* * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ] * to time slice values. * * The higher a thread's priority, the bigger timeslices * it gets during one round of execution. But even the lowest * priority thread gets MIN_TIMESLICE worth of execution time. * * task_timeslice() is the interface that is used by the scheduler. */
#define BASE_TIMESLICE(p) (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) * (MAX_PRIO-1-(p)->static_prio)/(MAX_USER_PRIO - 1)))
static inline unsigned int task_timeslice(task_t *p) { return BASE_TIMESLICE(p); }
/* * These are the runqueue data structures: */
#define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
typedef struct runqueue runqueue_t;
struct prio_array { int nr_active; unsigned long bitmap[BITMAP_SIZE]; list_t queue[MAX_PRIO]; };
/* * This is the main, per-CPU runqueue data structure. * * Locking rule: those places that want to lock multiple runqueues * (such as the load balancing or the thread migration code), lock * acquire operations must be ordered by ascending &runqueue. */ struct runqueue { spinlock_t lock; unsigned long nr_running, nr_switches, expired_timestamp, nr_uninterruptible; task_t *curr, *idle; prio_array_t *active, *expired, arrays[2]; int prev_nr_running[NR_CPUS];
task_t *migration_thread; list_t migration_queue;
} ____cacheline_aligned;
static struct runqueue runqueues[NR_CPUS] __cacheline_aligned;
#define cpu_rq(cpu) (runqueues + (cpu)) #define this_rq() cpu_rq(smp_processor_id()) #define task_rq(p) cpu_rq(task_cpu(p)) #define cpu_curr(cpu) (cpu_rq(cpu)->curr) #define rt_task(p) ((p)->prio < MAX_RT_PRIO)
/* * Default context-switch locking: */ #ifndef prepare_arch_switch # define prepare_arch_switch(rq, next) do { } while(0) # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock) # define task_running(rq, p) ((rq)->curr == (p)) #endif
/* * task_rq_lock - lock the runqueue a given task resides on and disable * interrupts. Note the ordering: we can safely lookup the task_rq without * explicitly disabling preemption. */ static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags) { struct runqueue *rq;
repeat_lock_task: local_irq_save(*flags); rq = task_rq(p); spin_lock(&rq->lock); if (unlikely(rq != task_rq(p))) { spin_unlock_irqrestore(&rq->lock, *flags); goto repeat_lock_task; } return rq; }
static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags) { spin_unlock_irqrestore(&rq->lock, *flags); }
/* * rq_lock - lock a given runqueue and disable interrupts. */ static inline runqueue_t *this_rq_lock(void) { runqueue_t *rq;
local_irq_disable(); rq = this_rq(); spin_lock(&rq->lock);
return rq; }
static inline void rq_unlock(runqueue_t *rq) { spin_unlock(&rq->lock); local_irq_enable(); }
/* * Adding/removing a task to/from a priority array: */ static inline void dequeue_task(struct task_struct *p, prio_array_t *array) { array->nr_active--; list_del(&p->run_list); if (list_empty(array->queue + p->prio)) __clear_bit(p->prio, array->bitmap); }
static inline void enqueue_task(struct task_struct *p, prio_array_t *array) { list_add_tail(&p->run_list, array->queue + p->prio); __set_bit(p->prio, array->bitmap); array->nr_active++; p->array = array; }
/* * effective_prio - return the priority that is based on the static * priority but is modified by bonuses/penalties. * * We scale the actual sleep average [0 .... MAX_SLEEP_AVG] * into the -5 ... 0 ... +5 bonus/penalty range. * * We use 25% of the full 0...39 priority range so that: * * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs. * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks. * * Both properties are important to certain workloads. */ static inline int effective_prio(task_t *p) { int bonus, prio;
bonus = MAX_USER_PRIO*PRIO_BONUS_RATIO*p->sleep_avg/MAX_SLEEP_AVG/100 - MAX_USER_PRIO*PRIO_BONUS_RATIO/100/2;
prio = p->static_prio - bonus; if (prio < MAX_RT_PRIO) prio = MAX_RT_PRIO; if (prio > MAX_PRIO-1) prio = MAX_PRIO-1; return prio; }
/* * activate_task - move a task to the runqueue.
* Also update all the scheduling statistics stuff. (sleep average * calculation, priority modifiers, etc.) */ static inline void activate_task(task_t *p, runqueue_t *rq) { unsigned long sleep_time = jiffies - p->sleep_timestamp; prio_array_t *array = rq->active;
if (!rt_task(p) && sleep_time) { /* * This code gives a bonus to interactive tasks. We update * an 'average sleep time' value here, based on * sleep_timestamp. The more time a task spends sleeping, * the higher the average gets - and the higher the priority * boost gets as well. */ p->sleep_avg += sleep_time; if (p->sleep_avg > MAX_SLEEP_AVG) p->sleep_avg = MAX_SLEEP_AVG; p->prio = effective_prio(p); } enqueue_task(p, array); rq->nr_running++; }
/* * deactivate_task - remove a task from the runqueue. */ static inline void deactivate_task(struct task_struct *p, runqueue_t *rq) { rq->nr_running--; if (p->state == TASK_UNINTERRUPTIBLE) rq->nr_uninterruptible++; dequeue_task(p, p->array); p->array = NULL; }
/* * resched_task - mark a task 'to be rescheduled now'. * * On UP this means the setting of the need_resched flag, on SMP it * might also involve a cross-CPU call to trigger the scheduler on * the target CPU. */ static inline void resched_task(task_t *p) { #ifdef CONFIG_SMP int need_resched, nrpolling;
preempt_disable(); /* minimise the chance of sending an interrupt to poll_idle() */ nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG); need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED); nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id())) smp_send_reschedule(task_cpu(p)); preempt_enable(); #else set_tsk_need_resched(p); #endif }
/*** * try_to_wake_up - wake up a thread * @p: the to-be-woken-up thread * @sync: do a synchronous wakeup? * * failure only if the task is already active. */ static int try_to_wake_up(task_t * p, int sync) { unsigned long flags; int success = 0; long old_state; runqueue_t *rq;
repeat_lock_task: rq = task_rq_lock(p, &flags); old_state = p->state; if (!p->array) { /* * Fast-migrate the task if it's not running or runnable * currently. Do not violate hard affinity. */ if (unlikely(sync && !task_running(rq, p) && (task_cpu(p) != smp_processor_id()) && (p->cpus_allowed & (1UL << smp_processor_id())))) {
set_task_cpu(p, smp_processor_id()); task_rq_unlock(rq, &flags); goto repeat_lock_task; } if (old_state == TASK_UNINTERRUPTIBLE) rq->nr_uninterruptible--; activate_task(p, rq);
if (p->prio < rq->curr->prio) resched_task(rq->curr); success = 1; } p->state = TASK_RUNNING; task_rq_unlock(rq, &flags);
return success; }
int wake_up_process(task_t * p) { return try_to_wake_up(p, 0); }
/* * context_switch - switch to the new MM and the new * thread's register state. */ static inline task_t * context_switch(task_t *prev, task_t *next) { struct mm_struct *mm = next->mm; struct mm_struct *oldmm = prev->active_mm;
if (unlikely(!mm)) { next->active_mm = oldmm; atomic_inc(&oldmm->mm_count); enter_lazy_tlb(oldmm, next, smp_processor_id()); } else switch_mm(oldmm, mm, next, smp_processor_id());
if (unlikely(!prev->mm)) { prev->active_mm = NULL; mmdrop(oldmm); }
/* Here we just switch the register state and the stack. */ switch_to(prev, next, prev);
return prev; }
/* * double_rq_lock - safely lock two runqueues * * Note this does not disable interrupts like task_rq_lock, * you need to do so manually before calling. */ static inline void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2) { if (rq1 == rq2) spin_lock(&rq1->lock); else { if (rq1 < rq2) { spin_lock(&rq1->lock); spin_lock(&rq2->lock); } else { spin_lock(&rq2->lock); spin_lock(&rq1->lock); } } }
/* * double_rq_unlock - safely unlock two runqueues * * Note this does not restore interrupts like task_rq_unlock, * you need to do so manually after calling. */ static inline void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2) { spin_unlock(&rq1->lock); if (rq1 != rq2) spin_unlock(&rq2->lock); }
#if CONFIG_SMP
/* * double_lock_balance - lock the busiest runqueue * * this_rq is locked already. Recalculate nr_running if we have to * drop the runqueue lock. */ static inline unsigned int double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest, int this_cpu, int idle, unsigned int nr_running) { if (unlikely(!spin_trylock(&busiest->lock))) { if (busiest < this_rq) { spin_unlock(&this_rq->lock); spin_lock(&busiest->lock); spin_lock(&this_rq->lock); /* Need to recalculate nr_running */ if (idle || (this_rq->nr_running > this_rq->prev_nr_running[this_cpu])) nr_running = this_rq->nr_running; else nr_running = this_rq->prev_nr_running[this_cpu]; } else spin_lock(&busiest->lock); } return nr_running; }
/* * find_busiest_queue - find the busiest runqueue. */ static inline runqueue_t *find_busiest_queue(runqueue_t *this_rq, int this_cpu, int idle, int *imbalance) { int nr_running, load, max_load, i; runqueue_t *busiest, *rq_src;
/* * We search all runqueues to find the most busy one. * We do this lockless to reduce cache-bouncing overhead, * we re-check the 'best' source CPU later on again, with * the lock held. * * We fend off statistical fluctuations in runqueue lengths by * saving the runqueue length during the previous load-balancing * operation and using the smaller one the current and saved lengths. * If a runqueue is long enough for a longer amount of time then * we recognize it and pull tasks from it. * * The 'current runqueue length' is a statistical maximum variable, * for that one we take the longer one - to avoid fluctuations in * the other direction. So for a load-balance to happen it needs * stable long runqueue on the target CPU and stable short runqueue * on the local runqueue. * * We make an exception if this CPU is about to become idle - in * that case we are less picky about moving a task across CPUs and * take what can be taken. */ if (idle || (this_rq->nr_running > this_rq->prev_nr_running[this_cpu])) nr_running = this_rq->nr_running; else nr_running = this_rq->prev_nr_running[this_cpu];
busiest = NULL; max_load = 1; for (i = 0; i < NR_CPUS; i++) { if (!cpu_online(i)) continue;
rq_src = cpu_rq(i); if (idle || (rq_src->nr_running < this_rq->prev_nr_running[i])) load = rq_src->nr_running; else load = this_rq->prev_nr_running[i]; this_rq->prev_nr_running[i] = rq_src->nr_running;
if ((load > max_load) && (rq_src != this_rq)) { busiest = rq_src; max_load = load; } }
if (likely(!busiest)) goto out;
*imbalance = (max_load - nr_running) / 2;
/* It needs an at least ~25% imbalance to trigger balancing. */ if (!idle && (*imbalance < (max_load + 3)/4)) { busiest = NULL; goto out; }
nr_running = double_lock_balance(this_rq, busiest, this_cpu, idle, nr_running); /* * Make sure nothing changed since we checked the * runqueue length. */ if (busiest->nr_running <= nr_running + 1) { spin_unlock(&busiest->lock); busiest = NULL; } out: return busiest; }
/* * pull_task - move a task from a remote runqueue to the local runqueue. * Both runqueues must be locked. */ static inline void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p, runqueue_t *this_rq, int this_cpu) { dequeue_task(p, src_array); src_rq->nr_running--; set_task_cpu(p, this_cpu); this_rq->nr_running++; enqueue_task(p, this_rq->active); /* * Note that idle threads have a prio of MAX_PRIO, for this test * to be always true for them. */ if (p->prio < this_rq->curr->prio) set_need_resched(); }
/* * Current runqueue is empty, or rebalance tick: if there is an * inbalance (current runqueue is too short) then pull from * busiest runqueue(s). * * We call this with the current runqueue locked, * irqs disabled. */ static void load_balance(runqueue_t *this_rq, int idle) { int imbalance, idx, this_cpu = smp_processor_id(); runqueue_t *busiest; prio_array_t *array; list_t *head, *curr; task_t *tmp;
busiest = find_busiest_queue(this_rq, this_cpu, idle, &imbalance); if (!busiest) goto out;
/* * We first consider expired tasks. Those will likely not be * executed in the near future, and they are most likely to * be cache-cold, thus switching CPUs has the least effect * on them. */ if (busiest->expired->nr_active) array = busiest->expired; else array = busiest->active;
new_array: /* Start searching at priority 0: */ idx = 0; skip_bitmap: if (!idx) idx = sched_find_first_bit(array->bitmap); else idx = find_next_bit(array->bitmap, MAX_PRIO, idx); if (idx == MAX_PRIO) { if (array == busiest->expired) { array = busiest->active; goto new_array; } goto out_unlock; }
head = array->queue + idx; curr = head->prev; skip_queue: tmp = list_entry(curr, task_t, run_list);
/* * We do not migrate tasks that are: * 1) running (obviously), or * 2) cannot be migrated to this CPU due to cpus_allowed, or * 3) are cache-hot on their current CPU. */
#define CAN_MIGRATE_TASK(p,rq,this_cpu) ((jiffies - (p)->sleep_timestamp > cache_decay_ticks) && !task_running(rq, p) && ((p)->cpus_allowed & (1UL << (this_cpu))))
curr = curr->prev;
if (!CAN_MIGRATE_TASK(tmp, busiest, this_cpu)) { if (curr != head) goto skip_queue; idx++; goto skip_bitmap; } pull_task(busiest, array, tmp, this_rq, this_cpu); if (!idle && --imbalance) { if (curr != head) goto skip_queue; idx++; goto skip_bitmap; } out_unlock: spin_unlock(&busiest->lock); out: ; }
/* * One of the idle_cpu_tick() and busy_cpu_tick() functions will * get called every timer tick, on every CPU. Our balancing action * frequency and balancing agressivity depends on whether the CPU is * idle or not. * * busy-rebalance every 250 msecs. idle-rebalance every 1 msec. (or on * systems with HZ=100, every 10 msecs.) */ #define BUSY_REBALANCE_TICK (HZ/4 ?: 1) #define IDLE_REBALANCE_TICK (HZ/1000 ?: 1)
static inline void idle_tick(runqueue_t *rq) { if (jiffies % IDLE_REBALANCE_TICK) return; spin_lock(&rq->lock); load_balance(rq, 1); spin_unlock(&rq->lock); }
#endif
/* * We place interactive tasks back into the active array, if possible. * * To guarantee that this does not starve expired tasks we ignore the * interactivity of a task if the first expired task had to wait more * than a 'reasonable' amount of time. This deadline timeout is * load-dependent, as the frequency of array switched decreases with * increasing number of running tasks: */ #define EXPIRED_STARVING(rq) ((rq)->expired_timestamp && (jiffies - (rq)->expired_timestamp >= STARVATION_LIMIT * ((rq)->nr_running) + 1))
/* * This function gets called by the timer code, with HZ frequency. * We call it with interrupts disabled. */ void scheduler_tick(int user_ticks, int sys_ticks) { int cpu = smp_processor_id(); runqueue_t *rq = this_rq(); task_t *p = current;
if (p == rq->idle) { /* note: this timer irq context must be accounted for as well */ if (irq_count() - HARDIRQ_OFFSET >= SOFTIRQ_OFFSET) kstat.per_cpu_system[cpu] += sys_ticks; #if CONFIG_SMP idle_tick(rq); #endif return; } if (TASK_NICE(p) > 0) kstat.per_cpu_nice[cpu] += user_ticks; else kstat.per_cpu_user[cpu] += user_ticks; kstat.per_cpu_system[cpu] += sys_ticks;
/* Task might have expired already, but not scheduled off yet */ if (p->array != rq->active) { set_tsk_need_resched(p); return; } spin_lock(&rq->lock); if (unlikely(rt_task(p))) { /* * RR tasks need a special form of timeslice management. * FIFO tasks have no timeslices. */ if ((p->policy == SCHED_RR) && !--p->time_slice) { p->time_slice = task_timeslice(p); p->first_time_slice = 0; set_tsk_need_resched(p);
/* put it at the end of the queue: */ dequeue_task(p, rq->active); enqueue_task(p, rq->active); } goto out; } /* * The task was running during this tick - update the * time slice counter and the sleep average. Note: we * do not update a thread's priority until it either * goes to sleep or uses up its timeslice. This makes * it possible for interactive tasks to use up their * timeslices at their highest priority levels. */ if (p->sleep_avg) p->sleep_avg--; if (!--p->time_slice) { dequeue_task(p, rq->active); set_tsk_need_resched(p); p->prio = effective_prio(p); p->time_slice = task_timeslice(p); p->first_time_slice = 0;
if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) { if (!rq->expired_timestamp) rq->expired_timestamp = jiffies; enqueue_task(p, rq->expired); } else enqueue_task(p, rq->active); } out: #if CONFIG_SMP if (!(jiffies % BUSY_REBALANCE_TICK)) load_balance(rq, 0); #endif spin_unlock(&rq->lock); }
void scheduling_functions_start_here(void) { }
/* * schedule() is the main scheduler function. */ asmlinkage void schedule(void) { task_t *prev, *next; runqueue_t *rq; prio_array_t *array; list_t *queue; int idx;
if (unlikely(in_interrupt())) BUG();
#if CONFIG_DEBUG_HIGHMEM check_highmem_ptes(); #endif need_resched: preempt_disable(); prev = current; rq = this_rq();
release_kernel_lock(prev); prev->sleep_timestamp = jiffies; spin_lock_irq(&rq->lock);
/* * if entering off of a kernel preemption go straight * to picking the next task. */ if (unlikely(preempt_count() & PREEMPT_ACTIVE)) goto pick_next_task;
switch (prev->state) { case TASK_INTERRUPTIBLE: if (unlikely(signal_pending(prev))) { prev->state = TASK_RUNNING; break; } default: deactivate_task(prev, rq); case TASK_RUNNING: ; } pick_next_task: if (unlikely(!rq->nr_running)) { #if CONFIG_SMP load_balance(rq, 1); if (rq->nr_running) goto pick_next_task; #endif next = rq->idle; rq->expired_timestamp = 0; goto switch_tasks; }
array = rq->active; if (unlikely(!array->nr_active)) { /* * Switch the active and expired arrays. */ rq->active = rq->expired; rq->expired = array; array = rq->active; rq->expired_timestamp = 0; }
idx = sched_find_first_bit(array->bitmap); queue = array->queue + idx; next = list_entry(queue->next, task_t, run_list);
switch_tasks: prefetch(next); clear_tsk_need_resched(prev);
if (likely(prev != next)) { rq->nr_switches++; rq->curr = next;
prepare_arch_switch(rq, next); prev = context_switch(prev, next); barrier(); rq = this_rq(); finish_arch_switch(rq, prev); } else spin_unlock_irq(&rq->lock);
reacquire_kernel_lock(current); preempt_enable_no_resched(); if (test_thread_flag(TIF_NEED_RESCHED)) goto need_resched; }
Linus is God
"The Linux kernel has no core team, and we all know who they are"
Alan Cox (paraphrased)
You do not need to know anything to post to Linux Kernel:
From: Rusty Russell <rusty@linuxcare.com.au> To: root@chaos.analogic.com Cc: lkml <linux-kernel@vger.kernel.org> Subject: Re: On labelled initialisers, gcc-2.7.2.3 and tcp_ipv4.c Date: Mon, 16 Oct 2000 20:59:38 +1100
In message <Pine.LNX.3.95.1001015203310@chaos.analogic.com> you write: > The 'C' language can order structure members anyway it wants.
You are an idiot.
Rusty. -- Hacking time.
Discussion on linux-kernel is usually best when code is included
Patches get dropped
Even good patches.
Trivial Patch Monkey: trivial@rustcorp.com.au
Small number of people have Linus bandwidth reservation
Documentation/CodingStyle
#ifdefs are bad, try to avoid them in functions. eg. Define dummy functions for non-SMP.
Linus says: ALWAYS _RETURN_ THE ERROR.
Usually aim for the *smallest possible patch*: If Linus says "please do more", then great!
Revolutionary changes have been most successful when they are small (at least to begin with)
The correct way to write a portable driver is to write it for 2.5, and then use compatibility macros for 2.4 and 2.2.
Removal of debugging stuff: if it's only useful to the maintainer, get rid of it before submission.
Standards are much higher for core code and infrastructure then drivers and other code which doesn't break anything else.
Do not optimize your locking: use locking idioms.
Do not use typedefs unneccessarily.
Linux kernel sources:
Documentation/CodingStyle
Documentation/DocBook/kernel-hacking.sgml
Documentation/DocBook/kernel-locking.sgml
Unix Systems for Modern Architectures:
Symmetric Multiprocessing and Caching for Kernel Programmers
Curt Schimmel [ISBN: 0201633388]
Linux Device Drivers
Understanding the Linux Kernel
Date: Tue, 29 Jan 2002 14:54:27 +0100 (CET) From: Ingo Molnar <mingo@elte.hu> Reply-To: <mingo@elte.hu> To: Rob Landley <landley@trommello.org> Cc: Linus Torvalds <torvalds@transmeta.com>, <linux-kernel@vger.kernel.org> Subject: Re: A modest proposal -- We need a patch penguin In-Reply-To: <200201290446.g0T4kZU31923@snark.thyrsus.com> Message-ID: <Pine.LNX.4.33.0201291324560.3610-100000@localhost.localdomain> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Sender: linux-kernel-owner@vger.kernel.org Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org
On Mon, 28 Jan 2002, Rob Landley wrote:
> (You keep complaining people never send you patches. People are > suggesting automated patch remailers to spam your mailbox even harder. > There has GOT to be a better way...)
None of the examples you cited so far are convincing to me, and i'd like to explain why. I've created and submitted thousands of patches to the Linux kernel over the past 4 years (my patch archive doesnt go back more than 4 years):
# ls patches | wc -l 2818
a fair percentage of those went to Linus as well, and while having seen some of them rejected does hurt mentally, i couldnt list one reject from Linus that i wouldnt reject *today*. But i sure remember being frustrated about rejects when they happened. In any case, i have some experience in submitting patches and i'm maintaining a few subsystems, so here's my take on the 'patch penguin' issue:
If a patch gets ignored 33 times in a row then perhaps the person doing the patch should first think really hard about the following 4 issues:
- cleanliness - concept - timing - testing
a violation of any of these items can cause patch to be dropped *without notice*. Face it, it's not Linus' task to teach people how to code or how to write correct patches. Sure, he still does teach people most of the time, but you cannot *expect* him to be able to do it 100% of the time.
1) cleanliness
code cleanliness is a well-know issue, see Documentation/CodingStyle. If a patch has such problems then maintainers are very likely to help - Linus probably wont and shouldnt. I'm truly shocked sometimes, how many active and experienced kernel developers do not follow these guidelines. While the Linux coding style might be arbitrary in places, all coding styles are arbitrary in some areas, and only one thing is important above all: consistency between kernel subsystems. If i go from one kernel subsystem to another then i'd like to have the same 'look and feel' of source code - i think this is a natural desire we all share. If anyone doesnt see the importance of this issue then i'd say he hasnt seen, hacked and maintained enough kernel code yet. I'd say the absolute positive example here is Al Viro. I think most people just do not realize the huge amount of background cleanup work Al did in the past 2 years. And guess what? I bet Linus would be willing to apply Al's next patch blindfolded.
impact: a patch penguin might help here - but he probably wont scale as well as the current set of experienced kernel hackers scale, many of whom are happy to review patches for code cleanliness (and other) issues.
2) concept
many of the patches which were rejected for a long time are *difficult* issues. And one thing many patch submitters miss: even if the concept of the patch is correct, you first have to start by cleaning up *old* code, see issue 1). Your patch is not worth a dime if you leave in old cruft, or if the combination of old cruft and your new code is confusing. Also, make sure the patch is discussed and developed openly, not on some obscure list. linux-kernel@vger.kernel.org will do most of the time. I do not want to name specific patches that violate this point (doing that in public just offends people needlessly - and i could just as well list some of my older patches), but i could list 5 popular patches immediately.
impact: a patch penguin just wont solve this concept issue, because, by definition, he doesnt deal with design issues. And most of the big patch rejections happen due to exactly these concept issues.
3) timing
kernel source code just cannot go through arbitrary transitions. Eg. right now the scheduler is being cleaned up (so far it was more than 50 sub-patches and they are still coming) - and work is going on to maximize the quality of the preemption patch, but until the base scheduler has stabilized there is just no point in applying the preemption patch - no matter how good the preemption patch is. Robert understands this very much. Many other people do not.
impact: a patch penguin just wont solve this issue, because a patch penguin cannot let his tree transition arbitrarily either. Only separately maintained and tested patches/trees can handle this issue.
4) testing
there are code areas and methods which need more rigorous testing and third-party feedback - no matter how good the patch. Most notably, if a patch exports some new user-space visible interface, then this item applies. An example is the aio patch, which had all 3 items right but was rejected due to this item. [things are improving very well on the aio front so i think this will change in the near future.]
impact: a patch penguin just wont solve this issue, because his job, by definition, is not to keep patches around indefinitely, but to filter them to Linus. Only separately maintained patches/trees help here. More people are willing to maintain separate trees is good (-dj, -ac, -aa, etc.), one tree can do a nontrivial transition at a time, and by having more of them we can eg. get one of them testing aio, the other one testing some other big change. A single patch penguin will be able to do only one nontrivial transition - and it's not his task to do nontrivial transitions to begin with.
Many people who dont actually maintain any Linux code are quoting Rik's complains as an example. I'll now have to go on record disagreeing with Rik humbly, i believe he has done a number of patch-management mistakes during his earlier VM development, and i strongly believe the reason why Linus ignored some of his patches were due to these issues. Rik's flames against Linus are understandable but are just that: flames. Fortunately Rik has learned meanwhile (we all do) and his rmap patches are IMHO top-notch. Joining the Andrea improvements and Rik's tree could provide a truly fantastic VM. [i'm not going to say anything about the IDE patches situation because while i believe Rik understands public criticism, i failed to have an impact on Andre before :-) ]
also, many people just start off with a single big patch. That just doesnt work and you'll likely violate one of the 4 items without even noticing it. Start small, because for small patches people will have the few minutes needed to teach you. The bigger a patch, the harder it is to review it, and the less likely it happens. Also, if a few or your patches have gone into the Linux tree that does not mean you are senior kernel hacker and can start off writing the one big, multi-megabyte super-feature you dreamt about for years. Start small and increase the complexity of your patches slowly - and perhaps later on you'll notice that that super-feature isnt all that super anymore. People also underestimate the kind of complexity explosion that occurs if a large patch is created. Instead of 1-2 places, you can create 100-200 problems.
face it, most of the patches rejected by Linus are not due to overload. He doesnt guarantee to say why he rejects patches - *and he must not*. Just knowing that your patch got rejected and thinking it all over again often helps finding problems that Linus missed first time around. If you submit to Linus then you better know exactly what you do.
if you are uncertain about why a patch got rejected, then shake off your frustration and ask *others*. Many kernel developers, including myself, are happy to help reviewing patches. But people do have egos, and it happens very rarely that people ask it on public lists why their patches got rejected, because people do not like talking about failures. And the human nature makes it much easier to attack than to talk about failures. Which fact alone pretty much shows that most of the time the problem is with the patch submitter, not with Linus.
it's so much easier to blame Linus, or maintainers. It's so much easier to fire off an email flaming Linus and getting off the steam than to actually accept the possibility of mistake and *fix* the patch. I'll go on record saying that good patches are not ignored, even these days when the number of active kernel hackers has multipled. People might have to go through several layers first, and finding some kernel hacker who is not as loaded as Linus to review your patch might be necessery as well (especially if the patch is complex), but if you go through the right layers then you can be sure that nothing worthwile gets rejected arbitrarily.
Ingo
- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.kernel.org More majordomo info at Please read the FAQ at
Date: Wed, 30 Aug 2000 10:04:12 -0700 (PDT) From: Linus Torvalds <torvalds@transmeta.com> To: Rogier Wolff <R.E.Wolff@BitWizard.nl> Cc: Arnaldo Carvalho de Melo <acme@conectiva.com.br>, Philipp Rumpf <prumpf@parcelfarce.linux.theplanet.co.uk>, Kenneth Johansson <ken@canit.se>, Jean-Paul Roubelat <jpr@f6fbb.org>, davem@redhat.com, linux-kernel@vger.kernel.org Subject: Re: [PATCH] af_rose.c: s/suser/capable/ + micro cleanups In-Reply-To: <200008300717.JAA02899@cave.bitwizard.nl> Message-ID: <Pine.LNX.4.10.10008300941230.1393-100000@penguin.transmeta.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Sender: linux-kernel-owner@vger.kernel.org Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org
On Wed, 30 Aug 2000, Rogier Wolff wrote: > > > source code smaller and more easier to read (yes, this is debatable, > > I think it becomes more clean, other think otherwise, I'm just > > following what Linus said he prefer). > > The kernel is a multi-million-lines-of-code piece of software. > Software maintenance cost is found to correlate strongly with the > number of lines-of-code. > > So, I would prefer the shorter version.
I disagree.
Number of lines is irrelevant.
The _complexity_ of lines counts.
And ?: is a complex construct, that is not always visually very easy to parse because of the "non-local" behaviour.
That is not saying that I think you shouldn't use ?: at all. It's a wonderful construct in many ways, and I use it all the time myself. But I actually prefer
if (complex_test) return complex_expression1;
return complex_expression2;
over
return (complex_test) ? complex_expression1 : complex_expression2;
because by the time you have a complex ?: thing it's just not very readable any more.
Basically, dense lines are bad. And ?: can make for code that ends up "too dense".
More specific example: I think
return copy_to_user(dst, src, size) ? -EFAULT : 0;
is fine and quite readable. Fits on a simple line.
However, it's getting iffy when it becomes something like
return copy_to_user(buf, page_address(page) + offset, size) ? -EFAULT: 0;
for example. The "return" is so far removed from the actual return values, that it takes some parsing (maybe you don't even see everything on an 80-column screen, or even worse, you split up one expression over several lines..
(Basically, I don't like multi-line expressions. Avoid stuff like
x = ... + ... - ...;
unless it is _really_ simple. Similarly, some people split up their "for ()" or "while ()" statement things - which usually is just a sign of the loop baing badly designed in the first place. Multi-line expressions are sometimes unavoidable, but even then it's better to try to simplify them as much as possible. You can do it by many means
- make an inline function that has a descriptive name. It's still complex, but now the complexity is _described_, and not mixed in with potentially other complex actions.
- Use logical grouping. This is sometimes required especially in "if()" statements with multiple parts (ie "if ((x || y) && !z)" can easily become long - but you might consider just the above inline function or #define thing).
- Use multiple statements. I personally find it much more readable to have
if (PageTestandClearReferenced(page)) goto dispose_continue;
if (!page->buffers && page_count(page) > 1) goto dispose_continue;
if (TryLockPage(page)) goto dispose_continue;
rather than the equivalent
if (PageTestandClearReferenced(page) || (!page->buffers && page_count(page) > 1) || TryLockPage(page)) goto dispose_continue;
regardless of any grouping issues.
Basically, lines-of-code is a completely bogus metric for _anything_. Including maintainability.
> If it takes you a few seconds to look this over, that's fine. Even it > the one "complicated" line take twice as long (per line) as the > original 4 lines, then it's a win.
I disagree violently.
Linus | http://www.ibiblio.org/pub/linux/docs/LuCaS/Presentaciones/200211hispalinux/rusty/seminar.html | crawl-002 | refinedweb | 6,934 | 55.84 |
libev - a high performance full-featured event loop written in C
#include <ev.h>
// a single header file is required #include <ev.h> #include <stdio.h> // for puts // every watcher type has its own typedef'd struct // with the name ev_TYPE ev_io stdin_watcher; ev_timer timeout_watcher; // all watcher callbacks have a similar signature // this callback is called when data is readable on stdin static void stdin_cb (EV_P_ ev_io *w, int revents) { puts ("stdin ready"); // for one-shot events, one must manually stop the watcher // with its corresponding stop function. ev_io_stop (EV_A_ w); // this causes all nested ev; // initialise an io watcher, then start it // this one will watch for stdin to become readable ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); ev_io_start (loop, &stdin_watcher); // initialise a timer watcher, then start it // simple non-repeating 5.5 second timeout ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); ev_timer_start (loop, &timeout_watcher); // now wait for events to arrive ev_run (loop, 0); // break was called, so exit return 0; }
This document documents the libev software package.
The newest version of this document is also available as an html-formatted web page you might find easier to navigate when reading it for the first time:.
While this document tries to be as complete as possible in documenting libev, its usage and the rationale behind its design, it is not a tutorial on event-based programming, nor will it introduce event-based programming with libev.
Familiarity with event based programming techniques in general is assumed throughout this document."., which are relatively small C structures you initialise with the details of the event, and then hand it over to libev by starting the watcher..
These version numbers refer to the ABI version of the library, not the release version.
Usually, it's a good idea to terminate if the major versions mismatch, as this indicates an incompatible change. Minor versions are usually compatible to older versions, so a larger minor version alone is usually not a problem.
Example: Make sure we haven't accidentally been linked against the wrong version (note, however, that this will not detect other ABI mismatches, such as LFS or reentrancy).
assert (("libev version mismatch", ev_version_major () == EV_VERSION_MAJOR && ev_version_minor () >= EV_VERSION_MINOR));: Replace the libev allocator with one that waits a bit and then retries (example requires a standards-compliant
realloc).
static void * persistent_realloc (void *ptr, size_t size) { for (;;) { void *newptr = realloc (ptr, size); if (newptr) return newptr; sleep (60); } } ... ev_set_allocator (persistent_realloc);.
Example: This is the most typical usage.
if (!ev_default_loop (0)) fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
Example: Restrict libev to the select and poll backends, and do not allow environment settings to be taken into account:
ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV);).
The big advantage of this flag is that you can forget about fork (and forget about forgetting to tell libev about forking).
To get good performance out of this backend you need a high amount of parallelism (most of the file descriptors should be busy). If you are writing a server, you should).
For few fds, this backend is a bit little slower than poll and select, but it scales phenomenally better. While poll and select usually scale like O(total_fds) where total_fds is the total number of fds (or the highest fd), epoll scales either O(1) or O(active_fds).
The epoll mechanism deserves honorable mention as the most misdesigned of the more advanced event mechanisms: mere annoyances include silently dropping file descriptors, requiring a system call per change per file descriptor (and unnecessary guessing of parameters), problems with dup, different file descriptors (even already closed ones, so one cannot even remove them from the set) than registered in the set (especially on SMP systems). Libev tries to counter these spurious notifications by employing an additional generation counter and comparing that against the events to filter out spurious ones, recreating the set when required.,
dup ()'ed file descriptors might not work very well if you register events for both file descriptors.
Best performance from this backend is achieved by not unregistering all watchers for a file descriptor until it has been closed, if possible, i.e. keep at least one watcher active per fd at all times. Stopping and starting a watcher (without re-setting it) also usually doesn't cause extra overhead. A fork can both result in spurious notifications as well as in libev having to destroy and recreate the epoll object, which can take considerable time and thus should be avoided.
All this means that, in practice,
EVBACKEND_SELECT can be as fast or faster than epoll for maybe up to a hundred file descriptors, depending on the usage. So sad.
While nominally embeddable in other event loops, this feature is broken in all kernel versions tested so far.
This backend maps
EV_READ and
EV_WRITE in the same way as
EVBACKEND_POLL..
You still can embed kqueue into a normal poll or select backend and use it only for sockets (after having made sure that sockets work with kqueue on the target platform). See
ev_embed watchers for more info.
It scales in the same way as the epoll backend, but the interface to the kernel is more efficient (which says nothing about its actual speed, of course). While stopping, setting and starting an I/O watcher does never cause an extra system call as with
EVBACKEND_EPOLL, it still adds up to two event changes per incident. Support for
fork () is very bad (you might have to leak fd's on fork, but it's more sane than epoll) and it drops fds silently in similarly hard-to-detect cases.
This backend usually performs well under most conditions.
While nominally embeddable in other event loops, this doesn't work everywhere, so you might need to test for this. And since it is broken almost everywhere, you should only use it when you have a lot of sockets (for which it usually works), by embedding it into another event loop (e.g.* kqueue *cough* do funny things during fork.
On the other hand, you only need to call this function in the child process if and only if you want to use the event loop in the child. If you just fork+exec or create a new loop in the child, you don't have to call it at all is usually better than relying on all watchers to be stopped when deciding when a program has finished (especially in interactive programs), but having a program that automatically loops as long as it has to and no longer by virtue of relying on its watchers stopping correctly, that is truly a thing of beauty. will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block your process until at least one new event arrives (which could be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop.
This is useful if you are waiting for some external event in conjunction with something not expressible using other libev watchers (i.e. "roll your own. - If we have been forked, detach and recreate the kernel state as to not disturb the other process. - Update the kernel state with all outstanding changes. - Update the "event loop time" (ev_now ()). - Calculate for how long to sleep or block, if at all (active idle watchers, EVRUN be >=
0) allows libev to delay invocation of I/O and timer/periodic callbacks to increase efficiency of loop iterations (or to increase power-saving opportunities).
The idea is that sometimes your program runs just fast enough to handle one (or very few) event(s) per loop iteration. While this makes the program responsive, it also wastes a lot of CPU time to poll for new events, especially with backends like
0.01, as this approaches the timing granularity of most systems. Note that if you do transactions with the outside world and you can't increase the parallelity, then this setting will limit your transaction rate (if you need to poll once per transaction and the I/O collect interval is 0.01, then you can't do more than 100 transactions per second).
Setting the timeout collect interval can improve the opportunity for saving power, as the program will "bundle" timer callback invocations that are "near" in time together, by delaying some, thus reducing the number of times the process sleeps and wakes up again. Another useful technique to reduce iterations/wake-ups is to use
ev_periodic watchers and make sure they fire on, say, one-second boundaries only.
Example: we only need 0.1s timeout granularity, and we wish not to poll more often than 100 times per second:
ev_set_timeout_collect_interval (EV_DEFAULT_UC_ 0.1); ev_set_io_collect_interval (EV_DEFAULT_UC_ 0.01);_TYPE_set macro.
Each and every callback receives the event loop pointer as first, the registered watcher structure as second, and a bitset of received events as third argument.
The received events usually include a single bit per event type received (you can receive multiple events at the same time). The possible bit masks are:)..
You best act on it by reporting the problem and somehow coping with the watcher being stopped. Note that well-written programs should not receive an error ever, so when your watcher receives it, this usually indicates a bug in your program. multi-threaded programs, though, as the fd could already be closed and reused for another thing, so beware. not).
It is possible that stopped watchers are pending - for example, non-repeating timers are being stopped when they become pending - but calling.
Stopping the watcher, letting libev invoke it, or calling.
In libev, Watcher priorities can be set using
ev_set_priority. See its description for the more technical details such as the actual priority range.
There are two common ways how these these priorities are being interpreted by event loops:
In the more common lock-out model, higher priorities "lock out" invocation of lower priority watchers, which means as long as higher priority watchers receive events, lower priority watchers are not being invoked.
The less common only-for-ordering model uses priorities solely to order callback invocation within a single event loop iteration: Higher priority watchers are invoked before lower priority ones, but they all get invoked before polling for new events.
Libev uses the second (only-for-ordering) model for all its watchers except for idle watchers (which use the lock-out model).
The rationale behind this is that implementing the lock-out model for watchers is not well supported by most kernel interfaces, and most event libraries will just poll for the same events again and again as long as their callbacks have not been executed, which is very inefficient in the common case of one high-priority watcher locking out a mass of lower priority ones.
Static (ordering) priorities are most useful when you have two or more watchers handling the same resource: a typical usage example is having an
ev_io watcher to receive data, and an associated
ev_timer to handle timeouts. Under load, data might be received while the program handles other jobs, but since timers normally get invoked first, the timeout handler will be executed before checking for data. In that case, giving the timer a lower priority than the I/O watcher ensures that I/O will be handled first even under adverse conditions (which is usually, but not always, what you want).
Since idle watchers use the "lock-out" model, meaning that idle watchers will only be executed when no same or higher priority watchers have received events, they can be used to implement the "lock-out" model when required.
For example, to emulate how many other event libraries handle priorities, you can associate an
ev_idle watcher to each such watcher, and in the normal watcher callback, you just start the idle watcher. The real processing is done in the idle watcher callback. This causes libev to continuously poll and process kernel event data for the watcher, but when the lock-out case is known to be rare (which in turn is rare :), this is workable.
Usually, however, the lock-out model implemented that way will perform miserably under the type of load it was designed to handle. In that case, it might be preferable to stop the real watcher before starting the idle watcher, so the kernel will not have to process the event in case the actual processing will be delayed for considerable time.
Here is an example of an I/O watcher that should run at a strictly lower priority than the default, and which should only process data when no other events are pending:
ev_idle idle; // actual processing watcher ev_io io; // actual event watcher idle_cb (EV_P_ ev_idle *w, int revents) { // actual processing read (STDIN_FILENO, ...); // have to start the I/O watcher again, as // we have handled the event ev_io_start (EV_P_ &io); } // initialisation ev_idle_init (&idle, idle_cb); ev_io_init (&io, io_cb, STDIN_FILENO, EV_READ); ev_io_start (EV_DEFAULT_ &io);
In the "real" world, it might also be beneficial to start a timer, so that low-priority connections can not be locked out forever under load. This enables your program to keep a lower latency for important connections during short periods of high load, while not completely locking out less important ones.
This [read-write], which means you can expect it to have some sensible content while the watcher is active, but you can also modify it. Modifying it may not do something sensible or take immediate effect (or do anything at all), but libev will not crash or malfunction in any way..
In general you can register as many read and/or write event watchers per fd as you want (as long as you don't confuse yourself). Setting all file descriptors to non-blocking mode is also usually a good idea (but not required if you know what you are doing).
EAGAIN is far preferable to a program hanging until some data arrives.
If you cannot run the fd in non-blocking mode (for example you should not play around with an Xlib connection), then you have to separately re-test whether a file descriptor is really ready with a known-to-be good interface such as poll (fortunately in the case of Xlib, it already does this on its own, so its quite safe to use). Some people additionally use
SIGALRM and an interval timer, just to be sure you won't block indefinitely.
But really, best use non-blocking mode.
Some backends (e.g. kqueue, epoll) need to be told about closing a file descriptor (either due to calling
close explicitly or any other means, such as
dup2). The reason is that you register interest in some file descriptor, but when it goes away, the operating system will silently drop this interest. If another file descriptor with the same number then is registered with libev, there is no efficient way to see that this is, in fact, a different file descriptor.
To avoid having to explicitly tell libev about such cases, libev follows the following policy: Each time
ev_io_set is being called, libev will assume that this is potentially a new file descriptor, otherwise it is assumed that the file descriptor stays the same. That means that you have to call
ev_io_set (or
ev_io_init) when you change the descriptor even if the file descriptor number itself did not change.
This is how one would do it normally anyway, the important point is that the libev application should not optimise around libev but should leave optimisations to libev..
While not really specific to libev, it is easy to forget about
SIGPIPE: when writing to a pipe whose other end has been closed, your program gets sent a SIGPIPE, which, by default, aborts your program. For most programs this is sensible behaviour, for daemons, this is usually undesirable.
So when you encounter spurious, unexplained daemon exits, make sure you ignore SIGPIPE (and maybe make sure you log the exit status of your daemon somewhere, as that would have given you a big clue). with
ENFILE but not rejecting the connection, leading to libev signalling readiness on the next iteration again (the connection still exists after all), and typically causing the program to loop at 100% CPU usage.
Unfortunately, the set of errors that cause this issue differs between operating systems, there is usually little the app can do to remedy the situation, and no known thread-safe method of removing the connection to cope with overload is known (to me).
One of the easiest ways to handle this situation is to just ignore it - when the program encounters an overload, it will just loop until the situation is over. While this is a form of busy waiting, no OS offers an event-based way to handle this situation, so it's the best one can do.
A better way to handle the situation is to log any errors other than.
Configures an
ev_io watcher. The
fd is the file descriptor to receive events for and
events is either
EV_READ,
EV_WRITE or
EV_READ | EV_WRITE, to express the desire stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents) { ev_io_stop (loop, w); .. read from stdin here (or from w->fd) and handle any I/O errors } ... struct ev_loop *loop = ev_default_init (0); ev_io stdin_readable; ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); ev_io_start (loop, &stdin_readable); ev_run (loop, 0);
ev_timer- relative and optionally repeating timeouts
Timer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.
The timers are based on real time, that is, if you register an event that times out after an hour and you reset your system clock to January last year, it will still time out after (roughly) one hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable (the monotonic clock option helps a lot here).
The callback is guaranteed to be invoked only).
Many real-world problems involve some kind of timeout, usually for error recovery. A typical example is an HTTP request - if the other side hangs, you want to raise some error after a while.
What follows are some ways to handle this problem, from obvious and inefficient to smart and efficient.
In the following, a 60 second activity timeout is assumed - a timeout that gets reset to 60 seconds each time there is activity (e.g. each time some data or other life sign was received).
This is the most obvious, but not the most simple way: In the beginning, start the watcher:
ev_timer_init (timer, callback, 60., 0.); ev_timer_start (loop, timer);
Then, each time there is some activity,.
ev_timer_again);
This is slightly more efficient then stopping/starting the timer each time you want to modify its timeout value, as libev does not have to completely remove and re-insert the timer from/into its internal data structure.
It is, however, even simpler than the "obvious" way to do it.
This method is more tricky, but usually most efficient: Most timeouts are relatively long compared to the intervals between other activity - in our example, within 60 seconds, there are usually many I/O events with associated activity resets.
In this case, it would be more efficient to leave the.
If there is not one request, but many thousands (millions...), all employing some kind of timeout with the same timeout value, then one can do even better:
When starting the timeout, calculate the timeout value and put the timeout at the if it was taken from the beginning of the list.
This way, one can manage an unlimited number of timeouts in O(1) time for starting, stopping and updating the timers, at the expense of a major complication, and having to use a constant timeout. The constant timeout ensures that the list stays sorted.
So which method the best?
Method #2 is a simple no-brain-required solution that is adequate in most situations. Method #3 requires a bit more thinking, but handles many cases better, and isn't very complicated either. In most case, choosing either one is fine, with #3 being better in typical situations.
Method #1 is almost always a bad idea, and buys you nothing. Method #4 is rather complicated, but extremely efficient, something that really pays off after the first million or so of active timers, i.e. it's usually overkill :)_periodics, as these are based on the wall clock time, where your comparisons will always generate correct results.
When you leave the server world it is quite customary to hit machines that can suspend/hibernate - what happens to the clocks during such a suspend?
Some quick tests made with a Linux 2.6.28 indicate that a suspend freezes all processes, while the clocks ( when a monotonic clock source is used. The real time clock advanced as expected, but if it is used as sole clocksource, then a long suspend would be detected as a time jump by libev, and timers would be adjusted accordingly.
I would not be surprised to see different behaviour in different between operating systems, OS versions or even different hardware.
The other form of suspend (job control, or sending a SIGSTOP) will see a time jump in the monotonic clocks and the realtime clock. If the program is suspended for a very long time, and monotonic clock sources are in use, then you can expect).
Configure the timer to trigger after
after seconds. If
repeat is
0., then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again
repeat seconds later, again, and again, until stopped manually.
The timer itself will do a best-effort at avoiding drift, that is, if you configure a timer to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, your program cannot keep up with the timer (because it takes longer than those 10 seconds to do stuff) the timer will not fire more than once per event loop iteration..
The current
repeat value. Will be used each time the watcher times out or
ev_timer_again is called, and determines the next timeout (if any), which is also when any modifications are taken into account.
Example: Create a timer that fires after 60 seconds.
static void one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents) { .. one minute over, w is actually stopped right here } ev_timer mytimer; ev_timer_init (&mytimer, one_minute_cb, 60., 0.); ev_timer_start (loop, &mytimer);
Example: Create a timeout timer that times out after 10 seconds of inactivity.?
Periodic calender or clock). The difference is that wall clock time can run faster or slower than real time, and time jumps are not uncommon (e.g. when you adjust your wrist-watch).
You can tell a periodic watcher to trigger after some specific point in time: for example, if you tell a periodic watcher to trigger "in 10 seconds" (by specifying e.g. with
ev_timer watchers, as those cannot react to time jumps._run recursively).
Lots of arguments, let's sort it out... There are basically three modes of operation, and we will explain them from simplest to most complex: an
ev_periodic that triggers each hour, on the hour (with respect to UTC):
ev_periodic_set (&periodic, 0., 3600., 0);
This doesn't mean there will always be 3600 seconds in between triggers, but only that the callback will be called when the system time shows a full hour (UTC), or more correctly, when the system time is evenly divisible by 3600.
Another way to think about it (for the mathematically inclined) is is
ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now), e.g.:
static ev_tstamp my_rescheduler .
NOTE:. How you do this is, again, up to you (but it is not trivial, which is the main reason I omitted it as an example).). time is divisible by 3600. The callback invocation times have potentially a lot of jitter, but good long-term stability.
static void clock_cb (struct ev_loop *loop, ev_periodic *w, int revents) { ... its now a full hour (UTC, or TAI or whatever your clock follows) } ev_periodic hourly_tick; ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); ev_periodic_start (loop, &hourly_tick);
Example: The same as above, but use a reschedule callback to do it:
#include <math.h> static ev_tstamp my_scheduler_cb .
Configures the watcher to trigger on the given signal number (usually one of the
SIGxxx constants).
The signal the watcher watches out for..
Only the default event loop is capable of handling signals, and therefore you can only register child watchers in the default event loop.
Due to some design glitches inside libev, child watchers will always be handled at maximum priority (their priority is set to
EV_MAXPRI by libev)).
Example:
fork() a new process and install a child handler to wait for its completion.
ev_child cw; static void child_cb (EV_P_ ev_child *w, int revents) { ev_child_stop (EV_A_ w); printf ("process %d exited with status %x\n", w->rpid, w->rstatus); } pid_t pid = fork (); if (pid < 0) // error else if (pid == 0) { // the forked child executes here exit (1); } else { ev_child_init (&cw, child_cb, pid, 0); ev_child_start (EV_DEFAULT_ &cw); }
0.1, but that's usually overkill.
This watcher type is not meant for massive numbers of stat watchers, as even with OS-supported change notifications, this can be resource-intensive.
At the time of this writing, the only OS-specific interface implemented is the Linux inotify interface (implementing kqueue support is left as an exercise for the reader. Note, however, that the author sees no way of implementing
ev_stat semantics with kqueue, except as a hint).
Libev by default (unless the user overrides this) uses the default compilation environment, which means that on systems with large file support disabled by default, you get the 32 bit version of the stat structure. When using the library from programs that change the ABI to use 64 bit file offsets the programs will fail. In that case you have to compile libev with the same flags to get binary compatibility. This is obviously the case with any flags that change the ABI, but the problem is most noticeably displayed with ev_stat and large file support.
The solution for this is to lobby your distribution maker to make large file interfaces available by default (as e.g. FreeBSD does) and not optional. Libev cannot simply switch on large file support because it has to exchange stat structures with application programs compiled using the default compilation environment. polling, but as long as kernel 2.6.25 or newer is used (2.6.24 and older have too many bugs), the path exists (i.e. stat succeeds), and the path resides on a local filesystem (libev currently assumes only ext2/3, jfs, reiserfs and xfs are fully working) libev usually gets away without polling.
There is no support for kqueue, as apparently it cannot be used to implement this functionality, due to the requirement of having a file descriptor open on the object at all times, and detecting renames, unlinks etc. is difficult.
stat ()is a synchronous operation
Libev doesn't normally do any kind of I/O itself, and so is not blocking the process. The exception are
ev_stat watchers - those call
stat (), which is a synchronous operation.
For local paths, this usually doesn't matter: unless the system is very busy or the intervals between stat's are large, a stat call will be fast, as the path data is usually in memory already (except when starting the watcher).
For networked file systems, calling
stat () can block an indefinite time due to network issues, and even under good conditions, a stat call often takes multiple milliseconds.
Therefore, it is best to avoid using
ev_stat watchers on networked paths, although this is fully supported by libev._stat will be unable to detect unless the stat data does change in other ways (e.g. file size).
The solution to this is to delay acting on a change for slightly more than a second (or till slightly after the next full second boundary), using a roughly one-second-delay.
Example: Watch
/etc/passwd for attribute changes.
static void passwd_cb (struct ev_loop *loop, ev_stat *w, int revents) { /* /etc/passwd changed in some way */ if (w->attr.st_nlink) { printf ("passwd current size %ld\n", (long)w->attr.st_size); printf ("passwd current atime %ld\n", (long)w->attr.st_mtime); printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime); } else /* you shalt not abuse printf for puts */ puts ("wow, /etc/passwd is not there, expect problems. " "if this is windows, they already arrived\n"); } ... ev_stat passwd; ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.); ev_stat_start (loop, &passwd);
Example: Like above, but additionally use a one-second delay so we do not miss updates (however, frequent updates will delay processing, too, so one might do the work both on...
Idle watchers trigger events when no other events of the same or higher priority are pending (prepare, check and other idle watchers do not count as receiving "events").
That is, as long as your process is busy handling sockets or timeouts (or even signals, imagine) of the same or higher priority it will not be triggered. But when your process is idle (or only lower-priority watchers are pending), the idle watchers are being called once per event loop iteration - until stopped, that is, or your process receives more events and becomes busy again with higher priority stuff..
ev_idlewatcherand
ev_check- customise your event loop!
Prepare,
ev_check so if you have one watcher of each kind they will always be called in pairs bracketing the blocking call.
Their main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement your own watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful if you cache some data and want to flush it before blocking (for example, in X programs you might want to do an
XFlush () in an
ev_prepare watcher).
This is done by examining in each prepare call which file descriptors need to be watched by the other library, registering
ev_io watchers for them and starting an
ev_timer watcher for any timeouts (many libraries provide exactly this functionality). Then, in the check watcher, you check for any events that occurred (by checking the pending status of all watchers and stopping them) and call back into the library. The I/O and timer callbacks will never actually be called (but must be valid nevertheless, because you never know, you know?).
As another example, the Perl Coro module uses these hooks to integrate coroutines into libev programs, by yielding to other active coroutines during each prepare and only letting the process block if no coroutines are ready to run (it's actually more complicated: it only runs coroutines with priority higher than or equal to the event loop and one coroutine of lower priority, but only once, using idle watchers to keep the event loop from blocking if lower-priority coroutines are active, thus mapping low-priority coroutines to idle/background tasks).).
ev_checkwatcher.
Initialises and configures the prepare or check watcher - they have no parameters of any kind. There are
ev_prepare_set and
ev_check_set macros, but using them is utterly, utterly, utterly and completely pointless.,
Glib::EV embeds EV into the Glib event loop).
Method 1: Add IO watchers and a timeout watcher in a prepare handler, and in a check watcher, destroy them and call into libadns. What follows is pseudo-code only of course. This requires you to either use a low priority for the check watcher or use adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents) { int timeout = 3600000; struct pollfd fds [nfd]; // actual code will need to loop here and realloc etc. adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); /* the callback is illegal, but won't be called as we stop during check */ ev_timer_init (&tw, 0, timeout * 1e-3, 0.); ev_timer_start (loop, &tw); // create one ev_io per pollfd for (int i = 0; i < nfd; ++i) { ev_io_init (iow + i, io_cb, fds [i].fd, ((fds [i].events & POLLIN ? EV_READ : 0) | (fds [i].events & POLLOUT ? EV_WRITE : 0))); fds [i].revents = 0; ev_io_start (loop, iow + i); } } // stop all watchers after blocking static void adns_check_cb (struct ev_loop *loop, ev_check *w, int revents) { ev_timer_stop (loop, &tw); for (int i = 0; i < nfd; ++i) { // set the relevant poll flags // could also call adns_processreadable etc. here struct pollfd *fd = fds + i; int revents = ev_clear_pending (iow + i); if (revents & EV_READ ) fd->revents |= fd->events & POLLIN; if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT; // now stop the watcher ev_io_stop (loop, iow + i); } adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop)); }
Method 2: This would be just like method 1, but you run
adns_afterpoll in the prepare watcher and would dispose of the check watcher.
Method 3: If the module to be embedded supports explicit event notification (libadns does), you can also make use of the actual watcher callbacks, and only destroy/create the watchers in the prepare watcher.); if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now); if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now); } // do not ever call adns_afterpoll
Method 4: Do not use a prepare or check watcher because the module you want to embed is not flexible enough to support it. Instead, you can override their poll function. The drawback with this solution is that the main loop is now no longer controllable by EV. The
Glib::EV module uses this approach, effectively embedding EV as a client into the horrible libglib event loop.
static gint event_poll_func (GPollFD *fds, guint nfds, gint timeout) { int got_events = 0; for (n = 0; n < nfds; ++n) // create/start io watcher that sets the relevant bits in fds[n] and increment got_events if (timeout >= 0) // create/start timer // poll ev).
There are primarily two reasons you would want that: work around bugs and prioritise I/O.
As an example for a bug workaround, the kqueue backend might only support sockets on some platform, so it is unusable as generic backend, but you still want to make use of it because you have many sockets and it scales so nicely. In this case, you would create a kqueue-based loop and embed it into your default loop (which might use e.g. poll). Overall operation will be a bit slower because first libev has to call
poll and then
kevent, but at least you can use both mechanisms for what they are best:
kqueue for scalable sockets and
poll if you want it to work :)
As for prioritising I/O: under rare circumstances you have the case where some fds have to be watched and handled very quickly (with low latency), and even priorities and idle watchers might have too much overhead. In this case you would put all the high priority stuff in one loop and all the rest in a second one, and embed the second one in the first.
As long as the watcher is active, the callback will be invoked every time there might be events pending in the embedded loop. The callback must then call by
ev_embeddable_backends are, which, unfortunately, does not include any portable one.
So when you want to use this feature you will always have to be prepared that you cannot get an embeddable loop. The recommended way to get around this is to have a separate variables for your embeddable loop, try to create it, and if that fails, use the normal loop for everything.
ev_embedand fork
While the
ev_embed watcher is running, forks in the embedding loop will automatically be applied to the embedded loop as well, so no special fork handling is required in that case. When the watcher is not running, however, it is still the task of the libev user to call
ev_loop_fork () as applicable..
Example: Try to get an embeddable event loop and embed it into the default event loop. If that is not possible, use the default loop. The default loop is stored in
loop_hi, while the embeddable loop is stored in
loop_lo (which is
loop_hi in the case no embeddable loop can be used).
struct ev_loop *loop_hi = ev_default_init (0); struct ev_loop *loop_lo = 0; ev_embed embed; // see if there is a chance of getting one that works // (remember that a flags value of 0 means autodetection) loop_lo = ev_embeddable_backends () & ev_recommended_backends () ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) : 0; // if we got one, then embed it, otherwise default to loop_hi if (loop_lo) { ev_embed_init (&embed, 0, loop_lo); ev_embed_start (loop_hi, &embed); } else loop_lo = loop_hi;; if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) { ev_embed_init (&embed, 0, loop_socket); ev_embed_start (loop, &embed); } if (!loop_socket) loop_socket = loop; // now use loop_socket for all sockets, and loop for everything else.
Most uses of
fork () consist of forking, then some simple calls to set up/change the process environment, followed by a call to
exec(). This sequence should be handled by libev without any problems.
This changes when the application actually wants to do event handling in the child, or both parent in child, in effect "continuing" after the fork.
The default mode of operation (for libev, with application help to detect forks) is to duplicate all the state in the child, as would be expected when either the parent or the child process continues.
When both processes want to continue using libev, then this is usually the wrong result. In that case, usually one process (typically the parent) is supposed to continue with all watchers in place as before, while the other process typically wants to start fresh, i.e. without any active watchers.
The cleanest and most efficient way to achieve that with libev is to simply create a new event loop, which of course will be "empty", and use that for new watchers. This has the advantage of not touching more memory than necessary, and thus avoiding the copy-on-write, and the disadvantage of having to use multiple event loops (which do not support signal watchers).
When this is not possible, or you want to use the default loop for other reasons, then in the process that wants to start "fresh", call.
ev_async does not support queueing of data in any way. The reason is that the author does not know of a simple (or any) algorithm for a multiple-writer-single-reader queue that works in all cases and doesn't need elaborate support such as pthreads or unportable memory access semantics.
That means that if you want to queue data, you have to provide your own queue. But at least I can tell you how to implement locking around your queue:
To implement race-free queueing, you simply add to the queue in the signal handler but you block the signal handler in the watcher callback. Here is an example that does that for some fictitious SIGUSR1 handler:
static ev_async mysig; static void sigusr1_handler (void) { sometype data; // no locking etc. queue_put (data); ev_async_send (EV_DEFAULT_ &mysig); } static void mysig_cb (EV_P_ ev_async *w, int revents) { sometype data; sigset_t block, prev; sigemptyset (&block); sigaddset (&block, SIGUSR1); sigprocmask (SIG_BLOCK, &block, &prev); while (queue_get (&data)) process (data); if (sigismember (&prev, SIGUSR1) sigprocmask (SIG_UNBLOCK, &block, 0); }
(Note: pthreads in theory requires you to use
pthread_setmask instead of
sigprocmask when you use threads, but libev doesn't do it either...)..
If both a timeout and an io event at the same time - you probably should give io events precedence.
Example: wait up to ten seconds for data to appear on STDIN_FILENO.
static void stdin_ready (int revents, void *arg) { if (revents & EV_READ) /* stdin might have data for us, joy! */; else if (revents & EV_TIMER) /* doh, nothing entered */; } ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);:
struct my_io { ev_io io; int otherfd; void *somedata; struct whatever *mostinteresting; }; ... struct my_io w; ev_io_init (&w.io, my_cb, fd, EV_READ);
And since your callback will be called with a pointer to the watcher, you can cast it back to your own type:
static void my_cb (struct ev_loop *loop, ev_io *w_, int revents) { struct my_io *w = (struct my_io *)w_; ... }
More interesting and less C-conformant ways of casting your callback function type instead have been omitted.
Another.
Often ;
Here).
Lib the
set call and your compiler is good :), then the method will be fully inlined into the thunking function, making it as fast as a direct C callback.
Example: simple class declaration and watcher initialisation
struct myclass { void io_cb (ev::io &w, int revents) { } } myclass obj; ev::io iow; iow.set <myclass, &myclass::io_cb> (&obj);:
// this is how ev_unref is being declared static void ev_unref (EV_P); // this is how you can declare your typical callback static void cb (EV_P_ ev_timer *w, int revents)
It declares a.
To include only the libev core (all the
ev_* functions), with manual configuration (no autoconf):
#define EV_STANDALONE 1 #include "ev.c"
This will automatically include ev.h, too, and should be done in a single C source file only to provide the function implementations. To use it, do the same for ev.h in all files wishing to use this API (best done by writing a wrapper around ev.h that you can include instead and where you can put other configuration options):
#define EV_STANDALONE 1 #include "ev.h"
Both header files and implementation files can be compiled with a C++ compiler (at least, that's a stated goal, and breakage will be treated as a bug).
You need the following files in your source tree, or in a directory in your include path (e.g. in libev/ when using -Ilibev):
ev.h ev.c ev_vars.h ev_wrap.h ev_win32.c required on win32 platforms only ev_select.c only when select backend is enabled (which is enabled by default) ev_poll.c only when poll backend is enabled (disabled by default) ev_epoll.c only when the epoll backend is enabled (disabled by default) ev_kqueue.c only when the kqueue backend is enabled (disabled by default) ev_port.c only when the solaris port backend is enabled (disabled by default)
ev.c includes the backend files directly when enabled, so you only need to compile this single file.
To include the libevent compatibility API, also include:
#include "event.c"
in the file including ev.c, and:
#include "event.h"
in the files that want to use the libevent API. This also includes ev.h.
You need the following additional files for this:
event.h event.c).
When doing priority-based operations, libev usually has to linearly search all the priorities, so having many of them (hundreds) uses a lot of space and time, so using the defaults of five priorities (-2 .. +2) is usually fine.
If your embedding application does not need any priorities, defining these both to
0 will save some memory and CPU.:
Symbols.ev for libev proper Symbols.event for the libevent emulation
This can also be used to rename all public symbols to avoid clashes with multiple versions of libev linked together (which is obviously bad in itself, but sometimes it is inconvenient to avoid this).
A sed command like this will create wrapper
"
All libev functions are reentrant and thread-safe unless explicitly documented otherwise, but libev implements no locking itself. This means that you can use as many loops as you want in parallel, as long as there are no concurrent calls into any libev function with the same loop parameter (
ev_default_* calls have an implicit default loop parameter, of course): libev guarantees that different event loops share no data structures that need any locking.
Or to put it differently: calls with different loop parameters can be done concurrently from multiple threads, calls with the same loop parameter must be done serially (but can be done from different threads, as long as only one thread ever is inside a call at any point in time, e.g. by using a mutex per loop).
Specifically to support threads (and signal handlers), libev implements so-called
ev_async watchers, which allow some limited form of concurrency on the same event loop, namely waking it up "from the outside".
If you want to know which design (one loop, locking, or multiple loops without or something else still) is best for your problem, then I cannot help you, but here is some generic advice:
This helps integrating other libraries or software modules that use libev themselves and don't care/know about threading.
Doing this is almost never wrong, sometimes a better-performance model exists, but it is always a good start.
Choosing a model is hard - look around, learn, know that usually you can do better than you currently
ev_async watcher from the default loop watcher callback into the event loop interested in the signal.
See also "THREAD LOCKING EXAMPLE"..
Depending on your compiler and compiler settings, you might get no or a lot of warnings when compiling libev code. Some people are apparently scared by this.
However, these are unavoidable for many reasons. For one, each compiler has different warnings, and each user has different tastes regarding warning options. "Warn-free" code therefore cannot be a goal except when targeting a specific compiler and compiler-version.
Another reason is that some compiler warnings require elaborate workarounds, or other changes to the code that make it less clear and less maintainable.
And of course, some compiler warnings are just plain stupid, or simply wrong (because they don't actually warn about the condition their message seems to warn about). For example, certain older gcc versions had some warnings that resulted in an extreme number of false positives. These have been fixed, but some people still insist on making code warn-free with such buggy versions.
While libev is written to generate as few warnings as possible, "warn-free" code is not a goal, and it is recommended not to build libev with any compiler warnings enabled unless you are prepared to cope with them (e.g. by ignoring them). Remember that warnings are just that: warnings, not errors, or proof of bugs.
Valgrind has a special section here because it is a popular tool that is highly useful. Unfortunately, valgrind reports are very hard to interpret.
If you think you found a bug (memory leak, uninitialised data access etc.) in libev, then check twice: If valgrind reports something like:
==2274== definitely lost: 0 bytes in 0 blocks. ==2274== possibly lost: 0 bytes in 0 blocks. ==2274== still reachable: 256 bytes in 1 blocks.
Then there is no memory leak, just as memory accounted to global variables is not a memleak - the memory is still being referenced, and didn't leak.
Similarly, under some circumstances, valgrind might report kernel bugs as if it were a bug in libev (e.g. in realloc or in the poll backend, although an acceptable workaround has been found here), or it might be confused.
Keep in mind that valgrind is a very good tool, but only a tool. Don't make it into some kind of religion.
If you are unsure about something, feel free to contact the mailing list with the full valgrind report and an explanation on why you think this is a bug in libev (best check the archives, too :). However, don't be annoyed when you get a brisk "this is no bug" answer and take the chance of learning how to interpret valgrind properly.
If you need, for some reason, empty reports from valgrind for your project I suggest using suppression lists.
GNU.
The whole thing is a bug if you ask me - basically any system interface you touch is broken, whether it is locales, poll, kqueue or even the OpenGL drivers.
kqueue.
errn
ENOBUFS if the buffer is too large, so make sure you only write small amounts into your sockets (less than a megabyte seems safe, but this apparently depends on the amount of memory available).
Due to the many, low, and arbitrary limits on the win32 platform and the abysmal performance of winsockets, using a large number of sockets is not recommended (and not reasonable). If your program needs to use more than a hundred or so sockets, then likely it needs to use a totally different implementation for windows, as libev offers the POSIX readiness notification model, which cannot be implemented efficiently on windows "
selectfunction and
EV_FD_TO_WIN32_HANDLE preprocessor symbols for more info.
The configuration for a "naked" win32 using the Microsoft runtime libraries and raw winsocket select is:
#define EV_USE_SELECT 1 #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */
Note that winsockets handling of fd sets is O(n), so you can easily get a complexity in the O(n²) range when using win32..
In this section the complexities of (many of) the algorithms used inside libev will be documented. For complexity discussions about backends see the documentation for
ev_default_init.
All of the following are about amortised time: If an array needs to be extended, libev needs to realloc and move the whole array, but this happens asymptotically rarer with higher number of elements, so O(1) might mean that libev does a lengthy realloc operation in rare cases, but on average it is much faster and asymptotically approaches constant time.. | http://search.cpan.org/dist/EV/libev/ev.pod | CC-MAIN-2014-52 | refinedweb | 8,160 | 57.71 |
Mostly, Computer programmers, are unfamiliar with the details of the linking process. Terms such as externally visible or just external not externally visible (or not external, only visible within one translation unit) are used by developers when discussing issues covered by the C term linkage. From the developers point of view, the most important property is whether an object can be referenced from more than one translation unit. The common usage terms external and not external effectively describe the two states that are of interest to developers. Unless a developer wants to become an expert on the C Standard, the cost/benefit of learning how to apply the technically correct terminology (linkage) is not worthwhile.
What does a linker do?
It’s simple: a linker converts object files into executable and shared libraries. Let’s look at what that means. For cases where a linker is used, the software development process consists of writing program code in some language: e.g., C or C++ or Fortran (but typically not Java). A compiler translates this program code, which is human readable text, into another form of human readable text known as assembly code. Assembly code is a readable form of the machine language which the computer can execute directly. An assembler is used to turn this assembly code into an object file. For completeness, note that some compilers include an assembler internally, and produce an object file directly.
History
Before 1940’s, the earliest computers were programmed entirely in machine language. Programmers would write out the symbolic programs on sheets of paper, hand assemble them into machine code and then toggle the machine code into the computer, or perhaps punch it on paper tape or cards. If any instruction had to added or deleted, the entire program had to inspected again and re-analyse the code or perhaps re-write the code from starting to end again.
In between 1940 – 1952, the Assembly Languages are developed. It is also known as second generation programming language. One of the early developments was a symbolic assembler. Instead of writing down a series of binary numbers, the programmer would write down a list of machine instructions, using human-readable symbols. A special program, the assembler, would convert these symbolic instructions into object or machine code. Assembly languages have the advantage that they are easier to understand than raw machine code, but still give access to all of the power of the computer (as each assembler symbol translates directly into a specific machine instruction). Assembly languages have the disadvantage that they are still very close to machine language. These can be difficult for a human to follow and understand and time-consuming for a human to write. Also, programs written in assembly are tied to a specific computer hardware and can’t be reused on another kind of computer. The human readable version of assembly code is known as source code (it is the source that the assembler converts into object code).
After 1952, the third generation programming languages started to appear, they are also known as high level programming language. A third-generation programming language (3GL) is a refinement of a second-generation programming language. The second generation of programming languages brought logical structure to software. The third generation brought refinements to make the languages more programmer-friendly. This includes features like improved support for aggregate data types, and expressing concepts in a way that favours the programmer, not the computer (e.g. no longer needing to state the length of multi-character (string) literal’s in Fortran). A third generation language improves over a second generation language by having the computer take care of non-essential details, not the programmer. “High level language” is a synonym for third-generation programming language. First introduced in the late 1950s, Fortran, ALGOL, and COBOL are early examples of this sort of language. Most popular general-purpose languages today, such as C, C++, C#, Java, BASIC and Delphi, are also third-generation languages.
Basic Linker Data Types
The linker operates on a small number of basic data types: symbols, relocations, and contents. These are defined in the input object files. Here is an overview of each of these.
A symbol is basically a name and a value. Many symbols represent static objects in the original source code–that is, objects which exist in a single place for the duration of the program. For example, in an object file generated from C code, there will be a symbol for each function and for each global and static variable. The value of such a symbol is simply an offset into the contents. This type of symbol is known as a defined symbol. It’s important not to confuse the value of the symbol representing the variable my_global_var with the value of my_global_var itself. The value of the symbol is roughly the address of the variable: the value you would get from the expression &my_global_var in C. Symbols are also used to indicate a reference to a name defined in a different object file. Such a reference is known as an undefined symbol. During the linking process, the linker will assign an address to each defined symbol, and will resolve each undefined symbol by finding a defined symbol with the same name.
A relocation is a computation to perform on the contents. Most relocations refer to a symbol and to an offset within the contents. Many relocations will also provide an additional operand, known as the added. A simple, and commonly used, relocation is “set this location in the contents to the value of this symbol plus this added.” The types of computations that relocations do are inherently dependent on the architecture of the processor for which the linker is generating code. For example, RISC processors which require two or more instructions to form a memory address will have separate relocations to be used with each of those instructions; for example, “set this location in the contents to the lower 16 bits of the value of this symbol.” During the linking process, the linker will perform all of the relocation computations as directed. A relocation in an object file may refer to an undefined symbol. If the linker is unable to resolve that symbol, it will normally issue an error (but not always: for some symbol types or some relocation types an error may not be appropriate).
The contents are what memory should look like during the execution of the program. Contents have a size, an array of bytes, and a type. They contain the machine code generated by the compiler and assembler (known as text). They contain the values of initialized variables (data). They contain static unnamed data like string constants and switch tables (read-only data or rdata). They contain uninitialized variables, in which case the array of bytes is generally omitted and assumed to contain only zeroes (bss). The compiler and the assembler work hard to generate exactly the right contents, but the linker really doesn’t care about them except as raw data. The linker reads the contents from each file, concatenated them all together sorted by type, applies the relocations, and writes the result into the executable file.
Basic Linker Operation
At this point we already know enough to understand the basic steps used by every linker:
- Read the input object files. Determine the length and type of the contents. Read the symbols.
- Build a symbol table containing all the symbols, linking undefined symbols to their definitions.
- Decide where all the contents should go in the output executable file, which means deciding where they should go in memory when the program runs.
- Read the contents data and the relocations. Apply the relocations to the contents. Write the result to the output file.
- Optionally write out the complete symbol table with the final values of the symbols.
C – International Standard
According to International Standard Committee Draft, June, 25, 2010, defined the linkage of identifier as under:
- An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. There are three kinds of linkage: external, internal, and none.
- In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.
- If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage.
-. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier.
- The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.
- If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.
Rule No.1 describe what are linkage and kinds of linkage’s and from Rule No.2 to Rule No.7, it describe the conditions of external, internal and no linkage. Let us first study what are 3 kinds of Linkage’s they are:
External Linkage.
Internal Linkage
A function declared inside a block will usually have external linkage. An object declared inside a block will usually have external linkage if it is specified extern. If a variable that has static storage is defined outside a function, the variable has internal linkage and is available from the point where it is defined to the end of the current translation unit. Internal linkage limits access to the data or function to the current file. The following kinds of identifiers have internal linkage:
- Objects, references, or functions explicitly declared static.
- Objects or references declared in namespace scope (or global scope in C) with the specifier const and neither explicitly declared extern, nor previously declared to have external linkage.
- Data members of an anonymous union.
No Linkage
The following kinds of identifiers have no linkage:
- Names that have neither external or internal linkage
- Names declared in local scopes (with exceptions like certain entities declared with the extern keyword)
- Identifiers that do not represent an object or a function, including labels, enumerators, typedef names that refer to entities with no linkage, type names, function parameters, and template names
You cannot use a name with no linkage to declare an entity with linkage. For example, you cannot use the name of a class or enumeration or a typedef name referring to an entity with no linkage to declare an entity with linkage. The following example demonstrates this:
int main() { struct A {}; // extern A a1; typedef A myA; // extern myA a2; }
The compiler will not allow the declaration of a1 with external linkage. Class A has no linkage. The compiler will not allow the declaration of a2 with external linkage. The typedef name a2 has no linkage because A has no linkage.
Important Points about extern keywords with examples
1. It is default storage class of all global variables as well all functions.:
#include <stdio.h> int i; //By default it is extern variable int main(){ printf("%d",i); return 0; }
Output: 0
2. When we use extern modifier with any variables it is only declaration i.e. memory is not allocated for these variable. If it is not initialize the compiler would show error unknown symbol as under:
#include <stdio.h> extern int i; //extern variable int main(){ printf("%d",i); return 0; }
Output: Compilation error, undefined symbol i
To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables. For example:
#include <stdio.h> extern int i=10; //extern variable int main(){ printf("%d",i); return 0; }
Output: 10
3. If you will not use extern keyword with global variables then compiler will automatically initialize with default value to extern variable. Default initial value of extern integral type variable is zero otherwise null. For example:
#include <stdio.h> char c; int i; float f; char *str; int main(){ printf("%d %d %f %s", c, i, f, str); return 0; }
Output: 0 0 0.000000 (null)
4. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separation. Extern variable can be initialize globally only. For example:
#include <stdio.h> int main(){ extern int i = 10; //Trying to initialize extern var locally printf("%d", i); return 0; }
Output: Compilation error: Cannot initialize extern variable
5. If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error. For example’s:
#include <stdio.h> int main(){ extern int i; //It will search initialization printf("%d", i); return 0; } int i =20;
Output: 20
#include <stdio.h> int main(){ extern int i; //It will search initialization printf("%d", i); return 0; } extern int i=20; //initialization of extern var
Output: 20
#include <stdio.h> int main(){ extern int i; //It will search initialization printf("%d", i); return 0; } static int i=20; //initialization of static var i
Output: 20
#include <stdio.h> int main(){ extern int i; //declared but not initialization printf("%d", i); return 0; }
Output: Compilation error: unknown symbol i
6. A particular extern variable can be declared many times but we can initialize at only one time. For example:
extern int i; //Declaration of variable int i=25; //Initialization of var extern int i; // Again declaration #include <stdio.h> int main(){ extern int i; //Again declaration printf("%d", i); return 0; }
Output: 25
extern int i; //Declaration of variable int i=25; //Initialization of var #include <stdio.h> int main(){ printf("%d", i); return 0; } int i =20; //Again Initialization
Output: Compiler error: Multiple initialization of variable i
7. We cannot write any assignment statement globally. Assigning any value to the variable at the time of declaration is known as initialization while assigning any value to variable not at the time of declaration is known assignment. For example:
#include <stdio.h> extern int i; //Declaration of variable int i=10; //Initialization of var i = 25; //Assignment statement int main(){ printf("%d", i); return 0; }
Output: Compilation error
#include <stdio.h> extern int i; //Declaration of variable int main(){ i=25; //Assignment Statement printf("%d", i); return 0; } int i = 10; //Initialization of var
Output: 25
30.756074 76.787399
Advertisements
interesting information, thanks. hope you add some more posts soon.
good work, continue the great blog.
cool website, rss following now and wish to see some similar posts soon.
made my way to your site from bing and and am glad i found it, hope you keep up the good work | https://vineetgupta22.wordpress.com/2011/11/15/linkages-of-identifiers/ | CC-MAIN-2017-30 | refinedweb | 2,513 | 54.12 |
Programming Reference/Librarys
Question & Answer
Q&A is closed
Q&A is closed
#include "graphics.h" void readimagefile( const char* title=NULL, int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX );
<code c> The readimagefile function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function reads a BMP, GIF, JPG, ICO, EMF or WMF image file and displays it in part of the current active window. The filename may be NULL (in which case a windows file save dialog box is opened to allow the user to select a file name).
See also
getimage printimage writeimagefile
no output of example at the moment do not hesitate and add it... | https://code-reference.com/c/graphics.h/readimagefile | CC-MAIN-2022-05 | refinedweb | 126 | 63.29 |
In this tutorial, we are going to learn how to add labels in React user forms.
React framework ignores for attribute for label element.
What does “for” attribute do in HTML tag?
React provides web accessibility guidelines to create a website. It helps us to navigate and access the page content by everyone. Labels are helpful to understand human-readable text for each form input control and help blind, keyboard, and mouse users.
When you are creating an form in Html pages, You will create a label and input that bind together as seen below
<label for="name">Name</label> <input id="name" type="text" />
Usually, labels are bound to input text using the
for attribute.
Input control id is matched with for attribute of the label. This applies to checkboxes, radio, and select controls.
if you use the same code in React JSX, It breaks during component loading
and throws below error
Invalid DOM property
for. Did you mean
htmlFor?`
React has no
for property for labels.
It defined the
htmlFor attribute.
The reason is, you are writing HTML code in JSX syntax. JSX is an extension to javascript which executes javascript code.
for is a keyword or reserved word in javascript. So we can not use it directly.
So we have to use the
htmlFor attribute like seen below.
Note: React is case sensitive, the first-word letter is small, and second letter work is capital Here is a react for label example component
import React, { Component } from 'react'; import { render } from 'react-dom'; import Hello from './Hello'; import './style.css'; interface AppProps {} interface AppState { name: string; } class App extends Component<AppProps, AppState> { constructor(props) { super(props); this.state = { name: 'React' }; } render() { return ( <div> <label htmlFor="name">Name</label> <input id="name" type="text" /> </div> ); } } render(<App />, document.getElementById('root'));
Once this component is rendered, generated DOM contains
for attribute instead of
htmlFor attribute for an label
When you inspect the code, You will see the below code
<html class=" "><head> </head> <body><div id="root"><div><label for="name">Name</label><input id="name" type="text"></div></div></body></html> | https://www.cloudhadoop.com/react-label-for-attribute/ | CC-MAIN-2022-21 | refinedweb | 353 | 56.76 |
Delay's Blog is the blog of David Anson, a Microsoft developer who works with C#, XAML, HTML, and Azure.
@DavidAns
Just over a year ago, a couple of readers asked me about a WPF/Silverlight Panel that arranged things to make "best use" of available space without requiring the developer to set a bunch of stuff up in advance or know how many child elements there would be. Interestingly, this is not a scenario the default Panel implementations handle particularly well...
Panel
Grid [WPF/SL/WP] is capable of pretty much anything, but requires the developer to explicitly specify how everything lines up relative to the rows and columns they must manually define.
StackPanel [WPF/SL/WP] arranges an arbitrary number of items in a tightly-packed line, but overflows when there are too many and leaves empty space when there are too few.
Canvas [WPF/SL/WP] provides the ultimate in flexibility, but contains absolutely no layout logic and pushes all that overhead onto the developer.
WrapPanel [WPF/SLTK/WPTK] flows its elements "book-style" left-to-right, top-to-bottom, but runs content off the screen when there's not enough room and can size things surprisingly unless you tell it how big items should be.
Aside: When scrolling content that doesn't fit is acceptable, WrapPanel can be quite a good choice. And if you like the idea, but want something a little more aesthetically pleasing, please have a look at my BalancedWrapPanel implementation... :)
WrapPanel
Further aside: On the other hand, if you're looking for something more like a StackPanel but with multiple columns (or rows), you might instead be interested in my BandedStackPanel implementation.
StackPanel
DockPanel [WPF/SLTK] crams everything against the edge of its layout slot and leaves a big "chunk" in the center for whatever element is lucky enough to end up there.
UniformGrid [WPF] does okay at sensible layout without a lot of fuss - but its default behavior can leave a lot of blank space and so it's best if you tell it in advance how many items there are.
That said, please don't get me wrong: I'm not complaining about the default set of layout containers - I think they're all good at what they do! However, in the context of the original "just do the right thing for me" scenario, none of them quite seems ideal.
So when this question came up before, I mentioned I'd written some code that seemed pretty relevant, but that it was for Windows Forms and therefore didn't map cleanly to the different layout model used by Silverlight and WPF. Soon thereafter, I created a sample project to implement a "best fit" panel for Silverlight and WPF (and got nearly all the code written!) - but then found myself distracted by other topics and never managed to write it up formally...
Until now!
Today I'm sharing the three Panel classes I originally wrote for Silverlight and WPF, two abstract base classes they're built on, an extra Panel I wrote just for this post and a Windows Phone 7 sample application! (Because this code supports Silverlight 3, it works just as well on the phone as on the desktop.) Hopefully the extra goodness in today's release will offset the delay in posting it... :)
The foundation for everything, BestFitPanel is an abstract base class that implements MeasureOverride and ArrangeOverride to arrange its children in a grid that's M columns wide and N rows high. What's nice is that the values of M and N are left to subclasses to define by overriding the CalculateBestFit method. Therefore, a subclass only needs to worry about columns/rows and the base class only needs to worry about handling layout.
BestFitPanel
CalculateBestFit
MostBigPanel is a BestFitPanel subclass that figures out which values of M and N maximize the length of the smaller dimension (be it width or height) of each item. In other words, it avoids long, skinny rectangles in favor of more evenly proportioned ones.
MostBigPanel
MostFullPanel is a BestFitPanel subclass that maximizes the total area occupied by the Panel's children. Specifically, an arrangement without any empty cells will be preferred over one with an empty cell or two - even if the shape of the resulting items is less balanced.
MostFullPanel
Sometimes it's nice to optimize for the "shape" of individual items - and for that there's the BestAnglePanel abstract base class which chooses the combination of M and N that yields items with a diagonal closest to some angle A determined by the GetIdealAngle override.
BestAnglePanel
GetIdealAngle
MostSquarePanel is a BestAnglePanel subclass that uses a value of 45° for A and therefore prefers arrangements where items are closest to being square.
MostSquarePanel
MostGoldenPanel, on the other hand, is a BestAnglePanel subclass that uses a value for A that matches that of a horizontally-oriented golden rectangle. Golden rectangles are said to be among the most aesthetically pleasing shapes, and this class makes it easy to create layouts based around them.
MostGoldenPanel
Of course, there are very few values of M and N to choose from, so it's not uncommon that all the implementations above choose the same values. The interesting differences tend to show up at various "special" sizes where each BestFitPanel selects a different layout. This is why the sample application allows you to enable all the panels at once: the sample content is translucent, so you can see where things differ and how each implementation is handling a particular configuration. I made sure all the arrangements above were unique - here's how it looks when they're all shown at once:
For a real-world example of BestFitPanel in action, I've adapted the "ImageLoading" sample from my Windows Phone 7 PhonePerformance project to use MostBigPanel (which is what I would have used if I'd written this post beforehand!). If you're not familiar with that sample, it finds all the followers of an arbitrary Twitter account and shows their images. Because it's impossible to know in advance how many followers an account has, trying to use one of the "in-box" Panel implementations is likely to be tricky or require writing code to configure things at run-time. But BestFitPanel makes this scenario easy by automatically showing all the items and optimizing for the most important attribute ("bigness" in this case). Here's the same code/XAML with different numbers of followers (400, 200, and 100) to show how things "just work":
[Click here to download the complete source code for all the BestFitPanels along with sample projects for Silverlight, WPF, and Windows Phone 7.]
The concept of a reusable, container-agnostic Panel for layout is tremendously powerful. The "stock" implementations for Silverlight, WPF, and Windows Phone are all quite useful, but sometimes you'll find that writing a custom Panel is the only way to get exactly the layout you're looking for. Fortunately, layout code is pretty straightforward - and classes like BestFitPanel and BestAnglePanel make it even easier. So the next time you're looking for a flexible container that works sensibly without requiring a bunch of prior knowledge or hand-holding, I hope you'll remember this post and consider using a BestFitPanel - or a custom subclass! :)
I used .NET 3.5 to write the first version of Insomnia about a year and a half ago. Its purpose in life is to make it easy for anyone to temporarily prevent their computer from going to sleep without having to futz with system-wide power options every time. Insomnia did its job well and people used it in ways I didn't expect: there were requests to allow the window to be minimized to the notification area, so I posted an update a few months later which allowed that. As a result, some people leave Insomnia running for extended periods of time (e.g., many days) and seemed likely to benefit from a version that didn't include the overhead of the .NET Framework, so I created new, native-code 32- and 64-bit versions of Insomnia late last year. These new versions did exactly what they were intended to and were also well received - but there's a catch...
Every couple of weeks or so, Insomnia gets featured by one of those "cool app of the day" sites (which is awesome, so thanks for that!). I never know when it's going to happen, but I can tell exactly when it does because I suddenly get a flurry of comments telling me the native-code versions don't run on Windows XP...
Aside: Many of you may be too young to remember; Windows XP is an operating system Microsoft released about ten years ago - practically an eternity in computing terms! And yet, a lot of people are still running XP... ;)
Although I didn't set out to not support Windows XP, I also didn't make a specific effort to support it - and as the saying goes, "if you don't test it, it won't work". Well it didn't work, so I investigated and summarized my findings in a reply on my blog:. :)
For what it's worth, I don't recall anybody coming back with a compelling reason why XP support is necessary - but after getting another round of XP feedback recently, I decided it was something I should do simply because it comes up so often. Therefore, I'm happy to announce that Insomnia's native 32-bit and 64-bit versions now support Windows XP!
Note: With today's update (and in lieu of feedback to the contrary), the native versions of Insomnia are believed to run everywhere the .NET version does. Because there's no functional difference between the native- and managed-code implementations, I'll probably deprecate the .NET version soon. (Please don't get me wrong: I love the significant productivity benefits of using .NET! They're just moot here because I'm already doing the work to maintain the native implementations.)
Notes:
By far the biggest change with this release is the replacement of the SysLink control with one I wrote called IdealSizeStatic. Recall from the previous post that there were two things I liked about SysLink: its ability to return an "ideal size" and its ability to render hyperlinks. Both of these features worked like I wanted, but the lack of support for LM_GETIDEALSIZE on XP was a deal-breaker. When creating IdealSizeStatic, I kept things as simple as possible while also being consistent with how SysLink operates (ex: the use of WM_CTLCOLORSTATIC and WM_SETFONT) just in case I decide to switch back some day. IdealSizeStatic ends up being a pretty general-purpose control that offers WM_GETIDEALSIZE for querying the bounds (width and height) of its text - which is handy for the WPF-like layout pass I implemented in Insomnia.
IdealSizeStatic
SysLink
WM_GETIDEALSIZE
Despite my goal of keeping IdealSizeStatic as simple as possible, I didn't want to give up on the hyperlink functionality Insomnia already used, so I did the work to support that scenario. Specifically, if the first character of its window title is '_', IdealSizeStatic assumes it's showing a link, strips off the '_' prefix, and renders the control text in blue. Assuming WS_TABSTOP has also been set, it will show a focus rectangle when relevant and respond to mouse left-button clicks and space bar presses by calling ShellExecuteEx to open the link in the user's preferred web browser.
IdealSizeStatic won't win any awards for "Win32 control of the year", but it seems to do just enough to be an adequate replacement for SysLink. :)
Having purged the SysLink control, Insomnia no longer has a dependency on the COMCTL32 common control DLL and the corresponding code to initialize it and incorporate the necessary manifest has been removed.
The other problem with running on XP was the use of the LoadIconMetric API to retrieve the application icon for the notification area. Fortunately, it's pretty simple to fall back to the LoadImage API instead - though it doesn't offer the same "auto-scaling" magic the original function does.
Speaking of icons, one curious problem with XP was that Windows Explorer showed the default application icon instead of the custom one embedded in the Insomnia executable. This ends up being because the custom ICO file generator I wrote/use outputs icon images in the 32-bit alpha-blended PNG format and that format isn't supported on Windows XP. This time around, I've also embedded 16x16 and 32x32 icons with the older 24-bit image+mask format. Because this type is recognized by XP, the icon shows up correctly.
Aside: Unfortunately, XP still has a bit of trouble rendering the bottom-most pixels of the 32x32 icon in the application's property page. But that property page seems to have a variety of troubles with icons - there was a similar issue with the previous version even under Windows 7!
I've also fixed a couple of minor issues I noticed along the way - none of which should matter much in practice. The new version of the 32-bit and 64-bit builds of Insomnia is 2011-03-19. The version number of the .NET build has not changed and remains 2010-01-29.
[Click here to download the 32-bit, 64-bit, and .NET builds of Insomnia along with the complete source code for everything.]
I initially put off supporting XP because I figured very few people still used it. However, the steady stream of feedback from XP users finally convinced me there's enough interest to make the effort worthwhile. Windows 7 and Windows Vista users won't see functional differences with this release, but they will benefit from the slightly reduced footprint that comes from breaking the ties to COMCTL32.dll. My IdealSizeStatic control isn't a perfect replacement for the SysLink control, but it gets close enough - and does so without being overly complex.
COMCTL32.dll
Windows XP users: I hope you like the new support. Thanks for your patience! :)
In the previous post, I showed how to combine .NET 4's "type embedding" capability with the Managed Extensibility Framework (MEF) to create an application that can be upgraded without breaking existing extensions. In that post, I described the notion of a MEF "contract assembly" thusly:.
The idea is pretty straightforward: an application's public API should be constant even if the underlying implementation changes dramatically. Similarly, the act of servicing an application (e.g., patching it, fixing bugs, etc.) should never require updates to its public contract assembly.
Fortunately it's pretty easy to ensure a contract assembly contains only interfaces and .NET Framework classes (which are safe because they're automatically versioned for you). But things get a little tricky when you decide to expose a custom event...
Imagine your application defines an event that needs to pass specific information in its EventArgs. The first thing you'd do is create a subclass - something like MyEventArgs - and store the custom data there. Because the custom event is part of a public interface, it's part of the contract assembly - and because the contract assembly is always self-contained, the definition of MyEventArgs needs to be in there as well. However, while MyEventArgs is probably quite simple, its implementation is... um... an implementation detail [ :) ] and does not belong in the contract assembly.
MyEventArgs
Okay, no problem, create an IMyEventArgs interface for the custom properties/methods (which is perfectly acceptable for a contract assembly) and then add something like the following to the application (or an extension):
IMyEventArgs
class MyEventArgs : EventArgs, IMyEventArgs
The public interface (in the contract assembly) only needs to expose the following and all will be well:
event EventHandler<IMyEventArgs> MyEvent;
Oops, sorry! No can do:
The type 'IMyEventArgs' cannot be used as type parameter 'TEventArgs' in
the generic type or method 'System.EventHandler<TEventArgs>'. There is no
implicit reference conversion from 'IMyEventArgs' to 'System.EventArgs'.
The compiler is complaining there's no way for it to know that an arbitrary implementation of IMyEventArgs can always be converted to an EventArgs instance (which is what the TEventArgs generic type parameter of EventHandler<TEventArgs> is constrained to). Because there's not an obvious way to resolve this ambiguity (the implicit keyword doesn't help because "user-defined conversions to or from an interface are not allowed"), you might be tempted to move the definition of MyEventArgs into the contract assembly and pass that for TEventArgs instead. That will certainly work (and it's not the worst thing in the world) but it feels like there ought to be a better way...
EventArgs
TEventArgs
And there is! Instead of using a new-fangled generic event handler, we could instead use a classic .NET 1.0-style delegate in our contract assembly:
/// <summary>
/// Interface for extensions to MyApplication.
/// </summary>
public interface IMyContract
{
/// <summary>
/// Simple method.
/// </summary>
void MyMethod();
/// <summary>
/// Simple event with custom interface-based EventArgs.
/// </summary>
event MyEventHandler MyEvent;
}
/// <summary>
/// Delegate for events of type IMyEventArgs.
/// </summary>
/// <param name="o">Event source.</param>
/// <param name="e">Event arguments.</param>
public delegate void MyEventHandler(object o, IMyEventArgs e);
/// <summary>
/// Interface for custom EventArgs.
/// </summary>
public interface IMyEventArgs
{
/// <summary>
/// Simple property.
/// </summary>
string Message { get; }
}
With this approach, the contract assembly no longer needs to include the concrete MyEventArgs implementation: the delegate above is strongly-typed and doesn't have the same constraint as EventHandler<TEventArgs>, so it works great! With that in place, the implementation details of the MyEventArgs class can be safely hidden inside the extension (or application) assembly like so:
EventHandler<TEventArgs>
/// <summary>
/// Implementation of a custom extension for MyApplication.
/// </summary>
[Export(typeof(IMyContract))]
public class MyExtension : IMyContract
{
/// <summary>
/// Simple method outputs the extension's name and invokes its event.
/// </summary>
public void MyMethod()
{
Console.WriteLine("MyExtension.MyMethod");
var handler = MyEvent;
if (null != handler)
{
handler(this, new MyEventArgs("MyEventArgs"));
}
}
/// <summary>
/// Simple event.
/// </summary>
public event MyEventHandler MyEvent;
}
/// <summary>
/// Implementation of a custom interface-based EventArgs.
/// </summary>
class MyEventArgs : EventArgs, IMyEventArgs
{
/// <summary>
/// Simple property.
/// </summary>
public string Message { get; private set; }
/// <summary>
/// Initializes a new instance of the MyEventArgs class.
/// </summary>
/// <param name="message">Property value.</param>
public MyEventArgs(string message)
{
Message = message;
}
}
The sample application I've created to demonstrate this practice in action (a simple executable/contract assembly/extension assembly trio) is quite simple and works just as you'd expect. Here's the output:
MyApplication.Run
MyExtension.MyMethod
MyEventArgs
[Click here to download the complete source code for the MefContractTricks sample.]
Keeping a MEF application's contract assemblies as pure and implementation-free as possible is a good and noble goal. There may be times when it is necessary to make compromises and allow implementation details to sneak into the contract assembly, but the use of custom event arguments does not need to be one of them!
So instead of being generic - and failing - go retro for the win! :)
One of the neat new features in version 4 of the .NET Framework is something called "type equivalence" or "type embedding". The basic idea is to embed at compile time all the type information about a particular reference assembly into a dependent assembly. Once this is done, the resulting assembly no longer maintains a reference to the other assembly, so it does not need to be present at run time. You can read more about type embedding in the MSDN article Type Equivalence and Embedded Interop Types.
Although type equivalence was originally meant for use with COM to make it easier to work against multiple versions of a native assembly, it can be used successfully without involving COM at all! The MSDN article Walkthrough: Embedding Types from Managed Assemblies (C# and Visual Basic) explains more about the requirements for this along with explicit steps to use type embedding with an assembly.
Here's a simple interface that is enabled for type embedding:();
}
}
Another thing that's new with .NET 4 (though it had previously been available on CodePlex) is the Managed Extensibility Framework (MEF). MEF makes it easy to implement a "plug-in" architecture for applications where assemblies are loosely coupled and can be added or removed without explicit configuration. While there have been a variety of not-so-successful attempts to create a viable extensibility framework before this, there's general agreement that MEF is a good solution and it's already being used by prominent applications like Visual Studio.
Here's a simple MEF-enabled extension that implements - and exports - the interface above:
[Export(typeof(MyInterface))]
public class MyExtension : MyInterface
{
public string Name
{
get { return "MyExtension"; }
}
...
}
And here's a simple MEF-enabled application that uses that extension by importing its interface:
class MyApplication
{
[ImportMany(typeof(MyInterface))]
private IEnumerable<MyInterface> Extensions { get; set; }
public MyApplication()
{
var catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
var container = new CompositionContainer(catalog);
container.SatisfyImportsOnce(this);
}
private void Run()
{
Console.WriteLine("Application: Version={0}", Assembly.GetEntryAssembly().GetName().Version.ToString());
foreach (var extension in Extensions)
{
Console.WriteLine("Extension: Name={0} Version={1}", extension.Name, extension.GetVersion());
}
}
...
}
The resulting behavior is just what you'd expect:
P:\MefAndTypeEmbedding>Demo
Building...
Staging V1...
Running V1 scenario...
Application: Version=1.0.0.0
Extension: Name=MyExtension Version=1.0.0.0
...
However, it's important to note that MEF does not isolate an application from versioning issues! Ideally, extensions written for version 1 of an application will automatically load and run under version 2 of that application without needing to be recompiled - but you don't get that for free. There is an easy way to do this, though: avoid making any changes to the contract assembly after v1 is released. :)
Aside:.
But because the whole point of version 2 is to improve upon version 1, it's quite likely the contract assembly will undergo some changes along the way. This is where problems come up: assuming the contract assembly was strongly-named and its assembly version updated (as it should be if its contents have changed!), v1 extensions will not load for the v2 application because they won't be able to find the same version of the contract assembly they were compiled against...
Aside: If the contract assembly was not strongly-named, then v1 extensions might be able to load the v2 version - but it won't be what they're expecting and that can lead to problems.
Here's an updated version of the original interface with a new Author property for version 2:
Author();
string Author { get; }
}
}
One way to solve the versioning problem is to ship the v1 contract assembly and the v2 contract assembly along with the v2 application. (Of course, this can be tricky if both assemblies have the same file name, so you'll probably also want to name them uniquely.) Shipping multiple versions of a contract assembly works well enough (it's pretty typical for COM components), but it can also cause some confusion for Visual Studio when it sees multiple same-named interfaces referenced by the v2 application - not to mention the developer burden of managing multiple distinct versions of the "same" interface...
Fortunately, there's another way that doesn't require the v2 application to include the v1 contract assembly at all: type embedding. If the contract assembly is enabled for type embedding and v1 extension authors enable that when compiling, all the relevant bits of the contract assembly will be included with the v1 extension and there will be no need for the v1 contract assembly to be present. What that means is "reasonable" interface changes during development of the v2 application will automatically be handled by .NET and v1 extensions will work properly without any need to recompile/upgrade/etc.!
Aside: By "reasonable" interface changes, I mean removing properties or methods (and therefore not calling the v1 implementations) or adding them (which will throw MissingMethodException for v1 extensions that don't support the new property/method). Changes to existing properties and methods are trickier and probably best avoided as a general rule.
The v2 version of the sample application uses the Author property when it's present (for v2 extensions), but gracefully handles the case where it's not (as for v1 extensions):
private void Run()
{
Console.WriteLine("Application: Version={0}", Assembly.GetEntryAssembly().GetName().Version.ToString());
foreach (var extension in Extensions)
{
string author;
try
{
author = extension.Author;
}
catch (MissingMethodException)
{
author = "[Undefined]";
}
Console.WriteLine("Extension: Name={0} Version={1} Author={2}", extension.Name, extension.GetVersion(), author);
}
}
Here's the v2 version in action:
...
Staging V2...
Running V2 scenario...
Application: Version=2.0.0.0
Extension: Name=MyExtension Version=1.0.0.0 Author=[Undefined]
Extension: Name=MyExtension Version=2.0.0.0 Author=Me
[Click here to download the complete source code for the sample application/contract assembly/extensions and demo script used here.]
Type embedding and MEF are both fairly simple concepts that add a layer of flexibility to enable some pretty powerful scenarios. As is sometimes the case, the whole is greater than the sum of its parts and combining these two technologies provides an elegant solution to the tricky problem of upgrading an application without breaking existing plug-ins.
If you aren't already familiar with MEF or type embedding, maybe now is a good time to learn! :)
PS - My thanks go out to Kevin Ransom on the CLR team for providing feedback on a draft of this post. (Of course, any errors are entirely my own!)
A few months ago I began a similar post about LowProfileImageLoader/DeferredLoadListBox updates by saying:
Windows Phone.
In the time since, I've continued to hear from people who are benefitting from LowProfileImageLoader and DeferredLoadListBox - and the code has even been incorporated into the WP7Contrib project! Along the way, I've also collected some great feedback, so I recently dedicated time to make a few improvements:
LowProfileImageLoader
DeferredLoadListBox
The most significant change is that I've removed the use of the UIElement.TransformToVisual platform-level method from DeferredLoadListBox because it has proven to be unreliable on Windows Phone 7 by throwing exceptions unexpectedly. Because this is not the first time I've had to fix crashes due to random ArgumentExceptions ("The parameter is incorrect."), I recommend not using the TransformToVisual method in Windows Phone 7 applications until/unless the underlying problem is fixed. In the meantime, it has been my experience that the LayoutInformation.GetLayoutSlot method can often be used as a substitute with just a little bit of extra effort.
TransformToVisual
I'd like to thank Tore Lervik, Baldelli Gabriele, and Holger Schmeken for reporting this problem.
Aside: Another time I had to remove TransformToVisual was for the Silverlight for Windows Phone Toolkit's ContextMenu control. (This fix was part of the November 2010 release).
ContextMenu
I've previously explained why DeferredLoadListBox requires every container to have a height (note: each height can be different!). However, there are some scenarios where the Windows Phone 7 platform will report ActualHeight to be 0 for a container even though its height has been explicitly and correctly set (ex: via ItemContainerStyle). (Note: This seems to occur most often during scrolling.) Fortunately, I found an easy workaround that appears to resolve this problem in cases where the platform is misbehaving: a call to the UpdateLayout API is sufficient to correct the value of ActualHeight.
ActualHeight
I'd like to thank Rich Griffin and Michael James for reporting this problem.
LowProfileImageLoader originally used a Queue to implement "first in, first out" (FIFO) behavior of the image downloads it performs. This is a "fair" implementation and is ideal for slowly scrolling up/down a list that uses LowProfileImageLoader and DeferredLoadListBox together. However, for the scenario of quickly scrolling such a list in a single direction, FIFO behavior means the images you see on the screen will be among the last to load. The "obvious" fix is to switch from a Queue to a Stack which gives "last in, first out (LIFO) behavior instead. But while that's better for the second scenario, it's worse for the first one - and it leads to a weird visual effect in apps like my ImageLoading sample (part of the download) because the "wall" of images loads bottom-to-top instead of "top-to-bottom" as people expect.
Queue
ImageLoading
Clearly, there's no perfect answer here, so the solution is to do well on average! The classic way of amortizing unpredictable cost is to introduce randomness (ex: the QuickSort algorithm) - so instead of processing FIFO or LIFO, LowProfileImageLoader now works through its queue of pending work in random order. As a result, both the fast and the slow scrolling scenarios show images quickly and the application appears more responsive overall!
Aside: The way I've implemented randomization is a slight variation of the solution to a classic programming puzzle: How do you sort a deck of N cards in linear time and constant space? If you haven't seen this one before, take a minute to think about it before following this link to a description of the Fisher-Yates/Knuth shuffle.
Though I initially meant for LowProfileImageLoader and DeferredLoadListBox to be used together, there's no reason LowProfileImageLoader can't be used on its own. In fact, I previously ensured that it works fine when used with the default ListBox/VirtualizingStackPanel combination. However, when the user is scrolling such a list very quickly, the default container recycling behavior means there will be multiple data bindings applied to a particular container in rapid succession. Every one of these will enqueue a request for LowProfileImageLoader to download the corresponding image - but only the most recent one matters. Any previous requests are "stale" and although it's safe to satisfy them, it's also unnecessary. Therefore, I've made a change with this update to detect stale requests and discard them before making an expensive web request on their behalf. This difference doesn't matter in non-virtualizing scenarios, but for virtualizing scenarios the amount of unnecessary work it saves can quickly add up!
Another consequence of using LowProfileImageLoader in the presence of container recycling is that re-used Image elements kept their old content until new content had been downloaded. This could lead to temporarily misleading UI where images show up alongside content they aren't associated with. It happens because LowProfileImageLoader didn't previously "null-out" the Source property when a new request was made. I've modified the code so it does now - and the virtualizing experience is nicer because of it.
When implementing the worker thread logic for LowProfileImageLoader, I intended for it to process WorkItemQuantum number of items each time through the loop until the queue of requests was exhausted. I wrote the following code:
WorkItemQuantum
for (var i = 0; (i < pendingRequests.Count) && (i < WorkItemQuantum); i++)
I'd like to thank Ashish Gupta for pointing out a bug here; what I meant was:
for (var i = 0; (0 < pendingRequests.Count) && (i < WorkItemQuantum); i++)
Coding errors in loops can cause serious problems if they result in an attempt to process too many or too few items. I got lucky here because there's no functional bug due to the original typo - the only downside is that performance might be a little worse because it takes a couple of extra passes through the loop to complete once the count drops below WorkItemQuantum. Fortunately, the value of WorkItemQuantum is only 5, so the real-world impact of this is minimal. However, the whole point of this code is to help improve performance, so I've fixed the oversight. :)
And finally, because I recently became a NuGet publishing "expert", I've created a package for the PhonePerformance assembly to make it easy to reference for all the NuGet fans out there. It contains the same binary you'd download below, but it contains only the assembly (and its XML IntelliSense file) - the three sample projects are available only with the ZIP download. This split seems like a reasonable compromise to me: reference from the NuGet gallery if you know what you're doing and just need to add the binary to your project - or - read the relevant blog posts and download the samples if you're getting started.
PhonePerformance
[Click here to download the compiled PhonePerformance assembly, sample applications, and full source code for everything.]
-OR-
[Click here to visit the NuGet gallery page for a package containing the PhonePerformance assembly.]
Windows Phone 7 developers must pay attention to performance because otherwise it's easy to end up with a slow, badly-behaved application. The PhonePerformance assembly focuses on two common scenarios (image loading and list scrolling) and attempts to improve upon the default experience by making it easy to avoid known problem areas. As with any performance technique, results can vary greatly depending on the specifics of each scenario, so it's important to take measurements and test everything on real phone hardware.
Many developers have told me they had success with the PhonePerformance assembly - I hope you do, too! :) | http://blogs.msdn.com/b/delay/archive/2011/03.aspx?PostSortBy=MostRecent&PageIndex=1 | CC-MAIN-2014-41 | refinedweb | 5,521 | 50.06 |
MSN Blocks Mozilla, Other Browsers [updated] 1295
k_hokanson writes: "I was just going to check out some tasty news articles, with my trusty Mozilla, at MSN. but what do I get when I go there? A nice little message telling me that 'in order to display this page properly', I have to get the latest version of IE! And no, there's no option to display it incorrectly. " Enough people have submitted this story that it can't be an isolated case;) Thanks, Microsoft. Here's the story on Yahoo!. CT: telling konqueror to lie about its User Agent causes the page to render correctly save the background which is the wrong color. Update: 10/25 23:19 GMT by T : kuwan writes "Looks like Microsoft was getting too much heat. CNet is reporting that Microsoft is backing off on their browser block. I'm only wondering how long it will be before they do it again with some other excuse as to why we all need IE."
Not for me (Score:2, Informative)
MjM
Re:Not for me - Galeon 0.12.4 is blocked (Score:2)
Re:Not for me (Score:2)
Re:Not for me (Score:2)
How are they blocking ? (Score:2)
So are they blocking specific browserid's or are they blocking everything but a couple specific ones?
Re:How are they blocking ? (Score:4, Informative)
eg: Opera includes the ability to spoof certain other ones, but still tacks "Opera 5.xx" somewhere in the UA. So if you simply search it for "Opera", you can block it. If they change the string to Opero for example, it will work again.
The interesting thing is that I'm not sure what would happen if you made a copy of IE using the IEAK that contained a custom UA string that had the word "Opera 5" in it. I wonder if it'd get blocked too.
Re:Not for me (Score:2)
Re:Not for me - iCab works (Score:2)
Re:Not for me - OmniWeb works (Score:2)
Re:Not for me (Score:4, Interesting)
I run into those every once in a while (Score:2)
Re:I run into those every once in a while (Score:3, Informative)
Re:I run into those every once in a while (Score:2)
JavaScript may also be able to report on the browser but I'm not sure. It makes more sense IMO to do it server-side anyway.
Someone else's post already said that in this case they check User-Agent so you can configure Mozilla to report IE or NS6 and it will work.
--
Garett
Re:I run into those every once in a while (Score:2)
Konq. (Score:2)
DMCA violation! (Score:2)
Workaround.... (Score:4, Informative)
user_pref("general.useragent.override", "Mozilla/5.0 (X11; U; Linux 2.2.16-22smp i686; en-US; m18) Gecko/20010110 Netscape6/6.5");
Mozilla on Win32 now gets in... But this just adds to the evidence against anything MS...
Re:Workaround.... (Score:2)
Re:Workaround.... (Score:2)
No no no! (Score:5, Insightful)
This what's important here: The authors of the site blocking you have decided that you're not important. Fine; nod your head in agreement and take your traffic, ad-viewing eyes, and attention elsewhere. Don't even tell them or complain; let them die of natural selection.
Re:No no no! (Score:2)
Unfortunately, natural selection only works when there is competition... not when the web site is owned by the same company that has a monopoly on desktop operating systems.
Re:No no no! (Score:3, Interesting)
I agree with this statement, but that's not what the author was suggesting. He was suggesting that you report it as the same browser, just on a different operating system. Mozilla on Linux is definitely not a "bad browser" and it's functionally equivalent to its Windows counterpart, so changing your Mozilla on Windows to say that it is Mozilla on Linux shouldn't be as big of a deal as masquerading as something like Netscape 4.x.
In practice, this may still cause problems with other braindead sites which will see your browser as Mozilla on Linux and not let you in. A great way to get around this would be to add a way to easily switch user-agent strings to this awesome little prefs toolbar [xulplanet.com]. Then you could surf with the correct user-agent most of the time and when you run into an annoying site like MSN that only works with certain browsers, you could easily switch to a different user-agent string just while you're looking at that site. The toolbar already lets you very easily turn on/off Javascript, Java, Pop-Ups, Onload Popups (with a slight modification that I wrote recently), and other things that usually require a browser restart or a lengthy trip through the preferences menu. User-agent masquerading would be a great addition to the toolbar (I'd do it myself if I actually wanted to look at MSN).
Re:Workaround.... (Score:2)
I'm running Mozilla on Solaris, and the page gives me the warning ("Gives me the finger", is more like it).
Note that this only applies to [msn.com]. Their Channel pages, such as womencentral.msn.com [msn.com] display just fine. Further proof that MSN's claim is bullshit.
Not a big problem, I don't really need MSN anyways, and apparently MSN advertisers don't really need my business.
Power of the default (Re:Workaround....) (Score:2)
Mozilla is more than capable of handling any standards compliant markup you throw at it so the whole thing stinks of anti-competitive behaviour.
Much though I don't like this, I have to say it has one positive benefit - I don't have to look at their stinky site or inadvertantly make them money by clicking on one of the adverts. I wonder what all their advertisers think of all this?
Re:Power of the default (Re:Workaround....) (Score:2)
It is also worth remembering that AOL is dumping IE for Gecko and perhaps MS is pre-emptively doing this to put a spanner in the works; to stop people from moving from the MSN service over to AOL.
Re:Workaround.... (Score:2)
Not that I really NEED to go to MSN, but it's nice to give Microsoft the finger.
Re:Workaround.... (Score:2)
Re:Workaround.... (Score:5, Insightful)
Gerv
Re:Workaround.... (Score:5, Funny)
Re:Workaround.... (Score:3, Insightful)
On my homepage I'm experimenting with a rather unique CSS positioning layout on the front page. Mozilla does a great job with it, IE does a poor (but readable) job with it, and NS 4 royally screws it up. To overcome this, I included some javascript that checks the user agent string and comments out the link to the stylesheet if it finds NS4.
Basically if you are running NS4 with a false user agent string, you will see a bunch of garbage when you visit my web site.
doesn't even work with IE 5.5!! (Score:2)
here's a screenshot [projectlockdown.com] of the page that i'm getting in IE 5.5.
anybody else seeing the same thing?
Re:doesn't even work with IE 5.5!! (Score:2)
Not just "incompatible browsers" (Score:5, Interesting)
"Microsoft is seeing (that) it is an Opera browser and shutting it out," said Tetzchner, whose team was testing the problem Thursday. "If you change the Opera string by one letter, it is letting us in."
Re:Not just "incompatible browsers" (Score:2)
This doesn't really make sense to me. It's either that compiled a list of browsers that are either "known to work" or "we don't compete with them so it doesn't matter" and they block everything else.
--
Garett
Re:Not just "incompatible browsers" (Score:2)
Re:Not just "incompatible browsers" (Score:2)
Re:Not just "incompatible browsers" (Score:2)
It comes with 5 different Browser Identification settings:
MSIE5.0, Opera, Mozilla 5.0, Mozilla 4.76, Mozilla 3.0
None of these setting can connect to MSN.com, as of 2 minutes before this post was posted.
Re:Not just "incompatible browsers" (Score:2)
To hell with them I say.
Re:Not just "incompatible browsers" (Score:2)
Tried to update it, but couldn't find IE 5 for Mac, and Netscape 6 wasn't working ethier.
Also cannot login to Hotmail with latest Mozilla (Score:2)
Is this a Mozilla bug or is it an evil MS deed?
Tried lynx... (Score:2)
Attention: Web Browser Upgrade Required to View MSN.com.
* Internet Explorer for Windows
* Internet Explorer for Macintosh
* MSN Explorer for Windows
old tactics (Score:2)
Re:old tactics (Score:3)
They and just about any other site that tried to do something other than straight text-and-jpg HTML. The fact is that Netscape browsers were buggy pieces of trash. A browser should not crash, no matter how messed up the content it receives. Period.
Netscape on Linux works but not Mozilla. (Score:2)
Other browsers planning ahead (Score:2)
It's a good thing that other browsers let you manipulate the user-agent string and trick stupid sites like this into believing that you're using IE. Of course that won't help the majority of users who don't know about features like that, but at least the option is there.
Confirmed, and this is great news. (Score:5, Insightful)
I think this is great news. It means Microsoft is leaving the web and going their own way. Whatever it is they've got over there, by definition it isn't the web if it can't be viewed with a generic web browser.
Good luck to them on their new venture, whatever it is, and happy to have them out of the way on standards issues now that they've left the web to the rest of us.
Re:Confirmed, and this is great news. (Score:3, Flamebait)
Whatever it is they've got over there, by definition it isn't the web if it can't be viewed with a generic web browser.
By your definition today, that may be true. But if you know anything about language, you know that definitions change. If Microsoft has it's way, in five years "the web" might be defined as "what's viewable by Explorer."
You know how they negotiate. Imagine the next time Macromedia goes to Microsoft with an update to Flash. MS says, yeah, we'll distribute that plug-in for you, just do this one thing for us, make sure Dreamweaver inserts this little script that tests for "browser compatibility" or maybe maybe we'll distribute our ActiveFlash (tm) plugin instead.. W'ere not furcing you, you understand, just a business deal, you help us, we help you.
Now imaging the same thing with Adobe, and the HTML tools are all enforcing browser checks by default. All of a sudden it's a Microsoft Web.
It's just to fool statistics (Score:4, Insightful)
The drawback is that the percentage of clients using IE will increase, even though they are really using Mozilla or other non-IE software.
So statistics will always show a lot of IE, even when AOL will have released AOL 6 with Gecko..
Re:It's just to fool statistics (Score:3, Funny)
lynx -useragent="Mozilla (compatible; MSIE 6.0b; Windows NT 5.0; Bill Gates
eats worms)"
Implications? (Score:2)
Dumb move in the short term, though. But with them ramping up XP, Passport and
I don't know. I'm not sure if they're shooting themselves in the foot or shouting "Resistance is Futile!"
My guess is long term, the American and European governments will use this as further evidence in any anti-trust cases.
Not to sound like a dick.... (Score:2, Insightful)
Why is it that when the underdog does something dirty it's all right? (Granted, the Apache mod was probably written by an individual [not a corp.], but still...)
For reference:
Proxies to the rescue? (Score:2)
Anyone out there who's done this?
Re:Proxies to the rescue? (Score:2)
Re:Proxies to the rescue? (Score:2)
user-agent Mozilla/4.77 [en] (Win95;U)
Re:Proxies to the rescue? (Score:2)
Re:Proxies to the rescue? (Score:2)
Wow! I Just Had the Same Problem With Slashdot! (Score:2, Funny)
Hi! How are you? I send you this Debian Potato in order to have your advice.
I'm sure glad I had Mozilla. A mere seven crashes, two freezes and a cookie later, I was able to read some News That Matters.
Simple fix :) (Score:2)
Settings->Configure Konqueror->User Agent
Simply add a new "Site/domain specific identification".
For example, I added ".msn.com" as the domain, and used "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)" as the user agent.
Voila! I can see msn.com again! Not that it is anything spectacular to look at, but if you MUST check the site out, this works well.
Imbeciles (Score:2)
-Tim Berners-Lee in Technology Review, July 1996
Microsoft seems to have forgotten the "World-Wide" part of the WWW. It still pisses me off. Not because I give a rat's ass about MSN, but because so many have forgotten the whole point of the web in the first place.
Re:Imbeciles (Score:2)
In ten years no address will start with www. It will be msw. for Microsoft Web. Of course, it will be running on MSP/IP. And the official history of MS will tout how it invented the web.
{taking off MS bashing clothes}
Of course, I don't think it'll come about. M$'s days of total dominance are coming to an end. They'll continue to be one of the big boys, but they're in the last, desperate throws of trying to de-commodify something and that never really works(think IBM's MCA bus). Once their management come to terms with the fact they they can no longer grow at a 20% a year clip -- which is what is driving all of this 'my way or the highway' crap -- and that they, like it or not, are going to at best have the economics of a mature, stable, boring company they'll stop all of this nonsense.
The Bastard's prediction: M$ cannot live on hype alone. And
They're going to have to worry more about appeasing the investment community. They're used to double digit growth, and it ain't going to be there. I expect them to sell their stake in MSNBC along with some of thier telecom/cable investments (because it never bought them access, which is why they threw money at it in the first place).
M$ banks on the ever forward march of the stock price. From employee compensation to extra money they make off of hedging their own stock to large investors. I'm afraid those days are over, and they're going to have to change with the times. Fundamental change is coming M$'s way. It won't happen overnight, but its gonna happen.
Not all of MSN (Score:3, Interesting)
For the record, I'm using FreeBSD with Konqueror and Mozilla.
Try clicking those links at the bottom of the page. You can't get to ``Terms of Use,'' but ``Advertise'' works just fine.
b&
Too blatent (Score:2)
In Opera's prefs, you can set it to identify itself as another browser, but you still get the same results when trying to go to msn.com. So they're doing something special to identify the browser besides just the http header info.
If you go to any place within MSN, everything works fine, and you don't get the lockout message.
If you go to msn.com with IE and view the source, you will notice that there is NOTHING in there that is IE specific code.
They're really using their touch. Most of their attempts at deceit are this obvious.
Mac IE works (Score:2)
In fact when I save the source of the page served up to my Mac IE here, I can see that it's pretty bog-standard XHTML but otherwise nothing special. So much for MSN.com needing a "browser upgrade".
Right. (Score:2, Interesting)
To those who already posted that they 'got in' with Netscape, the article did say that only some versions were affected... Don't make me say it...
Ensuing flame war (enable asbestos monitor) aside, can this sort of activity be gotten away with? Is this legal? It's certainly one thing to corner a market, but locking non-MS browsers out of MSN and making such a wild claim as it won't render properly is a whole new level, even for MS. Can those out there actually qualified to give me an answer please do so? Those who just want to pontificate, you'll just be preaching to the quoir with me.
You gotta hand it to them, they really done it this time. Now, where did I put my RedHat boot CD..?
Um... people? (Score:2)
Maybe there's a reason for a non-Windows/IE person to go to MSN, but as far as I know, all of those articles are available on MSNBC.com. Insofar as I can tell, it works fine.
So what? Microsoft has a stupid proprietary browser and a stupid proprietary site. We already knew this. That's their problem. When a site that actually does something usefull for non-Microsoft users becomes completely IE-dependant, then I'll be annoyed.
But bitching about Windows Update not working under Mozilla/X/Linux? That's daft. No one complains about the fact that their local Ford dealership doesn't carry all the parts to fix your Saturn. Sure, it's icky what they're doing to the HTML standard, but c'mon.
In other news (Score:4, Funny)
Re:In other news (Score:2)
One can browse aol.com quite easily with any browser. Actually connecting to AOL's service requires proprietary means, but AOL's service isn't on the web either. So, if Microsoft is going to put up a broken website that only runs through proprietary software, I think we're entitled to give them hell for being stupid.
This is precisely why I held onto NS4 for so long. (Score:2)
That said, the site renders perfectly in NS6.1.. better than IE, even -- the font isn't TINY.
IRIX - (Score:2)
Mozilla does not.
Should I be waiting for the IRIX port of IE?
They must really hate mozilla.
Who cares? (Score:2)
Why are you trying to go to MSN sites anyways? All it is is Microsoft propaganga, coated with a thick layer of privacy stealing passport authentication. Anything you want to get from MSN you can get from Yahoo, including email, news, stock quotes, etc. And no M$ or Passport bullshit, not to mention that Yahoo pages are and always have been perectly compatable with ANY browser (even Lynx), cause they never fell into all the DHTML crap. And they actually have a GOOD search engine (Google)
And this is a loss how? (Score:2)
Identity Should Be Selectable In Any Browser. (Score:2)
Here's a thought.
I sorta like what I saw in Konqueror not too long ago, the ability to present yourself to a server using several different browser identities.
This should be a standard feature of ALL browsers.
Prefaced, of course, with a little pop-up disclaimer stating that the subsequent content may not be displayed correctly, or securely.
Cheers, and yes, PROPAGANDA is still running..
HOLY SHIT! POPE IS FOUND TO BE CATHOLIC! (Score:2)
Hack the User Agent header? (Score:3, Redundant)
It should be easy to get around this... like Tetzchner said, you just have to change one character in the user-agent header to break MS's lockout mechanism. I've never used Opera myself; is the functionality to change the user-agent string built into the browser? If not, it wouldn't be hard to build a simple HTTP proxy that would munge the header for you.
A couple things of note: The first is that I received the "upgrade to IE" page when I ran msn.com through my Java HTTP header utility (Sun's Java, by default, has a user-agent string of something like "Java1.3.1_01"). This means that MSN might be breaking a lot of non-browser spiders, robots, and page scrapers out there.
My second note is that the content of msn.com (both the upgrade page and the real page) is now written in XHTML (a version of HTML that conforms to XML specifications). My guess is that this is Microsoft's justification for forcing people to "upgrade" to IE6... they want their users to be using an XHTML-compliant browser.
Microsoft has a death wish... (Score:2)
Microsoft is boldly saying "We want to run the Internet. Standards mean nothing except when its our standard."
I think all CS and IT people should strongly oppose this company both from the standpoint of the quality of it's engineering, and it's abysmal ethics and vision. Unix represents the best way (including Linux, *BSD and MacOS X) to fight back, and there are excellent rationales for doing so [slashdot.org].
This is probably the best chance alternatives will ever have...let's hope they make the most of it. The reviews of RH 7.2 [zdnet.com] are an encouraging start at least!
299,792,458 m/s...not just a good idea, its the law!
Old tactic - remember IGZ? (Score:2)
Embrace...extend...extinguish...
Well, I just tried it... (Score:2)
Translation: MS is lying to users. Not that this is the first time they've done it, but I guess it just goes to show that they're up to their old tricks.
Has anyone actually tried with Netscape? (Score:2)
How is this any different... (Score:2)
If we kick and scream about Microsoft doing it, then we need to make sure that we aren't playing the same game.
RD
Re:How is this any different... (Score:2)
Hotmail / NS (Score:2)
JavaScript required. The browser that you are using does not support JavaScript, or you may have disabled JavaScript.
[...snipped..]
Are you using a browser that doesn't support JavaScript?
If your browser does not support JavaScript, you can upgrade to a newer browser, such as Internet Explorer 5.
Do you have JavaScript disabled?
If you have JavaScript disabled, you must enable JavaScript to sign in. Instructions are listed below.
it then gives instructions for how to turn JS on for IE, and then...
Other browsers
To see if your browser supports JavaScript, and for detailed instructions about how to enable this feature, see the online Help for your browser.
And YES... I DO browse with JavaScript turned on.
This works, and you get minimal MSN to boot! (Score:2)
lynx -useragent="Mozilla/4.7 [en] (X11; I; SunOS 5.8 sun4u)"
Furthermore, MSN never looked better! Few graphics, no CSS-font-enlargment, not even a white background. It looks positively old-school, if you ask me. Unfortunately, the rest of the site is just as bloated as usual.
This does not work:
lynx
This gets me the upgrade-your-browser page. After some more investigation, I find that the minimal User-Agent string needed to get the minimal MSN home page, is: "Mozilla/4.7". "Mozilla" alone does not work, nor does "Mozilla/4" or "Mozilla/4.1". But any string like "Mozilla/4.$x" where $x -gt 4, works fine. You can include the additional User-Agent components if you like, but they do not seem to matter.
Tomorrows Yahoo Headline: (Score:2)
It will be shown tomorrow that a not-identified Yahoo executve bet Microsoft's Bill Gates 1 dollar that he could triple the page views of MSN.COM while pissing off the open source crew. Bill Gates, of course [one never to forego a challenge] took this bet. Commenting on the way things turned out, Bill said "Well, you win some, you lose some... this, though, was the most entertainment I got for a buck"
Back to you, john...
Don't Fall For It (Score:2)
This is a stunt. MS will relent within a week or two. They're doing this to drum up more PR for the XP release. It keeps their names in the headlines.
Bad publicity is better than no publicity.
A week, maybe two weeks from now (probably after the XBOX) they'll relent, redesign the MSN site slightly, and allow all browsers access.
Slashdot effect on MSN! (Score:2)
Confused (Score:2)
They've got it Backwards! (Score:3, Interesting)
Sure, it stinks to high heaven like a typically corrupt monopolist move (but they wouldn't do that would they?), and consider how ISP's have been switching over to MSN as their default portal for users, this would be an error. Right? Yes, just like putting the fox in the hen house and nailing the door shut. You can count on him to look after the best interest of the chickens.
This alleged ongoing effort to lock people into everything Microsoft would be an open admission that their software and systems are so bad that they can't sell on their own merits. But they wouldn't do these things, thus admitting to that, would they?
Something tells me... (Score:4, Insightful)
As terrible as it is that Microsoft is prohibiting other web browsers from accessing MSN, it's not as if Microsoft has a monopoly on news and content on the web (at least not yet). As a company, they can decide how they want their content rendered and if IE (no matter how self-serving it is) is the only browser that does the job perfectly, then so be it.
I develop web applications and there are times when a client asks for something that simply isn't feasible (or perhaps possible) in Netscape 4.x, so we inform the client of that and, effectively, prohibit them from using Netscape 4.x to access the application. I don't see much of a difference here.
Now I would see a major difference if there weren't news and content alternatives (and plenty of them) to MSN. Heck, IMO they could limit access to only IP addresses that are on the MSN network. Didn't Prodigy do that?
Yeah, it's self-serving and perhaps borderline unethical. But it's not illegal (yet) and if they want to make a sight that uses IE features they can't guarantee are supported in other browers, that's their call.
Almost, but not quite... (Score:3, Insightful)
You're right, and we face this on the internet every day. Say I visit a site that says that to view the site, I need Macromedia Shockwave. Well, if I really want to view the site, I'll download Macromedia Shockwave. If I want to say, "Screw that...I'm not going to give Macromedia the edge in my WWW viewing," that's my right as well.
But here's the problem: Microsoft isn't saying, "Hey, we use special things here, and if you want to view the webpage, you need this special software." No, Redmond's saying this:
."
Well, let's just go visit Mozilla.org's website for a second...if you look here [mozilla.org], you'll read at the top of the page that, Mozilla has good support for XML. Several World Wide Web Consortium (W3C) Recommendations and drafts from the XML family of specifications are supported, as well as other related technologies.
So, Mozilla supports XHTML, but for some strange reason, msn.com says it doesn't. As Chris Farley would say, "Hmm...That's a mystery!"
Oh, this is good! Check this out...
Okay, folks, here's the kicker. While I was looking around at this, a thought occured to me. Let's just go down and check out and see if the guys who made the standards actually say that MSN is playing by their rules. So, this lead me to W3's Validation site [w3.org], where I typed in into the XHTML validation field, here's what I got in return (abridged, but the key points are there)...
URL:
Server: Microsoft-IIS/5.0
Content Length: 1462
Detected Character Encoding: utf-8
Document Type: XHTML 1.0 Strict
Below are the results of checking this document for XML well-formedness and validity.
...(four errors listed, but omitted for space)
Sorry, this document does not validate as XHTML 1.0 Strict.
If you use CSS in your document, you should also check it for validity using the W3C CSS Validation Service.
---
But nothing, nothing comes close to just proving how dirty Microsoft is playing than this statement right here at the bottom of the page: (- character used to show XHTML script included in webpage)
---
Below is the source input I used for this validation:
1: -?xmlAttention: Web Browser Upgrade Required to View MSN.com-/title--base href="".
---
Can you believe this? MSN actually told the W3C standard comittee that their own standards did not work with MSN! That's a laugh riot right there.
So, Case in Point: If Microsoft were to flat out say, "Hey! We don't care about you guys with the other browsers! Our website only looks good with IE and that's the way it's going to be," then I'd grumble and go on with my business. But Microsoft says that they're conforming to the standards presented in XHTML by W3C, when in fact W3C says that does not comply with their standards.
This is outright monopolization at it's worst.
Client identifiers (Score:5, Insightful)
I've been thinking about this for a while, and prompted by this scenario, I've come to the conclusion that protocols that let client-identifying strings go through is just asking for discrimination and phony statistics.
Many protocols use client identifers, such as HTTP, SSH, and OpenPGP. However, I'm not seeing any true purpose for having these identifiers stuck into the messages used in these protocols. Perhaps at one time they were used so that workarounds for buggy clients could be made, but the problem there is with the buggy client. Nowdays, however, checking client identifiers, be it via user-agent or Javascript tests, it is used to discriminate against certain clients.
Futhermore, many clients probably lie about what what they are, in order to get a server to listen to them. This is sad, because it creates false statistics about what the client percentage breakdown really is. In addition to this problem, the statistics themselves create a snowballing effect, suggesting to server-admins to only 'support' certain clients, and suggesting to end-users that 'everyone' is using a certain client and they should too.
Just as justice is supposed to be blind, I feel the same should be said about servers; they should have no knowledge of what client it is that is accessing them.
As more and more services become network-enabled, we should be wary of any protocol that implements a client-identifier. Or else we will see more of the same discrimination.
Re:Client identifiers (Score:3, Insightful)
Your comparsion is flawed. Protocols identifiers describe publicly-known capabilities. These capabilities are standarized in the protocol. On the otherhand, what Microsoft is doing is asking Mozilla what it can do, but simply saying "Your badge says Mozilla; go away." Mozilla can handle MSN with ease. It is not a protocol or capability issue that Microsoft is blocking because of.
The W3 standards are not designed so that each user gets the exact same experience. They are designed so that an agent can be customized for a user's experience. It should not the servers' problem that there are buggy clients. As you state, there will be more of them, and catering to them is asking for more broken software.
Re:Windows Update is worse... (Score:2)
Why in God's name are you going to Windows update in Mozilla, on linux nonetheless??? Don't you realize that:
Windows update runs totally on ActiveX controls, which don't work in anything but IE, and
It downloads and installs everyhing on the fly, which makes it useless in Linux??
Someone mod the parent down, he's either a total idiot or a helpless troll
Don't moderate it down if it is true (Score:2)
Just because you shouldn't do something is no reason to not do something.
Anyways I think the author thought he was being funny but he doesn't seem to realise that this is exactly the type of thing that Microsoft loves to do. They have far too much time on their hands so they try to make life miserable for people.
Re:Windows Update is worse... (Score:2)
Bad analogy. A better one would be "Imagine you tried to drive your motorcycle underwater and it didn't work!" Er, yeah, anyone who has brains doesn't try that, and if they do, there hopeless.
Re:Windows Update is worse... (Score:2)
Well, then you'll have to get it from the plain old "Go to microsoft.com and click on Download". Yeah, I know its a HUGE hassle, those couple of mouse clicks instead of having a wizard do it all for you....
You're confusing a corporation with an individual (Score:2)
state. Unlike humans, they don't have rights.
Therefore, dealing with them is a matter of
pragmatism, not commonsense morals/ethics.
Re:Kinda begs the question.... (Score:2)
Re:Kinda begs the question.... (Score:2)
I have long been unable to login to Hotmail (after trying to login I never get a page returned) on various Linux boxes running NS 4.7, whereas I can login fine from my NT box right beside it. I have always been working under the tacit assumption that MS was either intentionally not replying to an 'unpreferred' browser, or was generating HTML that would somehow trip up NS on my platform.
Anyone else have problems accessing Hotmail with Netscape on Linux
Re:Matter of Economics (Score:2)
Re:How big of an Impact does this have? (Score:2) | http://slashdot.org/story/01/10/25/1824206/msn-blocks-mozilla-other-browsers-updated?sdsrc=nextbtmnext | CC-MAIN-2013-48 | refinedweb | 5,785 | 74.19 |
#include <SQLStatement.hpp>
A sql statement.
A SQLStatement instance is used to executing a SQL statement and returning the results it produces against a SQL database that is opened through a SQLi instance.
Through the SQLi, it's the reason why a principle of DBMS, DBMS system doesn't allow simultaneous query from a session (connection). Only a query (process) free() method(). If you don't, the mutex will not be unlocked, thus you can't do anything by the SQLi.
Definition at line 46 of file SQLStatement.hpp.
Protected Constructor.
SQLStatement's constructor have to created by SQLi::createStatement().
Don't create SQLStatement by yourself.
SQLStatement has to be created by SQLi::createStatement().
Definition at line 98 of file SQLStatement.hpp.
References free(), and sqli.
Free the sql statement.
Definition at line 124 of file SQLStatement.hpp.
Referenced by SQLStatement().
Refresh the sql statement.
Definition at line 140 of file SQLStatement.hpp.
Prepare a sql statement.
Prepare a sql statement with parameters to bind for execution
Definition at line 168 of file SQLStatement.hpp.
References bindParameter(), and refresh().
Execute the prepared sql statement.
Definition at line 212 of file SQLStatement.hpp.
Referenced by executeDirectly().
Execute sql-statement direclty.
Executes the given sql-statement without preparing or binding any parameter
Definition at line 239 of file SQLStatement.hpp.
Fetch a record.
Whether succeded to fetch a record.
False means there's not any record or previous record was the last.
Definition at line 260 of file SQLStatement.hpp.
Move cursor to the next sql-statement.
Definition at line 279 of file SQLStatement.hpp.
Get size of columns.
Returns the number of columns in a result set.
Definition at line 293 of file SQLStatement.hpp.
Get column's data by its index.
Returns column's data from fetched-record by specified column index
Definition at line 308 of file SQLStatement.hpp.
Get a column data by its name.
Returns column's data from fetchched-recrod by specified column name
Converts the records of current sql-statement to XML.
Recommends to override for each DBMS's domain XML rule.
Definition at line 396 of file SQLStatement.hpp.
References samchon::HashMap< Key, T, Hash, Pred, Alloc >::get(), and samchon::HashMap< Key, T, Hash, Pred, Alloc >::set().
SQLi who created the SQLStatement.
Definition at line 63 of file SQLStatement.hpp.
Referenced by SQLStatement().
Handler of sql statement (OBDC)
Definition at line 68 of file SQLStatement.hpp.
Count of binded parameters
.
Definition at line 76 of file SQLStatement.hpp.
A map for binary size.
When calls ByteArray::size(), the returned size_t value can't be kept until
Definition at line 84 of file SQLStatement.hpp. | http://samchon.github.io/framework/api/cpp/de/def/classsamchon_1_1library_1_1SQLStatement.html | CC-MAIN-2022-27 | refinedweb | 440 | 54.59 |
IRC log of tagmem on 2012-10-18
Timestamps are in UTC.
17:01:31 [RRSAgent]
RRSAgent has joined #tagmem
17:01:31 [RRSAgent]
logging to
17:02:27 [Zakim]
TAG_Weekly()1:00PM has now started
17:02:35 [Zakim]
+??P7
17:03:03 [ht]
zakim, ? is me
17:03:03 [Zakim]
+ht; got it
17:03:50 [noah]
noah has joined #tagmem
17:04:48 [noah]
?
17:05:04 [Zakim]
+plinss
17:05:27 [Zakim]
+[IPcaller]
17:05:36 [noah]
zakim,[IPCaller] is me
17:05:36 [Zakim]
+noah; got it
17:05:38 [Zakim]
+Ashok_Malhotra
17:05:41 [Zakim]
+Yves
17:05:57 [Yves]
trackbot, start telcon
17:05:59 [trackbot]
RRSAgent, make logs public
17:06:01 [trackbot]
Zakim, this will be TAG
17:06:01 [Zakim]
ok, trackbot, I see TAG_Weekly()1:00PM already started
17:06:02 [trackbot]
Meeting: Technical Architecture Group Teleconference
17:06:03 [trackbot]
Date: 18 October 2012
17:06:08 [Yves]
Scribe: Yves
17:06:11 [Yves]
Chair: Noah
17:06:47 [noah]
zakim, who is here?
17:06:47 [Zakim]
On the phone I see ht, plinss, noah, Ashok_Malhotra, Yves
17:06:48 [Zakim]
On IRC I see noah, RRSAgent, Zakim, ht, Ashok, Norm, plinss, Yves, trackbot
17:07:38 [Yves]
Topic: approval of minutes
17:07:49 [Yves]
no weekly minutes needs approval
17:07:57 [Yves]
minutes of f2f not entirely received yet
17:08:07 [Yves]
...postponed until next week
17:08:19 [noah]
ACTION-739?
17:08:19 [trackbot]
ACTION-739 -- Noah Mendelsohn to schedule F2F discussion of XXX handler registration see discussion on 20 Sept. -- due 2012-09-27 -- PENDINGREVIEW
17:08:19 [trackbot]
17:08:28 [Yves]
Topic: Administrative item
17:08:56 [ht]
HST happy with Election Procedures email
17:09:11 [noah]
ACTION-744?
17:09:11 [trackbot]
ACTION-744 -- Noah Mendelsohn to send a message to the AB to ask them to review the election procedures for the TAG -- due 2012-10-14 -- PENDINGREVIEW
17:09:11 [trackbot]
17:09:13 [noah]
17:10:02 [noah]
ab@w3.org?
17:10:27 [Yves]
RESOLUTION: send the aforementionned email to the AB <ab@w3.org>
17:10:53 [noah]
s/aforementionned/E-mail on TAG election procedures/
17:12:08 [noah]
HT: ab list is member-only...follow their precedent
17:12:10 [Yves]
(discussions about Cc:ing www-tag, result is no)
17:12:26 [noah]
NM: OK...I think our F2F minutes make the general concern clear
17:12:44 [noah]
Permission to close 744 once sent? No objection.
17:12:45 [Yves]
Noah: the f2f minutes have the discussion around that issue public anyway
17:13:02 [Yves]
Topic: action to be closed
17:13:08 [Zakim]
+ +1.415.832.aaaa
17:14:00 [noah]
ACTION-701?
17:14:00 [trackbot]
ACTION-701 -- Noah Mendelsohn to follow up with Robin on election reform -- due 2012-08-01 -- PENDINGREVIEW
17:14:00 [trackbot]
17:14:07 [noah]
ACTION-721?
17:14:07 [trackbot]
ACTION-721 -- Noah Mendelsohn to update product index to target date on publishing & linking -- due 2012-06-20 -- PENDINGREVIEW
17:14:07 [trackbot]
17:14:13 [noah]
ACTION-736?
17:14:13 [trackbot]
ACTION-736 -- Noah Mendelsohn to prod Henry on ACTION-724 for F2F -- due 2012-09-06 -- PENDINGREVIEW
17:14:13 [trackbot]
17:14:21 [noah]
close ACTION-701
17:14:21 [trackbot]
ACTION-701 Follow up with Robin on election reform closed
17:14:24 [noah]
close ACTION-721
17:14:24 [trackbot]
ACTION-721 Update product index to target date on publishing & linking closed
17:14:25 [Yves]
no objections, action closed
17:14:27 [noah]
close ACTION-736
17:14:27 [trackbot]
ACTION-736 Prod Henry on ACTION-724 for F2F closed
17:14:32 [noah]
ACTION-733?
17:14:32 [trackbot]
ACTION-733 -- Larry Masinter to prepare for 30 minute report on HTTP 2.0/SPDY at October 2012 F2F -- due 2012-09-28 -- PENDINGREVIEW
17:14:32 [trackbot]
17:14:44 [noah]
close ACTION-733?
17:14:49 [noah]
ACTION-739?
17:14:49 [trackbot]
ACTION-739 -- Noah Mendelsohn to schedule F2F discussion of XXX handler registration see discussion on 20 Sept. -- due 2012-09-27 -- PENDINGREVIEW
17:14:49 [trackbot]
17:14:50 [masinter]
masinter has joined #tagmem
17:14:57 [noah]
close ACTION-739
17:14:57 [trackbot]
ACTION-739 Schedule F2F discussion of XXX handler registration see discussion on 20 Sept. closed
17:15:05 [noah]
ACTION-740?
17:15:05 [trackbot]
ACTION-740 -- Larry Masinter to update the governance frame for Oct F2F discussion -- due 2012-09-27 -- PENDINGREVIEW
17:15:05 [trackbot]
17:15:23 [noah]
close ACTION-740
17:15:23 [trackbot]
ACTION-740 Update the governance frame for Oct F2F discussion closed
17:15:36 [Yves]
Topic: TPAC
17:15:57 [Yves]
nothing heard from the ab wrt joint meeting
17:17:14 [noah]
HT: Suggest nothing further official on AB syncup unless they reach out to us
17:17:32 [Yves]
Larry: I'll bug Steve
17:18:36 [noah]
Ian Jacobs:
17:18:44 [noah]
From Ian's note:
17:18:45 [noah]
Some options:
17:18:45 [noah]
* 5 minutes at the AC meeting (Tuesday afternoon or Thursday morning)
17:18:45 [noah]
* An breakout session during TPAC plenary. You don't have to use the whole hour if you don't need it.
17:18:45 [noah]
* A lightning talk during the plenary session on "new work".
17:18:46 [noah]
We can do all of them, or a subset.
17:19:47 [Yves]
ht: we won't do a breakout session
17:20:10 [Yves]
ht: I'll happy to make sure we don't drop this
17:20:44 [masinter]
I'm thinking of a breakout sesssion about precision and error handling
17:21:08 [noah]
Larry, do we need to discuss that here.
17:22:09 [masinter]
no
17:22:45 [masinter]
i'm working on the "list of issues for Jeff" and want to talk about the issues to people at TPAC
17:23:21 [Yves]
Ashok: publishing and linking can be mentionned in item 1 or 3
17:23:38 [Yves]
noah: lightning talk would make sense
17:23:39 [masinter]
I'm trying to decide whether I want "last call" of P&L before or after TPAC
17:25:18 [masinter]
list of issues for jeff
17:25:53 [masinter]
the issues I have are governance, security, http, URI, TAG
17:26:21 [Yves]
Noah: we got this discussed at the f2f, no?
17:26:34 [masinter]
i'll go back and look at the minutes
17:26:35 [timbl]
timbl has joined #tagmem
17:26:35 [Yves]
Larry: the list is constructed form memory, I'll check the f2f minutes
17:27:08 [masinter]
s/form/from/
17:28:04 [Yves]
Topic: Publishing and Linking
17:28:49 [Yves]
Ashok: I added an executive summary
17:30:20 [Yves]
the document was sent on monday, no comments since then
17:31:09 [Yves]
diff is at
17:31:38 [Yves]
Larry: we told some people we would ask for feedback, I would like their comment before LC
17:31:39 [masinter]
Last call is a general call for review
17:31:54 [masinter]
if we have 3-4 specific people we want to ask for review, we could do that before Last Call
17:32:11 [masinter]
i could go either way
17:32:34 [Yves]
Noah: the trade-off is that we don't want to LC if we think it's broken. Here there is no downside of going to LC back to WD, so not a big deal either way
17:32:41 [ht]
+1 to last call now
17:32:53 [Yves]
Ashok: I'd rather go to LC now and deal with comments
17:33:06 [masinter]
i'm fine with Last Call now
17:33:14 [Yves]
Yves: looks fine to go to LC now
17:33:36 [masinter]
+1 to last call before TPAC
17:33:52 [Yves]
Ashok: when can it be published?
17:34:14 [masinter]
weren't we going to write exit criteria
17:34:36 [Ashok]
Yves, if we agree today, we can publish next week
17:35:40 [Yves]
Noah: my inclination here is not to dive in process issue about exit criteria, LC is a good next step to get attention on the document
17:36:47 [noah]
. PROPOSAL: We agree to take
to last call, expecting publication in time for TPAC review. Yves w/rest of TAG to get suitable W3C news announcement.
17:37:02 [masinter]
ok, the exit criteria discussion was about fragid, not p&l
17:37:55 [noah]
RESOLUTION: We agree to take
to last call, expecting publication in time for TPAC review. Yves w/rest of TAG to get suitable W3C news announcement.
17:38:01 [noah]
Approved without objection.
17:38:53 [Yves]
17:39:00 [Yves]
FPWD announcement.
17:39:20 [Yves]
Yves: we can iterate form this announcement, asking explicitly for feedback
17:40:08 [noah]
ACTION-747?
17:40:08 [trackbot]
ACTION-747 -- Ashok Malhotra to update product page on publishing and linking: dates and link to public draft -- due 2012-10-14 -- OPEN
17:40:08 [trackbot]
17:40:46 [masinter]
action-755?
17:40:46 [trackbot]
ACTION-755 -- Larry Masinter to with help from Ashok (and TAG), 1) decide exit criteria on Publishing & Linking 2) Rec track vs. Finding 3) Update product page to match -- due 2012-10-16 -- OPEN
17:40:46 [trackbot]
17:41:23 [noah]
ACTION-755 Due 2012-10-28
17:41:23 [trackbot]
ACTION-755 with help from Ashok (and TAG), 1) decide exit criteria on Publishing & Linking 2) Rec track vs. Finding 3) Update product page to match due date now 2012-10-28
17:41:36 [noah]
ACTION-747 Due 2012-10-28
17:41:36 [trackbot]
ACTION-747 Update product page on publishing and linking: dates and link to public draft due date now 2012-10-28
17:44:37 [noah]
ACTION-755?
17:44:37 [trackbot]
ACTION-755 -- Larry Masinter to with help from Ashok (and TAG), decide exit criteria on Publishing & Linking - must be ahead of CR -- due 2012-11-20 -- OPEN
17:44:37 [trackbot]
17:45:03 [noah]
ACTION-747?
17:45:03 [trackbot]
ACTION-747 -- Ashok Malhotra to update product page on publishing and linking: dates and link to public draft -- due 2012-10-28 -- OPEN
17:45:03 [trackbot]
17:45:54 [Yves]
Topic: action items
17:46:01 [noah]
ACTION-708?
17:46:01 [trackbot]
ACTION-708 -- Henry Thompson to check with Chris Lilley on likely near term progress of RFC 3023bis -- due 2012-09-01 -- PENDINGREVIEW
17:46:01 [trackbot]
17:46:46 [noah]
ACTION-564?
17:46:46 [trackbot]
ACTION-564 -- Henry Thompson to track fragid issues in 3023bis, report to TAG and/or communicate with 3023bis editors as appropriate -- due 2012-10-23 -- OPEN
17:46:46 [trackbot]
17:47:00 [ht]
17:47:30 [ht]
Keep 564
17:47:37 [ht]
Close 708
17:47:44 [noah]
close ACTION-708
17:47:44 [trackbot]
ACTION-708 Check with Chris Lilley on likely near term progress of RFC 3023bis closed
17:47:46 [ht]
Move date to 1-Dec-2012
17:48:03 [noah]
ACTION-564 Due 2012-12-01
17:48:03 [trackbot]
ACTION-564 Track fragid issues in 3023bis, report to TAG and/or communicate with 3023bis editors as appropriate due date now 2012-12-01
17:48:15 [noah]
ACTION-564?
17:48:15 [trackbot]
ACTION-564 -- Henry Thompson to track fragid issues in 3023bis, report to TAG and/or communicate with 3023bis editors as appropriate -- due 2012-12-01 -- OPEN
17:48:15 [trackbot]
17:48:30 [noah]
ACTION-733?
17:48:30 [trackbot]
ACTION-733 -- Larry Masinter to prepare for 30 minute report on HTTP 2.0/SPDY at October 2012 F2F -- due 2012-09-28 -- PENDINGREVIEW
17:48:30 [trackbot]
17:48:52 [noah]
ACTION-659?
17:48:52 [trackbot]
ACTION-659 -- Yves Lafon to track IETF efforts on HTTP 2.0 & SPDY -- due 2013-01-01 -- OPEN
17:48:52 [trackbot]
17:49:04 [noah]
close ACTION-733
17:49:04 [trackbot]
ACTION-733 prepare for 30 minute report on HTTP 2.0/SPDY at October 2012 F2F closed
17:49:28 [noah]
ACTION-750?
17:49:28 [trackbot]
ACTION-750 -- Noah Mendelsohn to contact Ian about TAG participation in TPAC -- see minutes of 8 Oct late afternoon -- due 2012-10-15 -- PENDINGREVIEW
17:49:28 [trackbot]
17:50:06 [ht]
Fine
17:50:16 [noah]
ACTION-750?
17:50:16 [trackbot]
ACTION-750 -- Henry Thompson to contact Ian about TAG participation in TPAC -- see minutes of 8 Oct late afternoon -- due 2012-10-30 -- OPEN
17:50:16 [trackbot]
17:50:36 [noah]
ACTION-744?
17:50:36 [trackbot]
ACTION-744 -- Noah Mendelsohn to send a message to the AB to ask them to review the election procedures for the TAG -- due 2012-10-14 -- PENDINGREVIEW
17:50:36 [trackbot]
17:50:46 [noah]
ACTION-734?
17:50:46 [trackbot]
ACTION-734 -- Noah Mendelsohn to schedule discussion of vendor prefixes (ACTION-711) at F2F -- due 2012-09-20 -- PENDINGREVIEW
17:50:46 [trackbot]
17:51:40 [noah]
ACTION-672?
17:51:40 [trackbot]
ACTION-672 -- Jeni Tennison to work with PLH to create W3C-sponsored registry of HTML extensions, and get that referenced from HTML media type registration, per
-- due 2012-05-29 -- OPEN
17:51:40 [trackbot]
17:51:51 [noah]
ACTION-724?
17:51:51 [trackbot]
ACTION-724 -- Henry Thompson to investigate possible TAG efforts on URI scheme proliferation and extension points -- due 2012-10-05 -- OPEN
17:51:51 [trackbot]
17:52:18 [Yves]
Yves: I recall we discussed extensions in general, we might keep discussion about CSS vendor prefixes as well
17:52:32 [Yves]
Noah: should we schedule discussion next week?
17:53:47 [Yves]
Peter: I brought the issues about CSS vendor prefix
17:53:57 [masinter]
registerCSSHandler ?
17:54:03 [Yves]
Noah: the question is.. is it a model for anything else?
17:54:40 [Yves]
Peter: there are discussions in the CSS WG about changing it, nothing concrete so far
17:54:52 [Yves]
Larry: it would be good to know what are the issues
17:55:15 [masinter]
i'm still interested in this topic
17:55:39 [noah]
ACTION-734?
17:55:39 [trackbot]
ACTION-734 -- Noah Mendelsohn to schedule discussion of vendor prefixes (ACTION-711) at F2F -- due 2012-09-20 -- PENDINGREVIEW
17:55:39 [trackbot]
17:56:47 [Yves]
Larry: can you brief us about csswg discussions about vendor prefixes?
17:57:01 [noah]
ACTION-711?
17:57:01 [trackbot]
ACTION-711 -- Peter Linss to report on CSS WG plans for documenting policies relating to deployment and withdrawal of vendor-prefixed identifiers -- due 2012-11-20 -- OPEN
17:57:01 [trackbot]
17:57:07 [Yves]
Peter: I have an action to write a document about that
17:57:45 [masinter]
i'm ok with dropping 734 and keeping 711 open
17:58:24 [Zakim]
-ht
17:58:35 [noah]
close ACTION-734?
17:58:43 [noah]
ACTION-711?
17:58:43 [trackbot]
ACTION-711 -- Peter Linss to report on CSS WG plans for documenting policies relating to deployment and withdrawal of vendor-prefixed identifiers -- due 2012-11-20 -- OPEN
17:58:43 [trackbot]
17:59:23 [noah]
close ACTION-734
17:59:24 [trackbot]
ACTION-734 schedule discussion of vendor prefixes (ACTION-711) at F2F closed
17:59:57 [noah]
ACTION-683?
17:59:57 [trackbot]
ACTION-683 -- Yves Lafon to figure out who might be a good choice to present Hybi (and as appropriate WebSocket protocols) to the TAG -- due 2012-10-02 -- OPEN
17:59:57 [trackbot]
18:00:31 [noah]
YL: Started to discuss w/Mike, but he was away. On hold.
18:00:49 [noah]
ACTION-683 Due 2012-12-04
18:00:49 [trackbot]
ACTION-683 Figure out who might be a good choice to present Hybi (and as appropriate WebSocket protocols) to the TAG due date now 2012-12-04
18:01:01 [noah]
ACTION-617?
18:01:01 [trackbot]
ACTION-617 -- Yves Lafon to work with Noah to take
off the Rec track -- due 2012-10-15 -- OPEN
18:01:01 [trackbot]
18:02:28 [noah]
ACTION-617 Due 2012-10-23
18:02:28 [trackbot]
ACTION-617 Work with Noah to take
off the Rec track due date now 2012-10-23
18:02:50 [noah]
Good Practice
18:02:50 [noah]
Specifications that define namespaces SHOULD explicitly state their policy with respect to changes in the names defined in that namespace.
18:03:02 [masinter]
seems like it belongs in the XML spec
18:03:57 [Zakim]
+??P1
18:04:32 [noah]
ACTION-617?
18:04:32 [trackbot]
ACTION-617 -- Yves Lafon to work with Noah to take
off the Rec track -- due 2012-10-23 -- OPEN
18:04:32 [trackbot]
18:06:29 [Yves]
ht: this is not the XML-core business, it's a TAG issue, relative to httprange-14
18:07:12 [masinter]
should be errata / addendum to namespace rec
18:07:30 [Zakim]
-noah
18:07:34 [ht]
Whoops
18:07:37 [Yves]
noah: how about publishing this document as a note, and send the pointer to that note to xml-core (to be put on there work pile if they think it's ok with them)
18:07:40 [ht]
I like Noah's suggestion
18:07:45 [Yves]
Yves: +1
18:07:47 [ht]
I have to leave :-(
18:07:59 [masinter]
+1
18:07:59 [Zakim]
-ht
18:08:34 [masinter]
add an XML section to
:P
18:08:34 [plinss]
+1
18:09:54 [Zakim]
+Noah_Mendelsohn
18:10:43 [Yves]
due to technical issues... ADJOURNED
18:10:46 [Zakim]
-Noah_Mendelsohn
18:10:48 [Zakim]
-Ashok_Malhotra
18:10:51 [Zakim]
-plinss
18:10:53 [Zakim]
-Yves
18:10:54 [Zakim]
-Larry
18:10:54 [Zakim]
TAG_Weekly()1:00PM has ended
18:10:54 [Zakim]
Attendees were ht, plinss, noah, Ashok_Malhotra, Yves, +1.415.832.aaaa, Larry, Noah_Mendelsohn
18:10:57 [RRSAgent]
I have made the request to generate
Yves | http://www.w3.org/2012/10/18-tagmem-irc | CC-MAIN-2014-52 | refinedweb | 3,066 | 58.35 |
In this exercise, you will learn how to use the Code First approach to add a database with the tables of the MusicStore application to consume its data.
Once adding the database and generating the model, you will make the proper adjustments in the StoreController to provide the View template with the data taken from the database instead of hardcoding it.
If you have not completed Exercise 1 but would like to learn the Code First approach, you can start from this exercise and get a full coverage of the topic.
In this task, you will add an already created database with the main tables of the MusicStore application to the solution.
Add an App_Data folder to the project to hold the SQL Server Express database files. App_Data is a special folder in ASP.NET which already has the correct security access permissions for database access. To add the folder, right-click MvcMusicStore project, point to Add then to Add ASP.NET Folder and finally click App_Data.
Adding an App_Data folder
Add MvcMusicStore database file. In this lab, you will use an already created database called MvcMusicStore.mdf. To do that, right-click the new App_Data folder, point to Add and then click Existing Item. Browse to \Source\Assets\ and select the MvcMusicStore.mdf file.
Adding an Existing Item
MvcMusicStore.mdf database file
The database has been added to the project. Even when the database is located inside the solution, you can query and update it as it was hosted in a different database server.
MvcMusicStore database in Solution Explorer
Verify the connection to the database. To do this, open the Database Explorer (CTRL+ALT+S), and then double-click the MvcMusicStore.mdf. The connection is established.
Connecting to MvcMusicStore.mdf
1. Open the Windows Services console. To do that, open the Run command from Start | All Programs | Accessories | Run, type services.msc and then click OK.
Figure 27
Running services.msc
2. Right-click the SQL Server (SQLEXPRESS) service and select Properties.
Figure 28
SQL Server (SQLEXPRESS) service
3. Open the Log On tab, select Local System account as the account to log on with and click OK. Accept the dialog by clicking OK again.
Figure 29
Changing the log on account
4. Restart the SQL Server (SQLEXPRESS) service.
Figure 30
Restarting SQL Server (SQLEXPRESS) service
5. Once the service is restarted, close the Services console and verify the connection to the database. To do this, select the Database Explorer, and then double-click the MvcMusicStore.mdf. The connection is established.
Figure 31
Connecting to MvcMusicStore.mdf
Close the connection now. To do that, in Database Explorer right-click on the MvcMusicStore database and select Close Connection.
Closing the connection
Now that we have already added a database to our project, we will write in the Web.config the connection string. Then will include an external library for Entity Framework 4 Code First.
Add a connection string at Web.config. To do that, open Web.config at project root and include these lines at the end of the file:
Web.config file location
XML
…
Add a new reference to the Code First assembly EntityFramework.dll. To do this, right-click References and select Add Reference:
Adding a reference
In the Add Reference dialog, click the Browse tab and navigate to Source\Assets\EntityFrameworkCTP5 and select EntityFramework.dll. Then, click OK:
Adding EntityFramework assembly
EntityFramework assembly added to the project
Now that we have already included code first library and connected the database, we will link the model with the database tables. In this task, we will create a class that will be linked to the database with Code First. Remember we already have a POCO model class that should be modified.
Open the POCO model class Genre from /Models project folder and include an ID, a description attribute, and also an album’s collection.
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First Genre – CSharp)
C#
using System;
You can read more about Code First Conventions in this msdn blog article.
Now, open the POCO model class Album from /Models project folder and include the AlbumId and GenreId properties.
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First Album – CSharp)
Right-click the Models project folder point to Add and then click Class to add a new class. Name it MusicStoreEntities.cs and click Add.
Adding a class
Adding a class(2)
Open the class you have just created, MusicStoreEntities.cs, and include the namespace System.Data.Entity.
Replace the class declaration to extend DbContext class: declare a public DBSet and override the method OnModelCreating. After this step you will get a domain class that will link your model with the Entity Framework. In order to do that, replace the class code with the following:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First MusicStoreEntities – CSharp)
By extending OnModel Creating we are specifying in the code how Genre will be mapped to a database table.
You can find more information about DBContext and DBSet in this msdn blog article: link
In this task, you will update the StoreController class so that instead of using hard-coded data, it can consume it from the database.
If you completed Exercise 1 you will note these steps are the same, independently from the approach (Database first or Code first). They are different in how the data is linked with the model, but the access to data entities has to be the transparent from the controller.
Open Controllers\StoreController.cs and add the following field to hold an instance of the MusicStoreEntities class, named storeDB:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First storeDB – CSharp)
public class StoreController : Controller
The MusicStoreEntities class exposes a collection property for each table in the database. Update StoreController’s Index action to retrieve all Genre names in the database. This was done previously by hard-coding string data. Now you can instead write a LINQ query expression like the one below which retrieves the Name property of each Genre within the database:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 code First Store Index – CSharp)
//
For more information about LINQ, please visit the msdn site.
Transform the collection of genres to a list. To do this, replace the following code:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First Genres to List – CSharp)
public ActionResult Index()
In this task, you will check that the Store Index page will now display the Genres stored in the database instead of the hard-coded ones. There is no need of changing the View template because the StoreController is returning the same StoreIndexViewModel as before, although this time the data will come from the database.
The project starts in the Home page. Change the URL to /Store to verify that the list of Genres is no longer the hard-coded list, else the ones taken from the database.
Browsing Genres from the database
Exercise 3: Querying the Database with Parameters
Download The Offline Training Kit
Download Hands-on Lab Document (DOCX)
Download Hands-on Lab Source Files | https://docs.microsoft.com/en-us/previous-versions/gg618474(v%3Dmsdn.10) | CC-MAIN-2019-30 | refinedweb | 1,194 | 65.01 |
Unable to get double click event in OpenCV for python
python get coordinates of mouse click on image
click and crop opencv
python click on image
opencv mouse control python
opencv select roi mouse python
python wait for mouse click
python detect mouse click
OpenCV with python(MAC OS X EL Capitan)
I'm creating a demo project to track mouse events in openCV. using standard mouseCallback from openCV.
following is my code for the same.
drawWithMouse.py
#!/usr/local/bin/local/python3 import numpy as np import cv2 as cv #Mouse callback function def draw_shape(event,x,y,flags,param): print("event : ",event) if event == cv.EVENT_LBUTTONDBLCLK: cv.circle(img,(x,y),100,(255,0,0),-1) #Create a black image, a window and bind the function to the window img = np.zeros((780,780,3),np.uint8) cv.namedWindow('DrawWithMouse') cv.setMouseCallback('DrawWithMouse',draw_shape) while(1): cv.imshow('DrawWithMouse',img) if cv.waitKey(10) & 0xFF == 27: #ANDing with 0xFF as my machine is 64 bit break cv.destroyWindow('DrawWithMouse')
with this implementation i'm always getting mouse down and mouseup event and only single click event. i'm unable to get double click event(EVENT_LBUTTONDBLCLK). value for this constant is 7.
i'm getting following output
You can try to workaround problem with time measurement, for example time.clock() (not precise butthe simplest) and calculation of time difference between click and previous one. If time is less than threshold perform double click action.
time =0 thresh = 1 #Mouse callback function def draw_shape(event,x,y,flags,param): print("event : ",event) if event == cv.EVENT_LBUTTONDBLCLK: if time.clock - time < thresh: //double click time = time.clock() cv.circle(img,(x,y),100,(255,0,0),-1)
Unable to get double click event in OpenCV for python, OpenCV with python(MAC OS X EL Capitan). I'm creating a demo project to track mouse events in openCV. using standard mouseCallback from openCV. There can be different types of mouse events such as left button click, right button click, double_click, etc. To manage these events we need to design callback functions for each type of mouse click event while the window or frame is opened by OpenCV.The callback function will be helpful to implement what type of functionality you want with a
I just tried running your code, to me everything seems fine. I click down and hold a 1 comes up, I release and there is a 4. When I double click there is a 7. This however doesn't work if the mouse is moving. Try keeping your mouse still while you double click or try another mouse
Unable to get double click event in OpenCV for python, OpenCV with python(MAC OS X EL Capitan) I'm creating a demo project to track mouse events in openCV. using standard mouseCallback from openCV. OpenCV and Python versions: In order to run this example, you’ll need Python 2.7 and OpenCV 2.4.X. Capturing mouse click events with Python and OpenCV. Let’s go ahead and get this example started. Open up a new file, name it click_and_crop.py , and we’ll get to work:
I freshly downloaded opencv-python in El Capitan for Python 3 since I didn't have it:
Downloading opencv_python-3.3.0.10-cp36-cp36m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (43.8MB)
Ran the example code and left button double click worked fine, creating lots of blue circles. I then tried to make it fail. The only thing I found that came close was setting double click speed to the highest mark in Systems Preferences / Mouse:
I found a significant difference between the highest setting and the second highest. Searching the web, using either the Fast or Slow extreme can be troublesome with double clicking.
Have you verified that your double clicking works in general? Although I can't find it currently, I believe there were once settings that converted double clicks into two individual clicks and other potential Macintosh quirks. Is X-Windows in any way involved with your setup?
Good luck.
How to read a mouse left click event in python?, You can try a workaround with time measurement, for example time.clock () (not accurate, but the easiest) and calculating the time difference between the click Mouse event can be anything related to mouse like left-button down, left-button up, left-button double-click etc. It gives us the coordinates (x,y) for every mouse event. With this event and location, we can do whatever we like. To list all available events available, run the following code in Python terminal:
For people like me who want to
copy-paste:
import time last_time = None def double_click(self, event, x, y, flags, params) """handle double click""" if event == cv2.EVENT_LBUTTONDOWN: if last_time is not None and time.time() - last_time < 1: cv2.circle(img, (x, y), 20, (255, 0, 0), 2) last_time = None else: last_time = time.time()
You can use the last parameter
params to pass your frame when setting the callback:
cv2.setMouseCallback("image", double_click, img)
Capturing mouse click events with Python and OpenCV , For example, I would like to make a code like this: while True: [. not explain how to have Python only recognize the mouse left click event. can't seem to get the code to work: def mouse(event,x,y,flags,param): if event == cv2. In this blog post I'll show you how to capture mouse events using Python and OpenCV. Using these techniques you'll be able to crop your image by selecting a rectangular region of the image using
Temporary simple hack (until someone comes up with a real answer):
Change event from 'EVENT_LBUTTONDBLCLK' to any non double click events (e.g. 'EVENT_LBUTTONDOWN')
OpenCV-Python/mouse_callback.py at master · abidrahmank , Capturing mouse click events with Python and OpenCV. by Adrian Rosebrock on It means not being able to drive to the gym. And it means being stuck in Python and OpenCV. Let's go ahead and get this example started. Drawing shapes on image file with mouse event. Contribute to farcompen/Opencv-drawing-with-mouse development by creating an account on GitHub.
Mouse as a Paint-Brush, Contribute to abidrahmank/OpenCV-Python development by creating an Find file Copy path A simple example about generating mouse callback function. It is targeted on an absolute beginner.This program just print the coordinates in the terminal when you double click at any You can't perform that action at this time. These Mouse events include mouse clicks (like left-button down, left-button up, left-button double-click etc) and movements over an attached OpenCV window. Capturing mouse click events with Python
How to Detect Mouse Clicks and Moves, Learn to handle mouse events in OpenCV; You will learn these functions : cv2. a simple application which draws a circle on an image wherever we double-click on it. Next we have to bind this mouse callback function to OpenCV window. Capturing mouse click events with Python and OpenCV – PyImageSearch. opencv python. Follow. Best Python Courses online, If you’re looking to move into the
Python mouse click event, All you have do is to define a callback function in the OpenCV C++ code attaching to the OpenCV window. That callback cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl; } //if fail to read the image This is what we will do in this blog i.e. write text on images at mouse click position. To do this, we will create a mouse callback function and then bind this function to the image window. Mouse callback function is executed whenever a mouse event takes place. Mouse event refers to anything we do with the mouse like double click, left click etc.
- I'd tried this on two different computers. Both are MAC machines.
- And I'm unable to get double click on any of them with two different mouse.
- @RajendrasinhParmar the same occurs to me on macos
- @Fred did you found any solution?
- i tried that. it's long time now. i should try it again. as everything is updated now in my system.
- I think this might be related to some other problem related to MAC pointing device driver and OpenCV interaction. However, your solution for EVENT_LBUTTONDOWN seems to do the trick. | https://thetopsites.net/article/51644722.shtml | CC-MAIN-2021-31 | refinedweb | 1,389 | 73.68 |
brian m. carlson writes ("Re: The "node" command in Debian"): >. Yes. > Lacking an official definition for "filename" in Policy, I think it's > reasonable to assume that it should not be read as "path", and instead > be read to forbid this use (as you said, Ian). Nevertheless, I see how > reasonable people could disagree. The point of the exercise is not just to stop dpkg complaining when the packages are installed (otherwise Conflicts would suffice). The point is to try to arrange that when one bit of the system (or a user) asks for something by name, they don't get something entirely unrelated. The same principle should apply to any namespace, not just the command namespace. So for example we would not tolerate a new kernel module that used AF_INET for something strange, nor two applications which used the same object paths in dbus for unrelated purposes, nor two sets of packages which use the same virtual package name for unrelated purposes, or anything else similar. Nor should we accept two sets of shared libraries which exported the same function names for different purposes (although I guess we don't check for this automatically, and there would probably be more cases where it would be easier to argue that there was no harm done). Ian. | https://lists.debian.org/debian-devel/2011/02/msg00144.html | CC-MAIN-2015-35 | refinedweb | 216 | 52.94 |
This.
This, of course, requires a different style of coding. The usual declarative way of programming no longer works. Spring requires the Reactor framework to support the "new way" of programming.
The two most important concepts are Mono and Flux. These two types wrap the results of all operations. Mono can have a zero or one result, while Flux can handle a continuous stream of elements.
The code example below emits the given elements, applies some mapping transformations, and prints them out to a standard:
Flux.just("keyword 1", "keyword 2") .map(s -> s.replace(" ", "")) .map(String::toUpperCase) .subscribe(System.out::println);
The API looks quite similar to the Java Streaming API. For our follow-up example, imagine the stream of data is emitted from the data source and the standard out is the output stream of the HTTP response.
Spring MVC vs Spring MVC WebfluxThis code snippet shows a Spring MVC Rest Controller. It has just one mapping that returns all the data found in the repository. First, it loads all the data, and then it writes the response:
@RestController public class TestController { @Autowired private TestDataRepository testDataRepository; @GetMapping("/api/") public Iterable<TestData> getTestData() { return this.testDataRepository.findAll(); } }
Using Webflux, the controller does the same as the controller above, except that it returns a Flux object. This object writes data to the client as soon as it is available:
@RestController public class TestController { @Autowired private TestDataRepository testDataRepository; @GetMapping("/api/") public Flux<TestData> getTestData() { return this.testDataRepository.findAll(); } }
With these two implementations in place, it is time to compare their performances.
Performance ComparisonDisclaimer: Performance testing itself is a complex topic. These performance tests should just give a first hint about which direction to pursue. The results for each use case and configuration will be different. Furthermore, they don't show absolute performance numbers, just performance figures relative to each other. All performance tests were done on the same setup and repeated a couple of times to get these results.
Our test use case is an application that provides a REST interface to load data from a Cassandra data store. There are 10,000 entries in the database. Each request loads all of these entries. This leads to enough I/O to show the advantage of the reactive implementation.
The code for the example applications can be found in our github repository.
Please check the repository for the driver versions used here.
Gatling TestThe code snippet shows the gatling test that was used for performance testing. It includes just one HTTP call to the REST interface. It ramps up 600 requests over one minute, so ~ 10 per second:
val httpProtocol = http .baseURL("") .inferHtmlResources() .acceptHeader("*/*") .acceptEncodingHeader("gzip, deflate, sdch") .acceptLanguageHeader("de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4") .userAgentHeader("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36") val headers_0 = Map( "Content-Type" -> "application/json", "Accept" -> "application/json") val headers_1 = Map("Pragma" -> "no-cache") val scn = scenario("RecordedSimulation") .exec(http("getData") .get("") .headers(headers_0)) setUp(scn.inject(rampUsers(600) over (1 minutes))) .protocols(httpProtocol)
Plain Spring MVC + CassandraThis test shows 600 requests over one minute. As we can see, the application is over its limit, with only 6.1 requests per second.
Spring Webflux + Cassandra ReactiveIn comparison, observe the new reactive implementation. The same test shows that it can handle 600 requests in one minute quite well. As we know, the threads are waiting most of the time to get data via I/O. Not blocking these threads from handling new incoming requests results in quite a good performance advantage.
As shown in the figure below, we can get quite a lot more requests per second, but the response times will suffer as a result. If we do not limit the threads on Tomcat, we can see that the Cassandra connection pool is exhausted before the Tomcat thread pool is. This is exactly as we expected. All in all, this allows for a better use of the system's resources.
I do love programming in java..enjoyed reading this
This comment has been removed by a blog administrator.
This is so useful for everyone. July 2017 printable calendar
August 2017 printable calendar
Your work is very good and I appreciate you and hopping for some more informative posts
go to website
Great article Lot's of information to Read...Great Man Keep Posting and update to People..Thanks
a fantastic read | http://tech.willhaben.at/2017/05/reactive-java-performance-comparison.html | CC-MAIN-2017-26 | refinedweb | 748 | 58.48 |
ADCDMAGen3_RK (community library)
Summary
Analog to digital conversion using DMA.
ADC DMA Gen3
Analog to digital conversion using DMA for Particle Gen 3 devices (Argon, Boron, Xenon)
Note: This feature is experimental and not supported. It may not work properly. It may break in a future version of Device OS. Beware!
Also, this is the preview release 0.0.1, there may still be bugs.
Introduction
Normally, on Particle (and Arduino) devices, the
analogRead() function reads a value from a pin synchronously. There's a limit to how fast you can do this, and also because of the task scheduling on Particle, it's hard to do this regularly.
The nRF52 MCU in the Particle Argon, Boron, and Xenon has the ability to sample the analog to digital converter (ADC) using DMA (direct memory access). This samples the ADC at precise intervals (even when interrupts are disabled) and stores the values in RAM. You can do this into a single buffer if doing a one-shot sample until the buffer is filled. Or you can use double buffers so the capture is continuous. Once one buffer is filled you can begin processing it while the other buffer continues to be filled.
Some caveats:
- This is an unsupported feature.
- You cannot mix calls to ADC DMA and
analogRead()at the same time. In order to
analogRead()you must
uninit()the ADC DMA.
- There are hardware timer limitations. In the examples below, NFC cannot be used at the same time as ADC DMA, but if you absolutely need to use NFC you could give up a different peripheral (like Serial1).
You typically create a
ADCDMAGen3 object as a global variable. You can only have one per app!
#include "ADCDMAGen3_RK.h" ADCDMAGen3 adc; const size_t SAMPLE_FREQ = 16000; // Hz const size_t SAMPLES_IN_BUFFER = 1024; static nrf_saadc_value_t buffer0[SAMPLES_IN_BUFFER]; static nrf_saadc_value_t buffer1[SAMPLES_IN_BUFFER];
Some constants and two buffers are set up as global variables as well.
You can either set up the settings from
setup() or right before you need to use ADC DMA.
ret_code_t err = adc .withSampleFreqHz(SAMPLE_FREQ) .withDoubleBuffer(SAMPLES_IN_BUFFER, buffer0, buffer1) .withSamplePin(A0) .withBufferCallback(myBufferCallback) .init();
Settings are made fluent-style with the
withXXX() methods. In the example above:
- Sampling frequency is set to
SAMPLE_FREQ(16000 Hz)
- Double buffering is enabled and stores
SAMPLES_IN_BUFFER(1024) samples in each of
buffer0and
buffer1. When one buffer is filled the bufferCallback is called and the other buffer will continue to be filled. This prevents losing samples while processing a buffer.
- Samples pin A0
- Sets the bufferCallback to the function
myBufferCallback.
- Finally calls
init()to complete the initialization.
You must call
init() and
start() to actually start sampling.
You can call
init() once and use
start() and
stop() as necessary.
Or you can call
init() and
start() whenever you want to sample and call
uninit() when done. This will release the ADC resources when not actively being used.
If you want to mix ADC DMA and
analogRead() you need to call both
uninit() and
restoreDefaults(). See the 07-mixed example for more information.
The other thing you need to do is set a bufferCallback, the function that's called when a
The bufferCallback function looks like this:
void my; }
Because we may want to do lengthy operations we just save the buffer pointer and handle it from loop().
The samples other than 01-simple use a C++11 lambda to handle the buffer callback. That technique can also be used to call a class member function if desired.
adc.with; });
In addition to the SAADC (successive approximation ADC) module in the nRF52, this library also requires a hardware timer. Unfortunately there are no free timers available and you'll have to steal one.
- 0: Softdevice - do not use
- 1: Radio - probably best to not use, might work if not using BLE or mesh
- 2: Usart (Serial1) Can use if not using Serial1.
- 3: Usart (Serial2 on Xenon) Cannot be used on Argon or Boron because it's required by NCP.
- 4: NFC - recommended (unless you need NFC). This is the default.
The default is to use the NFC timer, which means you can't use NFC at the same time. If you need NFC, then you can switch to using a different timer using
withHardwareTimer().
API documentation
The full API documentation can be found here.
Examples
01-simple
This is the simplest example, and the code is described above in the introduction.
02-audio-over-tcp
This sends audio data to a node.js server (located in the server directory).
I used an Adafruit 1713 Electret Microphone Amplifier - MAX9814 with Auto Gain Control. Connect:
- GND to GND
- Vd to 3V3
- Gain (leave unconnected)
- Out to A0
- AR (leave unconnected)
[image unavailable]
Make sure you update the example code with the IP address and port of your server.
To install the dependencies:
cd server npm install
To run the server:
npm start
To sample audio, tap the MODE button. It will connect to the server and send audio for 30 seconds, or until you stop it using the MODE button.
The server saves .wav files in the
out directory.
03-one-shot-freq-counter
This code samples A0 to find the dominant frequency. This is best tested by connecting a function generator to A0. Make sure it's set to a sine wave 0 to 3.3V, not sending negative voltages!
This samples at 200 kHz so it can detect frequencies up to a little less than 100 kHz.
The frequency is printed to USB debug serial. You can read it with a serial terminal program or
particle serial monitor.
04-continuous-freq-counter
This is a continuous version the frequency counter. When the frequency changes it's printed to the USB debug serial. It's limited to detecting frequencies up to around 24 kHz.
05-dtmf
This example listens to the microphone input on A0 and prints any DTMF (telephone keypad) frequencies it hears to USB debug serial.
06-dtmf-two-channel
This example shows how to handle sampling multiple pins using the DTMF decoder.
07-mixed
This example shows how to switch between ADC DMA and
analogRead() mode. Basically, make sure you call:
adc.uninit(); adc.restoreDefaults();
after using ADC DMA and before using
analogRead() again. Then call
adc.init() again if you want to use ADC DMA again. You don't need to reset the settings using the
withXXX() methods again; they are saved.
More Examples
The more-examples directory contains more examples, mainly based on the SSD1306 display.
more-examples/01-dtmf-display
Works like the 05-dtmf example, but displays the results on a 0.96" OLED SSD1306 display.
more-examples/02-spectrum
Based on the 04-continuous-freq-counter example, instead of picking the dominant frequency it displays the results on a SSD1306 display showing the amplitude on each frequency bucket.
I'm not completely sure the results are correct, however it does display something, and does update at 20 millisecond intervals, which is pretty impressive, in my opinion.
more-examples/03-frequency-counter
A slightly modified version of 04-continuous-freq-counter that samples at 200 kHz and displays the results on a SSD1306 display.
It's pretty close (97000 vs. 97070 Hz.)!
[image unavailable]
Version History
- 0.0.1 (2019-09-27) Initial version. There may be bugs still.
Browse Library Files | https://docs.particle.io/reference/device-os/libraries/a/ADCDMAGen3_RK/ | CC-MAIN-2022-27 | refinedweb | 1,221 | 57.98 |
Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.
Provides. If your deployment does not use file-based downloads, this parameter can be ignored. The default value is 1.
1
s.username
VARCHAR(128). The MobiLink user name.
2
s.publication_name
VARCHAR(128)
3
s.last_publication_upload
TIMESTAMP. Last successful upload time of this publication.
4
s.last_publication_download
TIMESTAMP. The last download time of this publication.
5
s.subscription_id
VARCHAR(128). The remote subscription ID.
6. The last_publication_download is the same value that was passed to the download scripts as the last download
time.
If an UltraLite remote is synchronizing with UL_SYNC_ALL, this event is invoked once with the name 'unknown'.
The generation_number parameter is specifically for file-based downloads. In file-based downloads, changes to generation numbers
are used to force an upload before the download when the file is applied at the remote. The number is stored in the download
file.
The output value of the generation number is passed from the begin_publication script to the end_publication script. The meaning
of the generation_number depends on whether the current synchronization is being used to create a download file, or whether
the current synchronization has an upload.' )
The following is the sample Java method endPublication. It outputs a message to the MobiLink message log. (Note that printing
a message to the MobiLink message log might be useful at development time but would slow down a production server.)
public String endPublication(
int'
)
The following is the sample .NET method endPub. It outputs a message to the MobiLink message log. (Note that printing a message
to the MobiLink message log might be useful at development time but would slow down a production server.)
public string EndPub(
int generation_number,
string user,
string pub_name,
DateTime last_publication_upload,
DateTime last_publication_download ) {
System.Console.Write(
"Finished synchronizing publication " + pub_name );
return ( null );
} | http://dcx.sap.com/1200/en/mlserver/end-publication-syncref.html | CC-MAIN-2019-18 | refinedweb | 312 | 50.84 |
tcp - TCP protocol
Synopsis
Description
Address Formats
Socket Options
Sockets API
Ioctls
Error Handling
Errors
Versions
Bugs
Colophon
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
tcp_socket = socket(AF_INET, SOCK_STREAM, 0);.
TCP is built on top of IP (see ip(7)). The address formats defined by ip(7) apply to TCP. TCP only supports point-to-point communication; broadcasting and multicasting are not supported..
The following ioctl(2) calls return information in value. The correct syntax is:
int value; error = ioctl(tcp_socket, ioctl_type, &value);
ioctl_type is one of the following:
When a network error occurs, TCP tries to resend the packet. If it doesnt.
Support for Explicit Congestion Notification, zero-copy sendfile(2), reordering support and some SACK extensions (DSACK) were introduced in 2.4. Support for forward acknowledgement (FACK), TIME_WAIT recycling, and per-connection keepalive socket options were introduced in 2.3.
Not all errors are documented.
IPv6 is not described..
This page is part of release 3.44 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.sgvulcan.com/tcp.7.php | CC-MAIN-2018-17 | refinedweb | 184 | 53.27 |
in reply to LibXML, XPath and Namespaces
Can I have my bonus points please??
use v5.10;
use strict;
use warnings;
use XML::LibXML;
my $xml = XML::LibXML->load_xml(IO => \*DATA);
say "The root element's namespace is: ",
$xml->documentElement->namespaceURI;
# Give that namespace a prefix so that we can reference it in XPath
$xml->documentElement->setNamespaceDeclPrefix("", "gt");
say "Look! The new prefix works! Found: ",
$xml->findvalue( '//gt:EnvelopeVersion');
__DATA__
<?xml version="1.0"?>
<GovTalkMessage xmlns="">
<EnvelopeVersion>2.0</EnvelopeVersion>
<Header>
<MessageDetails>
.....
</MessageDetails>
</Header>
<GovTalkDetails>
.....
</GovTalkDetails>
<Body>
<!-- A valid Body payload with a namespace declaration on the first el
+ement -->
</Body>
</GovTalkMessage>
[download].
Yes, I'm aware the prefix is meaningless. Word it how you like, I wanted some way of making a null/default prefix map to my namespace. I know that XML has its flaws and this seems to be one. | http://www.perlmonks.org/index.pl?node_id=1024823 | CC-MAIN-2017-47 | refinedweb | 143 | 60.01 |
arpc 0.5
A small library for using AMQP message queues for RPC-like communication
This is a small library for RPC (Remote Procedure Call) communication using AMQP. It uses amqplib (), thus it uses blocking sockets, no threads or other asynchronous libs. However, there is a support for timeouts and "lazy responses". It's not meant to be a framework, like celery/kombu, only a library for easy setup of AMQP broker for RPC. It does not affect performance and does not introduce many abstractions or "magic", raw AMQP objects can be accessed directly if needed.
A typical usage scenario is when a client is a webapp, and a server consists of a pool of "workers", possibly placed on many nodes (physical servers). The webapp calls a service, eg. "send_email", and one of the workers from the pool processes the request. For default messages (service arguments and responses) are JSON document, although it is not hardcoded.
Example: a service for adding numbers
Let's call the service "example". The class implementing the service is as follows:
class ExampleService(object): def c_add(self, req): return {'res': req['x'] + req['y']}
Methods prefixed with c_ are methods exposed for remote calling. The req argument is a request sent by a client. In this example this is a JSON document with x and y attributes. We return a dictionary with a result which will be converted to a JSON document. This is how the processing loop in a worker process is run:
from arpc import mq # Uses default connection parameters (localhost) amqp = mq.AMQPOperations(useack=True, persistent=True) server = mq.make_json_server(amqp, 'example', ExampleService()) server.loop()
The AMQPOperations class makes low-level AMQP operations and stores connection parameters. The second argument of make_json_server indicates the name of AMQP routing key from which the process will receive requests. You can scale the service by running many worker processes with the same routing key.
A client calls the service following way:
from arpc import mq sc = mq.ServiceCaller(mq.AMQPOperations(useack=True, persistent=True), 'example', want_replies=True) res = sc.send_request({'c': 'add', 'x': 4, 'y': 8})
By convention the request document should be a dictionary with a c attribute, under which the name of called method should be placed (without the c_ prefix).
Sending messages from command line
There is a script arpc_msg_sender.py included with the package (should be in $PATH after installation). It can be used for sending messages directly from command line. The first argument is a routing key, and the second is message body. After running a worker process (runnable example of ExampleService is here:) we can use it from command line:
$ arpc_msg_sender.py example '{"c":"add", "x":10, "y":20}' msg_sender 2011-05-01 17:53:39,454 INFO Message sent, waiting for response msg_sender 2011-05-01 17:53:39,492 INFO Result: <{u'res': 30}>
Managing worker processes
For every service's routing key foo there is created a mgt.foo routing key which processes management commands. We can ping workers to see what are available:
$ arpc_msg_sender.py mgt.example '{"c":"ping"}' msg_sender 2011-05-01 19:01:34,544 INFO Message sent, waiting for response msg_sender 2011-05-01 19:01:34,583 INFO Result: <{u'host': u'aserver', u'wid': u'arpc-example-4f741449e0', u'pid': 6868}> msg_sender 2011-05-01 19:01:34,584 INFO Result: <{u'host': u'aserver', u'wid': u'arpc-example-cd06537047', u'pid': 7177}> msg_sender 2011-05-01 19:01:34,584 INFO Result: <{u'host': u'aserver', u'wid': u'arpc-example-1bea3c09b4', u'pid': 7178}>
The wid is a "worker id", a unique string identifying this process. We can also get some statistics:
$ arpc_msg_sender.py mgt.example '{"c":"stats"}' msg_sender 2011-05-01 19:04:22,114 INFO Message sent, waiting for response msg_sender 2011-05-01 19:04:22,154 INFO Result: <{u'wid': u'arpc-example-1bea3c09b4', u'pid': 7178, u'host': u'aserver', u'waittimes': [u'0.0049', u'0.0040', u'0.0043', u'0.0046', u'0.0050', u'0.0038', u'0.0039', u'0.0038', u'0.0038', u'0.0044'], u'processed': 3333, u'exceptions': 0}> msg_sender 2011-05-01 19:04:22,154 INFO Result: <{u'wid': u'arpc-example-4f741449e0', u'pid': 6868, u'host': u'aserver', u'waittimes': [u'0.0039', u'0.0038', u'0.0038', u'0.0053', u'0.0043', u'0.0040', u'0.0040', u'0.0053', u'0.0042', u'0.0038'], u'processed': 13337, u'exceptions': 0}> msg_sender 2011-05-01 19:04:22,154 INFO Result: <{u'wid': u'arpc-example-cd06537047', u'pid': 7177, u'host': u'aserver', u'waittimes': [u'0.0055', u'0.0041', u'0.0041', u'0.0040', u'0.0056', u'0.0038', u'0.0038', u'0.0039', u'0.0038', u'0.0038'], u'processed': 3333, u'exceptions': 0}>
The waittimes is an array with seconds elapsed between processing last ten requests. processed and exceptions give number of requests processed by a worker with a success and with a failure (unhandled exception thrown).
Other management commands are eval for evaluating Python expression and kill for killing the workers by themselves. Other commands can be added easily.
If you want to send a message to a specific worker, then use a routing key mgt.<worker-id>, eg. mgt.arpc-example-1bea3c09b4.
Lazy requests
In the default situation, when you call a service which sends a reply, the call operation blocks until there is a reply available. By calling res = service_caller.send_lazy_request() instead of res = service_caller.send_request(), the call doesn't wait for a reply. This way you can eg. call requests to services at the beginning of rendering a webpage, and receive the results at the time you really need them. Receiving a real result is done by calling res.get(). However, if multiple lazy requests are made, there is no guaranteed results ordering.
Implementation notes
- using explicit send_request instead of using a proxy object (service.add(x, y)) is a feature - simpler stack traces and easier to search code for remote calls
- tested with RabbitMQ
- requires Python 2.7
- no thread-safety, designed to work with multi-process webservers like
- timeout can be specified as a send_request argument
- exception information is transferred from a client to a server (no full object serialization, only exception name and a traceback).
- Author: selfsorted
- Keywords: python rpc amqp rabbitmq queues scalability
- License: New BSD
- Categories
- Development Status :: 4 - Beta
- Intended Audience :: Developers
- License :: OSI Approved :: GNU General Public License (GPL)
- Programming Language :: Python
- Programming Language :: Python :: 2.7
- Topic :: Software Development :: Libraries :: Application Frameworks
- Topic :: System :: Clustering
- Topic :: System :: Distributed Computing
- Topic :: System :: Networking
- Package Index Owner: selfsorted
- DOAP record: arpc-0.5.xml | http://pypi.python.org/pypi/arpc/0.5 | crawl-003 | refinedweb | 1,129 | 54.32 |
So that is a bit of a snarky title. Today, I want to talk about techniques that you can use to transform non-normal data into a distribution that makes way more sense. This can be useful for all kinds of analysis like time-series I deal with non-normal data a lot. In fact, I’ve come to the opinion that the most normal thing about data is that it usually isn’t normally distributed. However, in many cases we would like to use a test that requires normality. I’ve seen a number of solutions that normalize data so that it fits on a certain scale, like zero to one, or data that is scaled in a certain way so that your variable is expressed in interesting units, like standard deviation units. I’ve even seen non-linear transformations like box-cox transformations which try to use a parametric function to cram the data into a normal distribution, more on this technique later.
Generally, what I see when I see somebody normalize their data is that they take the data and they transform it with a linear transformation. A good example is to scale the data so that it falls on the zero to one scale. This requires knowledge of the minimum and maximum for the data, but once you know that, you can make a linear transformation. You can verify this by taking the pearson correlation coefficient between the rescaled data and the original. You will get a correlation coefficient of one. That tells you that fundamentally, you haven’t done any alteration to the data. You can also convert the data into z-scores, this requires knowledge of the mean and standard deviation, but it is essentially a linear transformation. Again this does not fundamentally change the nature of your data, and you will get a correlation coefficient of unity. So the distribution doesn’t change using these methods, only the scale. And in certain circumstances, that is fine. Neural networks, for example, seem to like having all of the data on the same scale as the output. So making a linear transformation makes sense.
The Box-Cox Transform
Sometimes, however, we want to have nice bell curve shaped data, or maybe, we want a nice uniform distribution to the data because of some statistical test that we want to run. But data is so rarely well-behaved. If you have read up on statistics you might know something about the box-cox transform. This nifty little function has a single parameter. Which when that parameter hits a magic value, specific to your dataset, it will transform your data the best that it can to look as bell curve like that it can. That’s all well and good, except that there is a problem. Sometimes it does a great job, and other times it kind of sucks.
Here’s the formula:
Then you can use a maximum likelihood calculation using the normal distribution as your likelihood distribution to calculate the correct value of lambda. The only problem is that, now you have inherently provided extra uncertainty into the test that you are going to conduct. It pains me when I see this, because, that extra uncertainty is rarely, if never accounted for in the test. But I digress as that would be a potentially fun statistics paper to write for an academic journal, and that isn’t what I set out to do in this post.
Helpfully, the stats module in scipy has a nice function for doing a box-cox transform. It will even do that pesky maximum likelihood business for you. Even though I don’t like that the extra uncertainty isn’t accounted for very well in the statistical tests, the box-cox transform is battle tested. It just seems to work. And as an economist, it holds a special place in my heart, because it is tightly connected to CES (constant elasticity of substitution) production/utility functions. I won’t beat this point home too hard for those of you that don’t want to geek out on the neat microeconomic implications of the box-cox transform, but for those of you that care, it is the inverse of the CES equation.
Anyway, like I mentioned earlier, the box-cox transformation doesn’t have a guarantee that you will end up with anything that has a distribution that has the same properties as a normal distribution. It just says that it will find the best approximation constrained to that functional form. Usually, it does pretty good. Sometimes, it fails spectacularly. Either way, it works by making a monotonic transformation of the data.
Detour: What is a monontonic transformation?
Great question, a monotonic transformation is any transformation that never changes the direction, but only the magnitude of its slope.
I saw eyes glaze over. Let me try again, for our purposes, a monotonic function is a function that is always increasing. In other words, the derivative is always positive. Okay, so it could also be that it’s derivative is always negative, but just multiply everything by -1, and then you get a function that is always increasing. Use that as your working definition of what a monotonic transformation is. The technical definition is a little more complicated, but this is the definition that I carry around in my head.
Your next question is probably why do we care about monotonic transformations? Well, we like them because they do not change the ordering of our data. In microeconomics, we like them because utility functions don’t have meaningful units, so we can do a monotonic transformation to make the calculus simpler. For statistics, it means that our data will still reflect reality (the ordering of the variables stays correct, but the spacing might not.) It will screw up the units we are working with and make the interpretation of a test, coefficient, etc. harder for us in the end. Although, we may gain more than we lose, or lose more than we gain, depending on what we want to do.
The problem with box-cox transforms is that they are parametric, which gives them constraints. For the rest of this post, I will consider two non-parametric approaches to normalizing the data in such a way that we force the data to have a certain distribution. That might be useful, for example, in eliminating human bias from a dataset that relies on human judgment, like movie ratings, beauty contest scores, or figure skating competition scores. That’s right, I’m pulling the winter Olympics into the blog post.
So I grabbed the scores for the top 24 female figure skaters in the 2014 Sochi games. The reason for top 24 is that those are qualifying athletes that got to participate in the full competition. Although we could add a correction to the truncated scores I didn’t want to over complicate things. The scores ranged from a high of 224.59 and a low of 125 points.
Let’s take a look at the distribution of those points.
df = pd.read_csv('data/figure_skating.csv') df.dropna(subset=['Rank'],inplace=True) df.index = range(len(df)) df['Result'].hist() plt.title("Distribution of Women's Figure Skating Scores" "\nSochi 2014 Raw Scores") plt.ylabel('Number of Athletes') plt.xlabel('Score') plt.show()
Which will produce this figure:
We would expect something that looks normally distributed. Especially, since we are dealing with human levels of achievement. You would expect to see a bell curve around Olympic quality figure skating. But we can do a non-parametric transformation of this data to force it into a specific distribution. For example, let’s say that I want to force a uniform distribution on the data. I can use percentile normalization. Here’s the code:
def percentile_norm(data): mem_cache = {} out_list = [] for i in data: if i not in mem_cache: mem_cache[i] = percentileofscore(data, i, kind='strict') / 100.0 out_list.append(mem_cache[i]) return out_list
This code uses a memory caching technique to speed up the computations. Other than that it simply maps the percentile of a data point to the data point. It is a monotonic transformation because it preserves the ordering of the data. If you plot the distribution of this data you can confirm that you have morphed the distribution into a uniform distribution.
df['pnorm'] = percentile_norm(df['Result']) plt.hist(df['pnorm']) plt.title("Distribution of Women's Figure Skating Scores" "\nSochi 2014 Percentile Normalized") plt.xlabel('Normalized Score') plt.ylabel('Number of Athletes') plt.show()
Which will produce this histogram:
So yeah it’s uniform. And if you want to make sure that we really did do a monotonic transformation of the data, you can plot the original values against the normalized values.
plt.scatter(df['Result'],df['pnorm']) plt.title('Monotonic Transformation for Percentile Normalization') plt.show()
Which gives you this figure:
Notice that it isn’t exactly a nice looking function, that would be easy to parameterize, although I suppose you could do it. This method is non-parametric, a
as opposed to the box-cox transformation.
But we didn’t want a uniform distribution, we wanted to have a nice gaussian distribution. That is where gaussian quantile normalization comes in. The code below implements it using the same memory caching technique that we used for percentile normalization. Notice, that I kind of cheat by taking a random sample. You could fix this by looking up values for the percentile normalized scores off of the inverse cummulative distribution function, but hey, I was getting lazy. So make sure to set your seed or results may vary.
def gaussian_quantile_norm(data, seed=None): if seed is not None: np.random.seed(seed) gauss = norm.rvs(size=len(data)) gauss = np.sort(gauss) test = np.sort(data) mem_cache = {} out_list = [] for i in range(len(data)): if test[i] not in mem_cache: mem_cache[test[i]] = gauss[i] for i in range(len(data)): out_list.append(mem_cache[data[i]]) return out_list
I won’t beat the drum of how to create analogous graphs to those that I did for the percentile normalization. I think you should be able to figure that out. Or just go to my github repo and grab the code for this tutorial. So here is the figures for gaussian quantile normalization:
Also using the scipy implementation of the box-cox transform this is what you get.
Notice that the Box-Cox Transform is an almost linear function. That would say that our data was already mostly bell-curve shaped. So we didn’t need to do that. Also we can check the hypothesis that the lambda value from the equation above is statistically significant. If it isn’t then we can say that the data is approximately normally distributed. Which I’m not going to do, because well, I’m tired. But give it a try. | https://barnesanalytics.com/box-cox-transforms-and-other-nonparametric-normalization-methods | CC-MAIN-2018-09 | refinedweb | 1,824 | 55.95 |
It was an interface that launched a thousand hacks. Near trivial to program, enough I/O lines for useful work, and sufficiently fast for a multitude of applications: homebrew logic analyzers, chip programmers, LCD interfaces and LED light shows, to name a few.
Today the parallel printer port is on the brink of extinction (and good riddance, some would say). Largely rendered obsolete by USB, few (if any) new peripherals even include a parallel connector, and today’s shrinking computers — nettops, netbooks, media center PCs — wouldn’t have space for it anyway. That’s great for tidy desks, but not so good if you enjoyed the dirt-cheap hacks that the legacy parallel port made possible.
Fear not, for there’s a viable USB alternative that can resurrect many of these classic hacks! And if you’ve done much work with Arduino, there’s a good chance it’s already lurking in your parts drawer.
A recurring element among many recent hacks is the use of an Arduino or other USB-connected microcontroller as an intermediary between a PC and an external circuit. Code running on the microcontroller will poll some sensor to detect a change (for example, an empty coffee pot), then send a message over USB to a host PC where another program then acts on it (updating a web page to tell the world there’s no coffee). This is a reasonable approach, the parts are affordable and simple to program, but for many projects we can get by with just half the code, complexity and expense…and some folks will be thrilled to hear, no Arduino!
When the microcontroller on an Arduino board talks to a host PC over USB, all of the heavy lifting of USB communication is done by a separate chip: the FTDI FT232R USB to serial UART interface. This allows code on both the host and microcontroller to use much simpler asynchronous serial communication. As a size- and cost-cutting measure, some Arduino variants place this chip on a separate board to be attached only when programming the microcontroller, allowing it to be re-used for the next project.
This default USB-to-serial mode of the FT232R is what usually draws all the attention and gets all the girls. An alternate mode, less talked about but no less useful, is bitbang mode. This gives us independent software control of up to eight I/O lines, similar to the classic parallel port or the digital I/O lines of a microcontroller.
Acquiring the Hardware
If one isn’t already in your stash, FT232R breakout boards are easy to come by. Any shop that carries the Arduino Pro or LilyPad, or some of the bargain-priced Arduino derivatives (e.g. Boarduino), will also offer a programming cable that breaks out four of the FT232R I/O lines:
Four data lines may seem constraining, but for many tasks this is sufficient; projects using SPI communication, shift registers and port expanders will be well served. If you need the full complement of I/O lines, more sophisticated breakout boards are available:
Setting Up for Development
Another encouraging aspect of the FTDI interface is cross-platform software support; the same hacks can be created whether you’re using Windows, Linux or Mac OS X. Two software components are required to begin development: a device driver, which operates behind the scenes to handle all the low-level USB communication, and an API library, which is linked with your own code and forwards requests to the driver. Complicating matters slightly, there are two different APIs to choose from, and the setup process is a little different for each OS.
FTDI’s own API is called D2XX. This library is proprietary and closed source, but they do not charge for its use, even in commercial situations. An alternate API, libftdi, is community-developed and fully open source. This library has similar capabilities, but different function names and syntaxes. Conversion between the two APIs is very straightforward, and we’ll provide an example for each.
Windows users: if you’ve used Arduino before, the necessary driver is already installed. Otherwise, download and extract the latest Windows driver from the FTDI web site. When first connecting an FTDI cable or breakout board, use the Found New Hardware Wizard to locate and install the driver. If you want to use the D2XX library, the header and object files are included in the driver folder. This is the easier option. If you’d prefer the open source libftdi, you’ll need to download and install the both the libusb-win32 device driver and source code, then download and build libftdi.
Linux users: most current Linux distributions already have the necessary driver present as a kernel module. The D2XX library for Linux can be downloaded from the FTDI driver page, but libftdi is easier to install: simply locate libftdi-dev in your favorite package manager and have it take care of the dependencies when installing. In either case, FTDI programs for Linux need to be run as root, e.g.
sudo ./hello-ftdi
Mac OS X users: download the D2XX library from the FTDI download page. The included ReadMe file will explain how to install this library. If you’d prefer to use libftdi, download the source for libusb (legacy 0.1.12 version) and libftdi from their respective sites, then use the following commands in a Terminal window to build and install each of the two libraries:
./configure make sudo make install
If you’ve used Arduino in the past or have the FTDI Virtual Com Port (VCP) driver installed for any other reason, this needs to be disabled before bitbang mode will work on the Mac; the two cannot coexist. In a Terminal window, type:
sudo kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext
To restore the driver and resume using Arduino or other FTDI serial devices:
sudo kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext
Other operating systems: drivers for several other platforms are available. Please see the FTDI drivers page for details and links.
Most of the FTDI sample code is written in C, and that’s what we’ll use here. Bindings for other languages are available on the FTDI web site.
Hello World: Flash an LED
The standard introductory program for nearly every microcontroller is the LED flasher, so let’s give that a try. You’ll need an FTDI cable or any of the breakout boards, one LED and a 220 Ohm resistor.
Connect the resistor to either leg of the LED, but keep note of which leg is the positive (anode) side. Then insert the LED/resistor pair into the socket on the end of the FTDI cable as shown below, with the negative leg connected to the GND line (the black wire on the FTDI cable) and the positive leg to the CTS line (brown wire).
Here’s the C source code, using the libftdi API. If you plan on using D2XX, have a look at the second listing a bit later; the relationship between functions should be fairly obvious.
/* hello-ftdi.c: flash LED connected between CTS and GND. This example uses the libftdi API. Minimal error checking; written for brevity, not durability. */ #include <stdio.h> #include <ftdi.h> #define LED 0x08 /* CTS (brown wire on FTDI cable) */ int main() { unsigned char c = 0; struct ftdi_context ftdic; /* Initialize context for subsequent function calls */ ftdi_init(&ftdic); /* Open FTDI device based on FT232R vendor & product IDs */ if(ftdi_usb_open(&ftdic, 0x0403, 0x6001) < 0) { puts("Can't open device"); return 1; } /* Enable bitbang mode with a single output line */ ftdi_enable_bitbang(&ftdic, LED); /* Endless loop: invert LED state, write output, pause 1 second */ for(;;) { c ^= LED; ftdi_write_data(&ftdic, &c, 1); sleep(1); } }
If the program successfully compiles (all of the required headers and libraries in the appropriate locations, and properly linked with our own code), the LED should flash slowly.
The code is largely self-explanatory, but there are a couple of points worth highlighting:
- Note the second parameter to ftdi_enable_bitbang(). This is an 8-bit mask indicating which lines should be outputs (bit set) vs. inputs (bit clear). As we’re only using a single output line (CTS in this case), we set just the one bit corresponding to that line (0x08). For additional outputs, we can OR the bit values together. The bitbang I/O pin mappings aren’t defined in either API’s header, so you might find it helpful to keep around a header such as this:
#define PIN_TX 0x01 /* Orange wire on FTDI cable */ #define PIX_RX 0x02 /* Yellow */ #define PIN_RTS 0x04 /* Green */ #define PIN_CTS 0x08 /* Brown */ #define PIN_DTR 0x10 #define PIN_DSR 0x20 #define PIN_DCD 0x40 #define PIN_RI 0x80
- Notice that the second parameter to ftdi_write_data() is a pointer to an 8-bit variable. The function normally expects an array (and the second example will demonstrate this), but for this simple case only one value is required. When issuing a single byte like this, remember to always pass by reference (a pointer), not a numeric constant. The last parameter to the function is the number of bytes.
The value(s) passed to ftdi_write_data() indicate the desired state of the output lines: a set bit indicates a logic high state (3.3 or 5 volts, depending on the FTDI adapter used), and a clear bit indicates logic low (0 volts). The mapping of bits to I/O pins is exactly the same as for ftdi_enable_bitbang(), so the prior #defines may be helpful in that regard.
More Bells and Whistles
There are many project ideas that only occasionally need to toggle an I/O line: ring a bell when a web counter increments, flash a light when email arrives, send a Tweet when the cat uses the litter box. The code for such tasks will often be just as simple as the example above. But when communicating with more complex devices and protocols, this byte-at-a-time approach becomes very inefficient. Every call to ftdi_write_data(), even a single byte, issues a USB transaction that will be padded to a multiple of 64 bytes, and there can be latencies of a full millisecond or more before this request is actually sent down the wire. To efficiently send complex data streams, it’s necessary to pass an entire array to the ftdi_write_data() function.
Bitbang mode operates very differently than the chip’s default serial UART mode. In the serial configuration, one simply calls fwrite() to issue a block of data to the serial port, and the chip manages all the details of the transmission protocol: word length, start, stop and parity bits, and toggling the logic state of the TX line at the required baud rate. In Bitbang mode there is no implied protocol; this is raw access to the data lines, and we must take care to construct a meaningful signal ourselves, essentially creating an image map of the data lines over time:
Suppose we want to communicate with a device that uses the SPI protocol (Serial Peripheral Interface, also sometimes called Microwire, synchronous serial or three- or four-wire serial, depending on the implementation). The required output would resemble the waveform in the illustration above: one output line provides a clock signal, another represents the data bits (in sync with the clock), and a third issues an end-of-data latch signal. If sending 8 bits of data, our output array would need to be twice that size (to represent the high and low state of each clock tick), plus two additional bytes for the latch high/low at the end. 8 * 2 + 2 = 18 bytes in the output array (possibly a few extra bytes, if a specific device requires a short delay before the latch signal).
SPI might be too esoteric for an introductory article; not everyone will have the right components around. Instead, let’s make something visually gratifying: we’ll drive a group of LEDs using pulse width modulation. This is of dubious utility but it’s flashy and hints at the speed and fine control that’s possible using this port.
The hardware setup is similar to the first example, but repeated four times: four LEDs, four 220 Omh resistors (we’re limiting it to four in order to work with the FTDI cable or SparkFun Basic Breakout, but it’s easily expandable to eight with the other boards). The negative legs are all connected in common to the GND line (black wire on the FTDI cable), while the positive legs are connected to CTS, TX, RX and RTS (brown, orange, yellow and green wires, respectively). The SparkFun Basic Breakout has DTR in place of RTS for the last pin, but the example code will work the same with either one…we’ll explain how shortly.
Here’s how the components look on a breadboard. Notice that the +5V line (red wire on FTDI cable) is skipped:
And here’s the source code, using the D2XX API. Adapting this to libftdi is straightforward; see the first example for the different syntaxes.
/* pwmchase.c: 8-bit PWM on 4 LEDs using FTDI cable or breakout. This example uses the D2XX API. Minimal error checking; written for brevity, not durability. */ #include <stdio.h> #include <string.h> #include <math.h> #include <ftd2xx.h> #define LED1 0x08 /* CTS (brown wire on FTDI cable) */ #define LED2 0x01 /* TX (orange) */ #define LED3 0x02 /* RX (yellow) */ #define LED4 0x14 /* RTS (green on FTDI) + DTR (on SparkFun breakout) */ int main() { int i,n; unsigned char data[255 * 256]; FT_HANDLE handle; DWORD bytes; /* Generate data for a single PWM 'throb' cycle */ memset(data, 0, sizeof(data)); for(i=1; i<128; i++) { /* Apply gamma correction to PWM brightness */ n = (int)(pow((double)i / 127.0, 2.5) * 255.0); memset(&data[i * 255], LED1, n); /* Ramp up */ memset(&data[(256 - i) * 255], LED1, n); /* Ramp down */ } /* Copy data from first LED to others, offset as appropriate */ n = sizeof(data) / 4; for(i=0; i<sizeof(data); i++) { if(data[i] & LED1) { data[(i + n ) % sizeof(data)] |= LED2; data[(i + n * 2) % sizeof(data)] |= LED3; data[(i + n * 3) % sizeof(data)] |= LED4; } } /* Initialize, open device, set bitbang mode w/5 outputs */ if(FT_Open(0, &handle) != FT_OK) { puts("Can't open device"); return 1; } FT_SetBitMode(handle, LED1 | LED2 | LED3 | LED4, 1); FT_SetBaudRate(handle, 9600); /* Actually 9600 * 16 */ /* Endless loop: dump precomputed PWM data to the device */ for(;;) FT_Write(handle, &data, (DWORD)sizeof(data), &bytes); }
When successfully compiled and run, the LEDs should slowly pulsate in a repeating “chaser” cycle. There are some notable differences from the first example:
- LED4 is defined by two bits, a logical OR of both RTS and DTR, and the two bits are always toggled in unison. This isn’t a mandatory requirement, it simply makes the program compatible with different hardware: the FTDI cable and the SparkFun Basic Breakout use a different signal on the last pin, and toggling both bits makes it work the same regardless.
- The baud rate is explicitly set to 9600 bps (bitbang mode will actually run at 16 times the baud rate). This is so the PWM speed will be the same whether using libftdi or D2XX. The former library normally initializes the port to 9600 baud by default, while the latter API (used here) opens the port at maximum speed and we need to slow it down to match. In practice, at maximum speed we’re able to get about 650,000 8-bit samples per second out this port.
- In Mac OS X 10.6, you may find it necessary to pass the -m32 flag to gcc in order to compile and link with the D2XX library. And Windows programmers using Cygwin may need some additional header files:
#include <stdarg.h> #include <windef.h> #include <winnt.h> #include <winbase.h>
Pulse width modulation makes for a nice visual demonstration of speed but unfortunately can’t really be put to serious use. In addition to the previously-mentioned I/O latency, other devices may be sharing the USB bus, and the sum total is that we can’t count on this technique to behave deterministically nor in realtime. PWM with an LED looks just fine to the eye…the timing is close enough…but trying to PWM-drive a servo is out of the question. For a synchronous serial protocol such as SPI, where a clock signal accompanies each data bit, this method works perfectly, and hopefully that can be demonstrated in a follow-up article.
Not a Panacea
FTDI bitbang mode comes in handy for many projects, but it’s not a solution to every problem. There are many situations where a microcontroller is still preferable:
- For extended standalone use, it’s a no-brainer: a microcontroller board costs less than a fancy meal and runs for days on a 9-volt battery. Only when a project is going to involve a full-on PC anyway should bitbang mode be considered.
- If a task involves basic analog-to-digital conversion, you’re almost certainly better off using a USB-connected microcontroller with built-in ADC. It’s just less hassle than the alternative.
- For tasks that require continual high-speed polling of a sensor, bitbang mode will needlessly gobble USB bandwidth and CPU cycles. Most microcontrollers have an interrupt-on-change feature that avoids polling entirely, using resources only when a change actually occurs.
We hope this introduction has planted the seeds of new hacks in your mind, or will breathe new life into forgotten classic parallel port hacks. To dig deeper, the FTDI web site is the best resource. Here you’ll find data sheets, articles, and most useful of all are the application notes. There’s also information for working with other languages: Java, Perl, Python and Visual Basic, among others.
80 thoughts on “Introduction To FTDI Bitbang Mode”
sweet! | https://hackaday.com/2009/09/22/introduction-to-ftdi-bitbang-mode/?replytocom=96030 | CC-MAIN-2019-26 | refinedweb | 2,977 | 57.5 |
svg file reading and display
svg file reading and display i want a sample program for reading and displaying the content of a svg file
Developing Struts Application
Developing Struts Application
... outline of Struts, we can
enumerate the following points.
All requests... of the servlets or Struts Actions...
All data submitted by user are sent multiple xml files
Reading multiple xml files How can we read many xml files from a folder? The same procedure as that of "listfiles
Reading and writting multiple files
Reading and writting multiple files how can i read and write say two different files at the same time using threads
Reading files in Java
Reading files in Java I have to make a program in my project....
Please provide me the example code for reading big text file in Java. What do you suggest for Reading files in Java?
Thanks a big file effeciently
Reading a big file effeciently How to read a large text file quickly without memory error in Java?
What is the best method to read a big file very efficiently?
Thanks
Hi,
Kindly check the program Java Read File
Reading excel via JSP
Reading excel via JSP The problem is while reading cells values... the space between words and get full cell value? I am reading the value...(means while reading the cell values space should be ignored between the words cookies in jsp
Reading cookies in jsp How read cookies in jsp ?
Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can
Best way to reading file in java
Best way to reading file in java Hi,
As a beginner I want to learn about Java programming and make a program for reading a text file in java. What is the best way for reading file in Java?
Thanks......
reading from pdf
reading from pdf how can i read specific words from pdf file?
Java Read pdf file
import java.io.*;
import java.util.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class ReadPDF {
public
reading excel sheet in java
reading excel sheet in java can anyone tell me a proper java code to read excel sheet using poi
Here is a java code that reads an excel file using POI api and display the data on the console.
import java.io. 2 Date Examples
1St Grade Reading Games
file reading - Swing AWT
Reading .doc file using swing
Reading .doc file using swing Sir,
Could U Please Tell me the Way To Read .doc file in java using swing
Writing for the Purpose of Reading
Writing for the Purpose of Reading
... in
the link or probably the address of the link.
- Its good to use hyperlinks to provide... and terms or background reading or
reference information.
- The font size that you a xml file - JSP-Servlet
Reading a xml file how to read a xml file using jsp and then i have to retrive a data from that file use it in code? Hi Friend,
Please visit the following
Reading the body of mail excluding the signature
Reading the body of mail excluding the signature Consider the body of mail as given below-
Hi, How do you do?
XYZ
(Image)
xyz@abc.com
Disclaimer
Reading and Writing files - Java Beginners
Reading and Writing files Hello,
please help me to Develop a simple Java application that, when run, Welcomes the users and tells them the name of the last person to run the application, this information should be retrieved
reading dropdown values from properties file in jsp
reading dropdown values from properties file in jsp reading dropdown values from properties file in jsp
reading and displaying svg file through java
reading and displaying svg file through java sample program for reading a svg file
implementing DAO - Struts
know only few concept of Structs(very basic, and not worth to mention ), how... it, and show some sample codes ?
Sorry if my question is very basic and not worth
Reading child of child nodes in xml
Reading child of child nodes in xml Hi I am using the following XML file and would like to read the data for respective date in the child nodes. I want to pass date and want to retrieve data for that particular date.
document reading in java - Java Beginners
document reading in java Hi Dipak,
Can you tell me how to read pdf files in to java.i want convert pdf file in xml format through java coding.can you please help me? Hi Friend,
Try the following | http://www.roseindia.net/tutorialhelp/comment/28192 | CC-MAIN-2015-11 | refinedweb | 775 | 67.59 |
Adding SPFx webpart to Microsoft Team Tab
With SPfx version 1.8, Microsoft has provided 2 additional Supported Host for SPFx webpart.
- Add to Microsoft Team tabs
- Single Page App Framework (App Pages).
For this article, we will focus on adding SPFx webpart to Team tabs and know how to use Microsoft Team context in code for accessing MS Team related data.
Pre-requisites – You have a working SPFx webpart (if not you can create a new Hello World from example here)
For my example, I have a SPFx solution with name ‘all-platforms-webpart’. Let us convert existing webpart so that it can be added to Team tabs.
Step 1 – Enable Webpart to be deployed as Teams tabs
- Go to webpart.manifest.json
- Add below line to json, if entry already exist just make sure you Add “TeamTab’ in “supportedHosts”
“supportedHosts”: [“SharePointWebPart”, “TeamsTab”],
- Every MS Team has associated SharePoint site collection created where all content is stored.
- To check site associated for a MS team, refer below screenshot
Now for simplicity of this example, we will configure this solution as tenant wide deployment, by doing this we won’t have to deploy this solution individually to each site collection. It would be globally deployed to all Site collections from app catalog. However please note that if you don’t want tenant wide deployment of your SPFx solution, you can skip this step. But then to add this app to MS team, you will have to individuall add this solution on MS Team site collection(refer above screenshot on how to go to MS team site collection, rest is as usual, add app and install)
For tenant deployment, go to ./config/package-solution.json, add attribute “skipFeatureDeployment”: true like below.
{ "$schema": "", "solution": { "name": "all-platforms-webpart-client-side-solution", "id": "fbf5059e-a0c9-4aba-9258-670a7cc3fa6a", "version": "1.0.0.0", "includeClientSideAssets": true, "isDomainIsolated": false, "skipFeatureDeployment": true }, "paths": { "zippedPackage": "solution/all-platforms-webpart.sppkg" } }
Step 3 – Updating webpart code to be read Microsoft Teams context
- Open AllPlatformWebPartWebPart.ts for the needed edits on making our solution aware of the Microsoft Teams context, if it’s used as a tab.
- Import team modules
import * as microsoftTeams from ‘@microsoft/teams-js’;
- Create variable to store teamContext
export default class AllPlatformWebPartWebPart extends BaseClientSideWebPart<IAllPlatformWebPartWebPartProps> { // This variable has been added private _teamsContext: microsoftTeams.Context;
- Add onInit method to initialize team context
protected onInit(): Promise<any> { let retVal: Promise<any> = Promise.resolve(); if (this.context.microsoftTeams) { retVal = new Promise((resolve, reject) => { this.context.microsoftTeams.getContext(context => { this._teamsContext = context; resolve(); }); }); } return retVal; }
- Update render method to read context and apply business logic accordingly. Based on TeamContext or SharePointContext we have to use control our logic to make sure single webpart works in both host.
public render(): void { let title: string = ''; let subTitle: string = ''; let siteTabTitle: string = ''; if (this._teamsContext) { // We have teams context for the web part >`; }
Step 5 – Check and verify teams icon and outline
To sync SPFx webpart to Teams, we need to make sure our solution has color and outline png file which is required. You will find this files in teams folder in your project root directory
Name of this file should be in specific format, Teams folder contains the following two files:
- [componentId]_color.png – Default small picture for a tab
- [componentId]_outline.png – Default large picture for a tab
componentId here is GUID of webpart – We can find this in webpart.manifest.json file with “id” attribute.
Step 4 – Package the solution.
gulp build
gulp bundle –ship
gulp package-solution –ship
Solution file will be created at “D:\SP\Samples\all-platforms-webpart\sharepoint\solution” with name ‘all-platforms-webpart.sppkg’
Step 5 – Deploy Package
Note – If you do not have an app catalog, a SharePoint Online Admin can create one by following the instructions in this guide: Use the App Catalog to make custom business apps available for your SharePoint Online environment.
- Go to site catalog
- Drag and drop you .sppkg file on App for SharePoint
- Trust the solution, Ensure that the Make this solution available to all sites in the organization option is selected, so that the web part can be used from the Microsoft Teams side.
- Click Deploy, ensure webpart is deployed with error(refer error column in view)
Step 6 – Sync solution to Team
- Click you solution, on ribbon we will see ‘Sync to Team options’
- You should get success message.
Step 8 Add tab to MS Team
- Visit MS team, click on + symbol as below
- Below popup should open, find our web part with name, Select our web part
- Click Install
- Once added, we can see below web part added as tab in MS Team
- If you notice, we are getting message Welcome to Team
That’s it, we have successfully deploy SPFx webpart to Microsoft Teams tabs. | https://siddharthvaghasia.com/2019/06/09/adding-spfx-webpart-to-microsoft-team-tab/ | CC-MAIN-2020-40 | refinedweb | 803 | 50.67 |
Python/ru an object that can be used as the base of another drawing function.
Wire = makeWire(pointslist, closed=True, face=True) Window = makeWindowWindow() and
myModule.makeWindow() may coexist without problem.
Full examples should include the necessary imports and the prefixed functions.
import FreeCAD, Draft p1 = FreeCAD.Vector(0, 0, 0) p2 = FreeCAD.Vector(1, 1, 0) p3 = FreeCAD.Vector(2, 0, 0) Wire = Draft.makeWire([p1, p2, p3], closed=True)
import FreeCAD, Draft, Arch p1 = FreeCAD.Vector(0, 0, 0) p2 = FreeCAD.Vector(1, 0, 0) p3 = FreeCAD.Vector(1, 1, 0) p4 = FreeCAD.Vector(0, 2, 0) pointslist = [p1, p2, p3, p4] Wire = Draft.makeWire(pointslist, closed=True, face=True) Structure = Arch.makeStructure(Wire, name="Big pillar") | https://www.freecadweb.org/wiki/Python/ru | CC-MAIN-2019-43 | refinedweb | 119 | 65.39 |
I'm trying to hook things such as entity creation and player run_command but they don't work at all. Nothing is output in console no matter what.
Example of code that works in tf2 but not tf2c (mod)
Code: Select all
from listeners import OnPlayerRunCommand
def IsPlayerBot(Obj):
if Obj.is_bot == True:
return True
elif Obj.playerinfo.is_fake_client():
return True
else:
return False
# This will never run #
@OnPlayerRunCommand
def on_player_run_command(player, user_cmd):
print("hook")
if (IsPlayerBot(player)):
user_cmd.forward_move = 0
user_cmd.side_move = 0
pass
Strangely though on_tick and on_player_say work fine. Right now I can work with that but its very limiting.
Does someone more experienced know what is happening and why it doesn't work? | https://forums.sourcepython.com/viewtopic.php?f=20&p=14714 | CC-MAIN-2020-45 | refinedweb | 117 | 51.14 |
Creating Your First C# Program - 02
- Posted: Nov 21, 2011 at 9:08 AM
- 469,285 Views
- 150 teaches you how to create a simple application—first using Windows Notepad and the C# Command Line Compiler, and then by using Visual Studio or Visual C# Express Edition. The point of this episode is to demonstrate how utilizing an Integrated Development Environment (IDE) is far easier than attempting to work using a loose collection of windows and tools. The video concludes with an explanation of common solutions to the many different problems you might encounter as you first begin writing and compiling code.
Download the source code for Creating Your First C# Program
IMPORTANT UPDATE: Before you watch this lesson, please make sure you have watched this video to learn about changes to Visual Studio since this series was originally recorded.
Thanks!
Excellent. Can't wait to work through the rest of the series
is it my pc problem or what i can see anything you type on the note pad .
i only see funny char.
Video resolution too low for a big screen (1680 X 1050) cant see the words on notepad
Thank you for great tutorial that i was understood foundamental of C# language
One thing to note that your VDO is not high resolution that it doesn't see your code at all.
Thank you.
I can only read parts of what you are typing at 2:36 and beyond. Otherwise some of the words/letters are hard or not possible to read because the type is so small.
Very clean and awesome
Awesome!!
@Chairat, @Justin ... and future reference for others ...
Short story: If you are streaming the videos you can try using the expand icon in the video player to view the video full screen. If, when in full screen mode the text is garbled, then you must DOWNLOAD the video to your computer first (see downloads to the right of the video player) to watch it using Windows Media Player (or other media player).
The videos were recorded in High Def resolution, 1280 x 720 (so, 720p).
Long story: After recording the videos, Channel 9 encodes the videos for streaming using Silverlight Smooth Streaming. Based on your bandwidth, computer processor, etc. enough video data is sent to render the video as best as possible to avoid gaps or pauses in playback. With "live video" like a movie or tv show, this usually means the video is pixelated but still acceptable. With screen cast videos where you are trying to read the small text on screen, this usually renders the text unreadable. The solution, as I mentioned previously, is to DOWNLOAD the video to your local computer THEN watch it.
Hope that helps!
Your excellent videos would be complete if we can download the exact script of your speech.
Thanks
Your excellent videos would be complete if we can download the exact script of your speech.
Thanks
Sir,
i would like u to please tell me a book which is best for learning C# with .net so that i can make my C# concepts more strong.
sir please help.
thank u
Thanks. It's really a good start for me now that I'm learning Razor. Can't wait to go through the whole process, but I'll be taking it one at a time.
By the way, what's the meaning of :
using System;
using System.Web
using System.Collections.Generic;
using System.Linq;
using System.Text;
Thanks
Heyz...!!
First of all man nicest WORK! Thanks a ton for this great help... I was starving for such help Thanks once again :)
and sir is it possible to download this complete series on my PC through torrent download..
As my streaming is too slow.. once it'll be completely downloaded i can learn from it without any waiting and interruption. please do consider my request.
And please if its possible for you to provide some guideline for MCTS preparation, please help me on this too.
ThanKS!!
@HEROLD: I believe we do talk about the using statements later in this series when I talk about Namespaces. Stay tuned!
@Naqi Agha: I believe each video has a download link at the very top of this and every Channel 9 video page. I don't know if there's a torrent for it ... I would doubt it would come directly from Channel 9, but I could be wrong.
@Rituraj Jain: For the basics, I like the Microsoft Press books, especially their Step-By-Step series, and anything written by Matthew MacDonald. (I've never met him ... no financial incentive here at all.)
Actually to do this command I had to use this command line code:
csc /t:exe /out:C:\HelloWorldcs/HelloWorld.exe C:\HelloWorldcs\HelloWorld.cs
So I had to add the C:\ to the cs file! I am using windows vista
Also is it possible to compile multiple files on the command line?
Great video, very easy to follow and the way you present it makes it so much less painful than other tutorials.
For the people that seem to be having issues with not seeing the text on Bob's notepad, hit ctrl and zoom in on your webpage, the text becomes clear as day.
Thanks.
Thanks i learn lot.
@Algorithum:Yes, it is absolutely possible. Check out this link:
And see this line:
That last part *.cs tells the compiler to compile all the .cs files in the directory. There are A BUNCH of command line options ... I only demo'd the tip of the iceberg.
Hope that helps! Best wishes in 2012!
Great videos. My skills are rusty, and were never great to start with,so this is a good refresher. But I suggest:
1. In Notepad, select Format ->Font before recording a video, and make the font BIG. For something as simple as HelloWorld, a size 28 font should be readable on any video stream.
2. My own "gotcha" - spaces in directory names. If you have a space, the destination string AND the target string each need to be put inside quotes.
@Alan: Hi Alan, thank you for the suggestions. Actually? I just wrapped up a new series for Channel9 two days ago and did exactly as you suggested ... not 28pt, but 18pt w/ bold. HOPEFULLY that's good enough (!!!)
re: spaces and directory names ... absolutely, and that is why I rigged the example to be created at c:\whatever instead of c:\what ever.
I agree, that can be frustrating. Fortunately, most of us rely on Visual Studio or the Express Editions to make all that stuff trivial.
Great videos
sir this is very good fundamental videos of c# thanks alot.
The C# .NET Framework tutorial is awesome.
Microsoft partners has a very good idea to build this.
At this time I`am programming in c++ but I can learning a C#.
Thanks Microsoft!
P.S Sorry my English at the moment isn't very good.
@Mamoun Saeed: @abid ali: @Aleksander: Thank you, all.
Great videos.Thanks
Thanks Bob! I dabbled a bit with C about 20 years ago...barely got past "Hello World"...hehehe. I know I am going to enjoy going thru your lessons. I consider myself a "Utilitarian" programmer. I learn what I need to accomplish the task at hand. I have managed to do this with HTML, CSS, javascript and PHP...so the little foundation I have has already helped.
These are great videos! I have no programming background, so I was intimidated to start. But your video helped me see that it's not all that complicated and crazy. Thanks a million!
I got this c:\HelloWorld\HelloWorld.cs(5,32): error CS1010: Newline in constant
Please help...
@steve: Hey Steve, could you post your code? I'll try to help you through it. Keep in mind: the purpose of the exercise was NOT to discourage you completely, just to discourage you from trying to type all your code in Notepad and compile in the command line compiler. If this doesn't work, I recommend shrugging it off and moving forward.
public class HelloWorld
{
public static void Main()
{
system.console.WriteLine("hello world!);
system.console.ReadingLine();
}
}
Hi Steve,
Please correct the code as follows:
Hope this helps!!
@Bob :
Hi Bob, i was able to clear the errors but do know what the error exactly means so Could you please clarify what is that error "NewLine in constant" ?
thens
@thens: @Steve: Thank you, thens, for the corrected code! re: your question ... I don't know for sure, but I have a feeling the error had something to do with the command line compiler and the arguments Steve set it to. It never got to the line of code: Console.ReadlingLine() ... which would obviously fail.
@Steve: Remember -- this is an exercise in preciseness ... things must be typed in EXACTLY as I do them down to the same words and punctuation. Best wishes!!!
Thanks @thens and Bob!!! Got it!!!
@BobTabor:Thanks Bob
@Steve: Welcome steve, Happy Learning & Coding
I have tried to follow your video "Creating Your First C# Program - 02" but I could not make the screen bigger and I was not able to see clearly what appeared on the screen. I apologize for this so simple question, but I would appreciatte your help.
Creating Your First C# Program - 02
Amazing videos.Thanks
@Reynaldo Guiza: Hi, and sorry you're having a problem viewing. If you're having problems viewing, I strongly recommend that you download the files to your local computer and view in full-screen. You will need to see my code throughout the series. Hope that helps!!!
Hi, I am having a problem in cmd with the exe.
Here is a screenshot of the error.
Never mind i went through the video again and in the notepad part i did not capitalize Main in "public static void Main()"
i am create a video player in C# application but his not complete plz help me ? plz send player sorce code my E mail ID plz
thank you Sir
Thx you:)
Great Job Sir, I want to clarify my concepts of C#, please guide me and I also want to develop my Final Year Project using it,
May I do it???
Please reply me to my e-mail id. i mentioned above
The cmd line attempt failed. Here's the information:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>csc /t:exe /out:C:\HelloWorldtest\HelloWorld.exe C:\HelloWorldtest\HelloWorld.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
error CS0016: Could not write to output file 'c:\HelloWorldtest\HelloWorld.exe'
-- 'The directory name is invalid. '
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>
I would appreciate any information on how to correct this.
Thanks,
Steve
@Steve: I would make sure that the directory you are referencing is valid. Are you SURE it is spelled EXACTLY the way that you typed it into the compiler's command? ALSO don't get stuck here ... the point of this exercise was this this is really tough to get right ... and so you should be using Visual Studio because it takes care of frustrating things like this!
Best wishes!
good resources i hav ever seen....
TANKS FOR THE TUTORIAL ,I WILL SEE B/C I LIKE C#
Hi Bob,
I am excited to view your videos but I am having a very difficult time. I have tried streaming and it buffers forever. I have also tried downloading the second video twice and it took 6 or more hrs to finally get to 98% and then it failed. Can you suggest a better way to view your videos or perhaps what I'm doing wrong?
Thank you
I may have resolved my download issues. I think it is my internet provider. I was quickly able to download them from work.
Thanx Bob sir for awesome videos....
thanks a Lot SIR. Ur videos Helped me a lot!!
Thank you Bob for these Video! I love it!
Hey Bob , your style of teaching is amazing. I think words fall short of what you have delivered (Style, professionalism, attitude to teach. This is no flattery but having C# as free series is a blessing for all the folks who want to be programmers in the Microsoft realm, which usually cost $$$ outside especially in this economy.
Bob . One again you rock!
If you debugged the above message, there is a build error (haha) . Closing ")" braces missing after the word teach on line 3. Great way to teach troubleshooting.
@Neo:
I had to read that a couple of times to get the joke. Nice.
I want to study the fundamental of c#, please tell the best book that I can simply understand the language.
Hi Bob, thanks a lot. I'm so excited about this series. I just wish there was an option to download all the videos at once. For I assure you... They will be eventually. ^_^
Hey Bob, I am running Visual Studio Express 2012 for Windows 8. I am not sure how to start a new console application. I can't see any option for it when I click file>new project. Thanks for your help!
Reviewed some of the comments. Have a terrible time actually seeing what he is typing. On my ipad I can scrub but can't see what Bob is typing. On my computer, pretty new, widescreen, I also can't see what Bob is typing, even almost when its in fullscreen! Is there anywhere to go to see these videos larger. Seems like a great series....
thanks alot bob ...
can you upload series of sql server !!
i am keen to learn that topic !!
I just would like to say some words in my own language.
Allah razı olsun...
I have been trying to teach myself C-languages for a while now and these videos have been a great help to me in regards to following along. Thank you all very much for giving your knowledge to others. Five year plan; HERE I COME!
thanks Bob :)
challenging
Yes hello Bob I know you are one of those people that were abducted by the aliens and they injected you with super intelligence and now you are trying to teach us how to say “hello aliens” and I am trying hard to learn the language. I think I just need to give my programing more memory. But seriously thank you for your generosity this is helping me with my college courses
Hi Ian,
I was running into the same problem in trying to follow along. You will need to download Visual Studio Express 2012 for Windows Desktop. At which point, the Console Application template will become available under Visual C#. Hope that helps.
This is a wonderful resource, the fact that it is free and you still answer questions is astounding to me! You sir are a good man. I believe my machine just might be possessed, here is my code and the resulting error message I received:
------------
C:\Windows\Microsoft.NET\Framework\v4.0.30319>csc /t:exe /out:c:\HelloWorld\Hell
oWorld.exe c:\HelloWorld\HelloWorld.cs
Microsoft (R) Visual C# 2010 Complier version 4.0.30319.1
c:\HelloWorld\HelloWorld.cs(5,30): error CS1010: Newline in constant
C:\Windows\Microsoft.NET\Framework\v4.0.30319>
-----------
I'm running Windows 7 on an Alien Desktop. Continuing on with the tutorial, many thanks!!
Found it.... it was a missing " in the HelloWorld.cs
:)
Thank you for the great videos. I just started wish me a good luck.
Regards,
Sen
thank you sir , this is best video .
I am curious if Bob is still around. He hasn't been on for a long time now, may be since September 2012???
He thanks for the video series. I'm a total beginner and trying to learn c#. I have visual studio express 2012 for windows8 and blend. What I've discovered is that I can't make console apps in this IDE. Is there an easy way for me to translate your lessons into this environment?
What it would be nice if this new lovely video player will stay full screen when you click on another app. I have 2 monitors so trying to be multitasking and learn in the process. I hope somebody from Channel 9 will catch this. Best regards to all and yes a nice and good show. Planning to watch them all and redirect juniors to this videos. Thx.
nice! I start the videos yesterday and I'm using visual studio express 2012, all is ok with the first video...
sir i have visual studio 2012 express edition ..should i have to install the previous version for learning of c# because their isnt any console application in the newer version of visual studio
sir i have visual studio 2012 express edition ..should i have to install the previous version for learning of c# because their isnt any console application in the newer version of visual studio
ok this wasn't supposed to happen but by refreshing the page (video stopped) my question got uploaded again.
Sorry. :)
Could anybody please help me with the cmd error?
Thnx.
Marcel
Okay.....solved it as Bob tells us 1million times check your writing...and I wrote 'main' instead of "Main"...Oh boy. Feel like an 3th grader.
Hi All,
I use Visual Studio 2012 Express for web and I cannot sellect "Console Application"???
Please don't tell me that I have to install an different vs of Visual Studio...:(
Marcel
@Marcel: Yep, you'll need Visual Studio 2012 Express for Windows Desktop (not web).
Bob, mentions it above;
In that Important Update post he also provides a link to Download Visual Studio 2012 Express for Windows Desktop
@gduncan411: Heard and read it...how could I miss that one...well....let's download.
This an tutorial not for web programming is it, is it still an good basis for learning C#?
Thnx
@mducrocq68: Yes, this is a great series to learn C#.
That said, there's a number of other great that are also web focused. You can see them all here, Channel 9 Content for Beginners
This tutorial is freaking awesome! Thanks heaps Bob...Cheers
hello everybody !
i not build file.cs to file.exe using prompt commands from file.batch
i has write file.batch :
G:\test C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe out.exe test1.cs
pause
But it is not run !
please help me !
Thanks
How slow the network is!
Maybe I choose a bad time to watch this video(I Live in China so the New York time is 4:30 in the morning when I was watching this episode).
hi bob, may i ask why can not i find a release folder inside the folder bin in my documents. im using visual studio 2010 ultimate version
Nice tutorial. 5 Stars.
This lesson really taught me theand the hard way. (Notepad)
What i like about this series is that it shows a way to correct your errors and tips in coding.
This series is good today and should be good in the upcoming years.
I'm starting to love these tuts! Thanks a lot Bob and I hope I'll learn C# and get into my dream of learning to build apps within a year or two. Can't focus completely here as its my last year in High School. I'm happy I found a place where I can learn freely and with the help of an expert.
Hey, I just tried compiling that in Visual Studio 2012 but I'm getting errors, and when I hover over the red lines, it says "Identifier expected" what can I do?
Oh darn, I had a period before the parenthesis! You're right about needing an eye for detail!
Love these videos Bob, you explain clearly and love to learn from your videos.Being a fresher its very useful for me and thanks a lot in making concepts easy for me to understand.KUDOS
sir suggest me a book to learn C# and .NET
Is there a page somewhere with a transcript of this series like the one provided with the Windows Phone 8 for Absolute Beginners series? The transcript is incredibly helpful.
@Holden326: chances are you only have a debug folder as you aren't doing a release mode build.
@Marcel: check the included sample, your syntax is incorrect for your first line chances are
@ericCodes: this was something we learned to do. Wp8 was the first series we did that. Much like we learned to do the fundamentals series after the first wp7 series and realized we would have to teach if statements and the basics every time versus just jumping in. These series are big undertakings.
Hi Bob!
The console Version does not cause any Problems, but the VS 2012 Version did. If i press the compile button an error exists, that says
Fehler 1 Die Anwendungskonfigurationsdatei "App.config" ist ungültig. Das Stammelement ist nicht vorhanden.
That means the App.config is not valid. But what can i do? The App.config is in the Folder the error tells me.
Thanks, Steffen
I solved that Problem by removing the App.config from the Project. But i would be interested to know what that means.
Awesome Video! Great explanation!
@Steffen: we build the videos under 2010, I'd have to dedicate some time to seeing what is up. Can you describe a bit more about how built out your project? Was it file->new from VS 2012/2013?
Does anyone else feel like Steve Martin is teaching how to write in C#?
Excellent..
Bob I can't tell you how pleased I am to have stumbled across this. There's a wonderful clarity in your work.
Bob.. I am using W8 with VStudio 2013.. Following the video was not able to find the compiler. There is no Framework.NET folder or Framewor folder. Has this been move to another Location?
I added the path of the C# compiler under path in environment variables.
But still csc is not being recognized in other directories. Why??
@jecalderon: use the "windows desktop" version of express for the fundamental series. We recorded this series before that shift came out.
Bob...fantastics videos and enjoying the clear tutorials. I've followed the instructions to the letter but at the command prompt I get an error after adding the cdc /t:exe /out:c:\HelloWorld\HelloWorld.exe c:\HelloWorld.cs
the error read
C:\HelloWorld\HelloWorld.cs(5,19): error CS0117: 'System.Console' does not contain a definition for 'writeline'
i'm using windows 8.1 incase that should make a difference?
error cs0103 when compiling
code:
public class HelloWorld
{
public static void Main()
{
system.console.WriteLine("Hello World!");
system.console.ReadLine();
}
}
@BobTabor finally i got good teacher thank you BobTabor .My i know which keyboard your using ?
@ginksi: c# is case sensitive. System and Console both need to be cased properly.
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-Beginners/Creating-Your-First-C-Sharp-Program?format=progressive | CC-MAIN-2014-41 | refinedweb | 3,852 | 76.01 |
Windows Mixed Reality enables a user to see holograms as if they are right around you, in your physical or digital world. At its core, both HoloLens and the Desktop PCs you attach headset accessories to are Windows 10 devices; this means that you're able to run almost all of the Universal Windows Platform (UWP) apps in the Store as 2D apps.
Microsoft has been rapidly evolving the Windows platform over the past few years. That means many developers have different starting points even if they deliver an app to the Windows 10 Store today on Desktop, Mobile, or Xbox. This guide will focus on helping you get started when you have an existing app that you are trying to bring to mixed reality headsets, no matter where you're starting from.
To build an app for Windows Mixed Reality headsets, you must target the Universal Windows Platform - the developer platform introduced in Windows 10. That means to bring your app to HoloLens, you must first ensure it targets the Windows 10 Universal Windows Platform (UWP). We'll talk about ways that you can restrict your app specifically to the HoloLens device using the Windows.Holographic device family below. Here are all the potential starting points you may have with your app today:
Congratulations! Your app is now using the Windows 10 Universal Windows Platform (UWP). Your app is now capable of running on todays Windows devices like Desktop, Mobile, Xbox, and HoloLens as well as future Windows devices.
Now let's jump into your AppX manifest to ensure your Windows 10 UWP app can run on HoloLens.
If your app already runs on Desktop PCs, you're set to have your app run as a 2D slate in mixed reality. To target HoloLens as well, you must ensure you are targeting the "Windows.Universal" device family.
<Dependencies> <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.10240.0" MaxVersionTested="10.0.10586.0" /> </Dependencies>
If you do not use Visual Studio for your development environment, you can open AppXManifest.xml in the text editor of your choice to ensure you're targeting the Windows.Universal TargetDeviceFamily.
Now that your UWP app targets "Windows.Universal", let's build your app and run it in the HoloLens Emulator.
At this point, one of two things can happen:
HoloLens Development Edition is a new device target of the Windows 10 operating system, so there are Universal Windows Platform APIs that are still undergoing testing and development. We've experienced our own challenges bringing Microsoft UWP apps to HoloLens.
Here are some high level areas that we've found to be a problem:
To get to the bottom of what's causing your UWP app not to start on HoloLens, you'll have to debug.
These steps will walk you through debugging your UWP app using the Visual Studio debugger.
As mentioned above, there are known issues with APIs under testing and development for the HoloLens Development Edition. If you find that your app uses one of the APIs in the namespaces listed as having potential problems, use the Windows Feedback tool to send feedback to Microsoft.
How to open the Windows Feedback tool
We are continually fixing platform bugs in the APIs of UWP. For APIs that are failing by design - because they are not supported on HoloLens - here are the patterns that you can expect in your app and design around:
Error codes
Collections
Asynchronous functions
Events
Now that your UWP app is running on Desktop headsets and/or HoloLens as a 2D hologram, next we'll make sure it looks beautiful. Here are some things to consider:
HoloLens uses advanced depth sensors to see the world and see users. This enables advanced gestures like bloom and air-tap. Powerful microphones also enable voice experiences. With Desktop headsets, users can use motion controllers to point at apps and take action. Windows takes care of all of this complexity for UWP apps, translating your gaze, gestures, voice and motion controller input to pointer events that abstract away the input mechanism. For example, a user may have done an air-tap with their hand or pulled the Select trigger on a motion controller, but 2D applications don't need to know where the input came from - they just see a 2D touch press, as if on a touchscreen.
Here are the high level concepts/scenarios you should understand for input when bringing your UWP app to HoloLens:
Voice input is a critical part of the mixed reality experience. We've enabled all of the speech APIs that are in Windows 10 powering Cortana when using a headset.
Once your app is up and running, package your app to submit it to the Universal Windows Store. | https://developer.microsoft.com/en-us/windows/mixed-reality/building_2d_apps | CC-MAIN-2017-30 | refinedweb | 791 | 59.74 |
whats wrong in my code ?
def is_int(x): if type(x)==int: return True else: return False
whats wrong in my code ?
def is_int(x): if type(x)==int: return True else: return False
Hi @puneetsinha ,
Because the code that you posted is not formatted, it is difficult for other users to read and debug it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. Alternatively, you can place three backquotes on the line before the code and three backquotes on the line after the code. This will enable us to see important details, such as the indentation and underscores. If you use the backquotes, your code will be color-coded, making it especially easy to read.
This is not the correct test to use for this exercise ...
if type(x)==int:
In fact, the instructions state ...
... for this lesson, you can't just test the input to see if it's of type int.
For this exercise, any number, including a
float, that has the value of a whole number qualifies for a return of
True. So, a number such as
8.0 would conform to that criterion.
The correct test to apply is one that determines if
x is equivalent in value to
int(x).
Your if statement should be -i think-
if x == int(x):
I might be mistaken, but that how i got it to accept.
You can also just use a bit of clever mathematics to determine if it is an integer or not.
My solution was to run x through:
x%1 == 0
Anything with a remainder of 0 would be an integer.
I came up with this. My theory was to mod x and if it returns 0 or 1 without any decimals then it is an integer. If it returns .14 or 1.14 then it is a float. I tested it with several inputs and it worked.
def is_int(x): y = x % 2 if y == 0 or y == 1: return True else: return False
A method is_integer() will return true for 7.0 and false for 7.5, that was how I did mine. You can try the method too. Cheers
You also can include a 'elif' to check negative numbers. There is a post that someone is working with the same alternative like you:
the post asked the result of the difference between a number and that same number which makes it confusing.
defining a function which produces an integer by dividing x/x as an instance of our function......is that right?
for me this worked perfetcly
def is_int(x):
if x - int(x) == 0:
return True
else:
return False
Hi everybody! That's my sokution for this task:
def is_int(x): if float(x)-int(x) == 0: return True else: return Fals
Here I was looking for a any decimal numbers, if they are
alternative way:
from math import floor
def in_int(x):
x += .0
y = floor(x)
if x == y:
return True
else:
return False
--Jeffrey A.
Another way
def is_int(x):
if x == round(x):
return True
else:
return False
print (is_int(7.0))
Another way, although I seem to have a very different approach. Maybe because learning this ■■■■ is turning my brain into applesauce!
def is_int(x):
if abs(x) - abs(round(x)) > 0:
return False
else:
return True | https://discuss.codecademy.com/t/3-is-int/18562 | CC-MAIN-2018-34 | refinedweb | 573 | 74.08 |
Rob Spoor wrote:Class Whatever needs to be public, which means it has to move into a file of its own. I tried that and it worked.
Rob Spoor wrote:I think that what Marcus means is that why the class needs to be public.
What I have experienced is that reflection has trouble finding non-public classes in general. This only applies to the classes themselves though. If a public class is nested in a non-public class (and is static) then it can be loaded through reflection. I've done this myself just quite recently. I was using some tool that automatically generated the public class, and I couldn't add a nested class to it. I could add code outside the class. What I did was create one non-public class with a public classes nested in it, and that worked just fine. | http://www.coderanch.com/t/580036/GUI/java/EventHandler-ActionListener-usage | CC-MAIN-2014-52 | refinedweb | 146 | 74.29 |
Section 11.4
Networking
As far as a program is concerned, these basic networking classes, and shows how they relate to input and output streams.
11.4.1 URLs and URLConnections."
An object belonging to the URL class represents such an address. Once you have a URL object, you can use it to open a URLConnection to the resource at that address.
public.(). The string returned by getContentType() is in a format called a mime type. Mime types include "text/plain", "text/html", "image/jpeg", "image/gif", and many others. All mime types contain two parts: a general type, such as "text" or "image", and a more specific type within that general category, such as "html" or "gif". If you are only interested in text data, for example, you can check whether the string returned by getContentType() starts with "text". (Mime types were first introduced to describe the content of email messages. The name stands for "Multipurpose Internet Mail Extensions." They are now used almost universally to specify the type of information in a file or other resource.)()
A complete program that uses this subroutine can be found in the file ReadURL.java. When using the program, note that you have to specify a complete url, including the "http://" at the beginning. Here is an applet that does much the same thing. The applet lets you enter a URL, which can be either a complete URL or a relative URL. A relative URL will be interpreted relative to the document base of the applet. Error messages or text loaded from the URL will be displayed in the text area of the applet. (The amount of text is limited to 10000 characters.) When the applet starts up, it is configured to load the file ReadURL.java from this book's source code directory; just click the "Load" button:
You can also try to use this applet to look at the HTML source code for this very page. Just type s4.html into the input box at the bottom of the applet and then click on the Load button. You might want to experiment with other urls to see. To protect you from malicious applets, an applet is allowed to open network connections only back to the computer from which it came.) The source code for the applet is in the file ReadURLApplet.java.
11.4.2, sending data over uses. To do this, it is necessary to use threads (Section 8.5). We'll look at how it works in the next section..).
A computer can have several IP addresses, and can have both IPv4 and IPv6 addresses. Usually, one of these is the loopback address, which can be used when a program wants to communicate with another program on the same computer. The loopback address has IPv4 address 127.0.0.1 and can also, in general, be referred to using the domain name localhost. In addition, there can be one or more IP addresses associated with physical network connections. Your computer probably has some utility for displaying your computer's IP addresses. I have written a small Java program, ShowMyNetwork.java, that does the same thing. When I run ShowMyNetwork on my computer, the output is:
en1 : /192.168.1.47 /fe80:0:0:0:211:24ff:fe9c:5271%5 lo0 : /127.0.0.1 /fe80:0:0:0:0:0:0:1%1 /0:0:0:0:0:0:0:1%0
The first thing on each line is a network interface name, which is really meaningful only to the computer's operating system. The output also contains the IP addresses for that interface. In this example, lo0 refers to the loopback address, which has IPv4 address 127.0.0.1 as usual. The most important number here is 192.168.1.47, which is the IPv4 address that can be used for communication over the network..)
11.4.3 Sockets
To implement TCP/IP connections, the java.net package provides two classes, ServerSocket and Socket. A ServerSocket represents a listening socket that waits for connection requests from clients. A Socket represents one endpoint of an actual network connection. A Socket.. Keeping all this in mind,(). However, what I've covered here should give you the basic ideas of network programming, and it is enough to write some simple network applications. Let's look at a few working examples of client/server programming.
11.4.4 A Trivial Client/Server
The first example consists of two programs. The source code files for the programs are DateClient.java and DateServer.java. One is a simple network argument For example, if the server is running on a computer named math.hws.edu, then you would typically run the client with the command "java DateClient math.hws.edu". Here is the complete client program:
import java.net.*; import java.io.*; /** * This program opens a connection to a computer specified * as the first command-line argument. The connection is made to * the port specified by LISTENING_PORT. The program reads one * line of text from the connection and then closes the * connection. It displays the text that it read on * standard output. This program is meant to be used with * the server program, DateServer, which sends the current * date and time on the computer where the server is running. */ public class DateClient { public static final int LISTENING_PORT = 32007; public static void main(String[] args) { String hostName; // Name of the server computer to connect to. Socket connection; // A socket for communicating with server. BufferedReader incoming; // For reading data from the connection. /* Get computer name from command line. */ if (args.length > 0) hostName = args[0]; else { // No computer name was given. Print a message and exit. System.out.println("Usage: java DateClient <server_host_name>"); return; } /* Make the connection, then read and display a line of text. */ try { connection = new Socket( hostName, LISTENING_PORT ); incoming = new BufferedReader( new InputStreamReader(connection.getInputStream()) ); String lineFromServer = incoming.readLine(); if (lineFromServer == null) { // A null from incoming.readLine() indicates that // end-of-stream was encountered. throw new IOException("Connection was opened, " + "but server did not send any data."); } System.out.println(); System.out.println(lineFromServer); System.out.println(); incoming.close(); } catch (Exception e) { System.out.println("Error: " + e); } } // end main() } //end class DateClient
Note that all the communication with the server is done in a try..catch statement. This will catch the IOExceptions that can be generated when the connection is opened or closed and when data is read from the input stream. The connection's input stream is wrapped in a BufferedReader, which has a readLine() method that makes it easy to read one line of text. (See Subsection 11.1.4.) domain name localhost and the IP number 127.0.0.1 as referring to "this computer." This means that the command "java DateClient localhost" will tell the DateClient program to connect to a server running on the same computer. If that command doesn't work, try "java DateClient 127.0.0.1".
The server program that corresponds to the DateClient client program is called DateServer. The DateServer program creates a ServerSocket to listen for connection requests on port 32007. After the listening socket is created, the server will enter an infinite loop in which it accepts and processes connections. This will continue until the program is killed in some way -- for example by typing a CONTROL-C in the command window where the server is running. When a connection is received from a client, the server calls a subroutine to handle the connection. In the subroutine, any Exception that occurs is caught, so that it will not crash the server. Just because a connection to one client has failed for some reason, it does not mean that the server should be shut down; the error might have been the fault of the client. The connection-handling subroutine creates a PrintWriter:). Note that this server processes each connection * as it is received, rather than creating a separate thread * to process the connection. */ public class DateServer { public); System.out.println("Listening on port " + LISTENING_PORT); while (true) { // Accept next connection request and handle it. connection = listener.accept(); sendDate(connection); } } catch (Exception e) { System.out.println("Sorry, the server has shut down."); System.out.println("Error: " + e); return; } } // end main() /** * The parameter, client, is a socket that is already connected to another * program. Get an output stream for the connection, send the current time, * and close the connection. */ private static void sendDate(Socket client) {erver
When you run DateServer in a command-line interface, it will sit and wait for connection requests and report them as they are received. To make the DateServererver generally.
11.4.5 A Simple Network Chat
In the DateServer. The client and server programs can be found in the files CLChatClient.java and CLChatServer.java. (The name "CLChat" stands for "command-line chat.") Here is the source code for the server:
import java.net.*; import java.io.*; /** * This program is one end of a simple command-line interface chat program. * It acts as a server which waits for a connection from the CLChatClient * program. The port on which the server listens can be specified as a * command-line argument. If it is not, then the port specified by the * constant DEFAULT_PORT is used. Note that if a port number of zero is * specified, then the server will listen on any available port. * This program only supports one connection. As soon as a connection is * opened, the listening socket is closed down. The two ends of the connection * each send a HANDSHAKE string to the other, so that both ends can verify * that the program on the other end is of the right type. Then the connected * programs alternate sending messages to each other. The client always sends * the first message. The user on either end can close the connection by * entering the string "quit" when prompted for a message. Note that the first * character of any string sent over the connection must be 0 or 1; this * character is interpreted as a command. */ public class CLChatServer { /** * Port to listen on, if none is specified on the command line. */ static final int DEFAULT_PORT = 1728; /** * Handshake string. Each end of the connection sends this string to the * other just after the connection is opened. This is done to confirm that * the program on the other side of the connection is a CLChat program. */ static final String HANDSHAKE = "CLChat"; /** * This character is prepended to every message that is sent. */ static final char MESSAGE = '0'; /** * This character is sent to the connected program when the user quits. */ static final char CLOSE = '1'; public static void main(String[] args) { int port; // The port on which the server listens. ServerSocket listener; // Listens for a connection request. Socket connection; // For communication with the client. BufferedReader incoming; // Stream for receiving data from client. PrintWriter outgoing; // Stream for sending data to client. String messageOut; // A message to be sent to the client. String messageIn; // A message received from the client. BufferedReader userInput; // A wrapper for System.in, for reading // lines of input from the user. /*) { System.out.println("Illegal port number, " + args[0]); return; } } /* Wait for a connection request. When it arrives, close down the listener. Create streams for communication and exchange the handshake. */ try { listener = new ServerSocket(port); System.out.println("Listening on port " + listener.getLocalPort()); connection = listener.accept(); listener.close(); incoming = new BufferedReader( new InputStreamReader(connection.getInputStream()) ); outgoing = new PrintWriter(connection.getOutputStream()); outgoing.println(HANDSHAKE); // Send handshake to client. outgoing.flush(); messageIn = incoming.readLine(); // Receive handshake from client. if (! HANDSHAKE.equals(messageIn) ) { throw new Exception("Connected program is not a CLChat!"); } System.out.println("Connected. Waiting for the first message."); } catch (Exception e) { System.out.println("An error occurred while opening connection."); System.out.println(e.toString()); return; } /* Exchange messages with the other end of the connection until one side or the other closes the connection. This server program waits for the first message from the client. After that, messages alternate strictly back and forth. */ try { userInput = new BufferedReader(new InputStreamReader(System.in)); System.out.println("NOTE: Enter 'quit' to end the program.\n"); while (true) { System.out.println("WAITING..."); messageIn = incoming.readLine(); if (messageIn.length() > 0) { // The first character of the message is a command. If // the command is CLOSE, then the connection is closed. // Otherwise, remove the command character from the // message and proceed. if (messageIn.charAt(0) == CLOSE) { System.out.println("Connection closed at other end."); connection.close(); break; } messageIn = messageIn.substring(1); } System.out.println("RECEIVED: " + messageIn); System.out.print("SEND: "); messageOut = userInput.readLine(); if (messageOut.equalsIgnoreCase("quit")) { // User wants to quit. Inform the other side // of the connection, then close the connection. outgoing.println(CLOSE); outgoing.flush(); // Make sure the data is sent! connection.close(); System.out.println("Connection closed."); break; } outgoing.println(MESSAGE + messageOut); outgoing.flush(); // Make sure the data is sent! if (outgoing.checkError()) { throw new IOException("Error occurred while transmitting message."); } } } catch (Exception e) { System.out.println("Sorry, an error has occurred. Connection lost."); System.out.println("Error: " + e); System.exit(1); } } // end main() } //end class CLChatServer
This program is a little more robust than DateServer. For one thing, it uses a handshake to make sure that a client who is trying to connect is really a CLChatClient program. A handshake is simply information sent between client and server as part of setting up the connection, before any actual data is sent. In this case, each side of the connection sends a string to the other side to identify itself. The handshake is part of the protocol that I made up for communication between CLChatClient and CLChatServer. A protocol is a detailed specification of what data and messages can be exchanged over a connection, how they must be represented, and what order they can be sent in. When you design a client/server application, the design of the protocol is an important consideration. Another aspect of the CLChat protocol is that after the handshake, every line of text that is sent over the connection begins with a character that acts as a command. If the character is 0, the rest of the line is a message from one user to the other. If the character is 1, localhost" to connect to the server that is running on the same machine. | http://math.hws.edu/javanotes/c11/s4.html | crawl-001 | refinedweb | 2,382 | 59.4 |
To obtain these tools:
Install the Xcode Tools from developer.apple.com.
If you are running a version of
Xcode Tools other than 4.0, view the documentation locally:
In Xcode.
SHUTDOWN(2) BSD System Calls Manual SHUTDOWN(2)
NAME
shutdown -- shut down part of a full-duplex connection
SYNOPSIS
#include <sys/socket.h>
int
shutdown(int socket, int how);
DESCRIPTION.
RETURN VALUES
The shutdown() function returns the value 0 if successful; otherwise the value -1 is returned and the
global variable errno is set to indicate the error.
ERRORS
The call succeeds unless:
[EBADF] Socket is not a valid descriptor.
[EINVAL] The how argument is invalid.
[ENOTCONN] The specified socket is not connected.
[ENOTSOCK] Socket is a file, not a socket.
SEE ALSO
connect(2), socket(2)
HISTORY
The shutdown() function call appeared in 4.2BSD.
4.2 Berkeley Distribution June 4, 1993 4.2 Berkeley Distribution
The way to report a problem with this manual page depends on the type of problem: | http://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/shutdown.2.html | CC-MAIN-2013-20 | refinedweb | 164 | 59.8 |
[Today’s post comes to us courtesy of Jim Martin]
Can you have additional domain controllers (Replica DCs) in an SBS domain?
The are several myths about SBS (see “The Top Ten (Plus One) Myths About Windows Small Business Server 2003” or the webcast “Debunking the Top 10 Myths of Small Business Server in Larger Environments”). But the most common one seems to be the misconception that you cannot have other domain controllers in a domain that has a Small Business Server. Let’s set the record straight right now. You can! In fact, in many cases it can be very beneficial.
The myth about this not being allowed probably originated from one or more of the following, which are themselves true. However this somehow got misconstrued to mean that you can’t have additional DCs:
- You cannot have more than one Small Business Server in the same domain. This is most likely the main cause of confusion on the issue. You can have other DCs but none of them can be another Small Business Server.
- You must take special steps to promote a Small Business Server into an existing Active Directory domain. I’ll go into more details on this later, but essentially because of the way that SBS is promoted as a DC in a new domain during the SBS integrated setup, it may not be immediately apparent how to successfully promote it into an existing domain. And with SBS 2000 you could not use the SBS media to do so, but rather had to use media for Standard Windows 2000 Server. Also, it is not supported to demote the Small Business Server after it is installed then promote it into another, existing domain.
- The Small Business Server must own all of the forest and domain FSMO roles. Obviously only one DC in the forest can have this requirement.
- The SBS domain must be the root domain of the forest and trusts or parent/child domains are not supported.
Note: For the sake of clarity, a “replica domain controller” is simply an additional domain controller. In an Active Directory domain there are no longer PDCs or BDCs and all DCs are considered peers. When another DC is promoted into an existing domain it is typically referred to as a replica DC. We have seen the acronym “ADC” used to refer to an “Additional Domain Controller”, but we will not use that here in to avoid confusion it with “Active Directory Connector”.
Check out the following links for more information about the top 10 myths about Small Business Server 2003:
What are the benefits of having replica DCs in an SBS domain, or in any domain for that matter?
- Redundancy
- If the Small Business Server cannot be contacted but another DC is available users can still authenticate.
- If DNS is also installed and the zone for the internal domain is being replicated to all DCs/DNS servers, redundancy will be provided for local and public DNS namespace queries.
- Disaster recovery
- It is not necessary to rebuild your entire Active Directory domain if the Small Business Server crashes and you don’t have a good system state backup.
- Improved user experience
- If additional DCs are placed at remote sites and also made Global Catalog Servers, remote users can logon more quickly and reliably, and locate objects in the domain more quickly.
Before we look at how to deploy it, let’s review the real restrictions associated with deploying SBS.
- There can be only one Small Business Server in the domain. (You can actually have more than one Small Business Server in the same domain for up to 7 days before one or both of them start shutting down every hour. This can be useful in some migration scenarios. However be sure to finish the migration and then demote and remove one of them from the network before they start shutting down!)
- The Small Business Server must be installed into the root domain of a single-domain forest.
- SBS does not support trusts with other domains or forests, including both implicit and explicit trusts.
- SBS does not support parent or child domains.
- The Small Business Server must own all 5 of the forest and domain FSMO roles.
- The Small Business Server must be a global catalog server.
- SBS supports up to 75 user or device CALs.
- The components that come with SBS such as Exchange, SQL, and ISA can only be installed on the server that is running SBS.
-.
The following FAQs answer these and other questions related to SBS licensing and installation:
Deployment
Analysis and Planning
Planning is always beneficial, even in small environments. And sometimes you can gain some insight about your network just by drawing it out on paper.
Analyze your existing physical network
Create a diagram of your existing physical network including:
- Sites – Keep in mind the definition of a site is a group of well-connected computers. Well-connected typically means they are connected to each other at LAN speed (10 mbps or greater) and that the connection is relatively consistent and reliable. This usually means they are on the same physical LAN (but not necessarily the same subnet). Physical sites are not related to the logical structure of your AD domain (Containers, OUs, etc.). If you have 2 sets of subnets connected via a VPN over the Internet, you should consider them to be different sites.
- Subnets – there could be more than one at a site
- Domain controllers – which of these are global catalog servers?; which ones are also DNS servers?
- Member servers – Application servers, Exchange Servers, file and print servers, etc.
- Workstations
- Printers
Analyze the number and distribution of users
In particular note roaming patterns and which sites they typically logon from.
Using all of the information above you should then be able to determine the number and placement of domain controllers, global catalog servers, and DNS servers.
Backup every existing DC before making any changes
Perform a full backup of every existing DC, including system state, before making any changes to the network or the domain. If a configuration change or DC promotion fails or causes problems, you might have to rebuild a server or your domain if you do not have good backups.
Check the health of the existing network and Active Directory
Verify the DNS configuration
First decide on one DNS server in your domain to be the “master”. In reality they are all peers but you should choose one to be configured as the “Preferred DNS Server” for all domain controllers in the domain. This is very important to make sure that all host (A) and service (SRV) records are dynamically updated and replicated universally. Registering the domain controller DNS records is pivotal to AD replication working properly. You want to avoid inadvertently creating a situation known as “DNS islands” in which different DNS servers might have their own copies of the internal zones which differ from the copies on other DNS servers.
Next, verify the properties of the network connection on each DC. In each case the “Preferred DNS Server” should point to the “master” DNS server and the “Alternate DNS Server” should point to itself.
In the advanced DNS properties make sure the following are selected:
- Append primary and connection specific DNS suffixes
- Append parent suffixes of the primary DNS suffix
- Register this connection’s addresses in DNS
If you make changes to these settings on any machine, re-register the DNS host and service records for that machine with the following commands:
- Ipconfig /flushdns
- Ipconfig /registerdns
- Net stop netlogon
- Net start netlogon
Verify the health of the network
One of the best ways to do this is to run NETDIAG from the Windows Support Tools or Resource Kit. I would run it once on each DC without any parameters just to see if there are any errors at a glance, then if there are some or if you want more detail, run it with the “/v” switch. For more options run it with the “/?” switch.
If it fails any test, investigate and resolve that issue before proceeding.
Verify the health of the domain
From the same set of tools as NETDIAG run DCDIAG. Again, run it once without parameters just to see a summary of issues and run it with “/v” to get more details. Use “/?” to see more options. Note that you can specify a domain controller name with the “/s” switch so you can run it for each machine from the same one provided there are no network or others issues preventing you from doing so.
One error you can safely ignore when you run it on SBS will be:
Starting test: Services
IsmServ Service is stopped on [SBSERVER]
……………………. SBSERVER failed test Services
Fix any other errors before proceeding.
Verify the health of replication
DCDIAG will give you some indication if there are replication issues but you should use REPADMIN or REPLMON to thoroughly verify and analyze the replication status of every existing DC. Both of these can be found in the Windows Support Tools.
REPADMIN is a command line tool. In short, you can run “repadmin /showreps” on each DC to get the date, time, and status of the last replication attempt for each AD partition. Use the “/?” switch for more options.
REPLMON is a GUI that makes it easier to visualize the replication status.
Fix any errors before proceeding.
Domain controller placement
Having more than one DC at the same site is usually a decision based on redundancy, disaster recovery, and the volume of users at that site. I recommend that if you only have one site you should have at least 2 DCs at that site regardless of the volume of users. The costs associated with an additional DC can certainly be a factor but, although I won’t go into details about it here, keep in mind that virtualization technologies such as Virtual Server and Virtual PC provide a variety of low-cost options.
For the best user experience each site should have at least one DC. But several factors can dictate how practical that might be such as:
- The number of users at the site
- The reliability of the connection to other sites
- How well the users at the site can tolerate a temporary outage or slow logon, access, or search responses
- The hardware, software, and maintenance costs of an additional DC vs. the benefits
When a user logs on to the domain, in order to optimize their experience, the logon process attempts to locate a DC which is in the same site as the client machine from which the user is logging on. The site is determined based on the IP subnet of the client machine. If one cannot be found in the same site, a DC in the next closest site is used. So as long as the site’s connection to other sites is reliable, a DC is likely to be located to authenticate the user, although the user’s experience may not be optimal. Another thing to keep in mind is that if a DC cannot be located, the user will be logged on with cached credentials if the user has previously logged on to the domain from that machine.
The following article describes the process of locating a domain controller during the logon process:
247811 – How Domain Controllers Are Located in Windows
Another way that connection speed and reliability play a part in determining the proper location for domain controllers has to do with replication. This is a double-edged sword. That’s because if you have a large number of users at a site and perhaps a connection with limited bandwidth, the volume of authentication traffic might be a significant justification for locating a DC at the site. On the other hand, all DCs must replicate with each other to be healthy and up-to-date and replication traffic uses bandwidth as well. Usually the best practice in that situation, is to install the DC at the site if the user volume justifies it and configure replication to occur less frequently or after-hours (this is by default if the DCs are placed in the correct sites in AD Sites and Services). High-priority AD updates such as password changes and user account lockout updates will be replicated as soon as possible regardless of the regular replication schedule. And only objects or attributes that have changed are replicated which uses less bandwidth than if the entire AD partition or object had to be replicated.
Global Catalog Server placement
In a single-domain AD forest, as in the case of SBS (see SBS restrictions earlier in this post), a global catalog server is not needed during the logon process because any DC in the domain essentially has a complete copy of every object in the forest. This is regardless of whether universal groups are available or whether a UPN (Universal Principal Name) is used to logon to the domain. See sections “User Logon” and “Logon Process in a Single-Domain Forest” in the TechNet article “How the Global Catalog Works”:
However, certain applications such as Exchange and Outlook require a Global Catalog to locate objects in the forest, regardless of the AD structure. In the case of Exchange and Outlook it is used to populate address lists and resolve names. The white paper “Understanding and Troubleshooting Directory Access” has more detailed information about how Active Directory and Global Catalog location and access are handled by Exchange and Outlook.
So for SBS domains what’s the best practice for global catalog placement? If you have already made the case for a DC at a site, then you should also make it a GC. Since this is a single-domain forest any additional replication traffic resulting from making the DC a GC will be negligible. Thus your users at that site can enjoy a better experience for virtually no additional cost in bandwidth or overhead. See “How to create or move a global catalog in Windows Server 2003, Windows 2000, or Small Business Server 2000”.
DNS Server placement
A DNS server that hosts a copy of the zones for the internal domain provides the following services for the domain:
- Resolves internal Active Directory names
- Performs recursive queries on behalf of clients to resolve public names
- Caches both positive and negative DNS query results to improve performance
- Using dynamic DNS it keeps the internal zone up-to-date by registering and maintaining the host (A) and service (SRV) records for machines and services in the internal domain.
By default SBS hosts AD-integrated copies of the zones for the internal domain (contoso.local, _msdcs.contoso.local, and the reverse lookup zones). Since the internal DNS namespace and Active Directory are so closely linked, being able to locate, query, and update a DNS server is integral to maintaining and utilizing a healthy AD.
As with any other AD partition, the DNS application partition (the hosted zones) must replicate with other DNS servers. However, once the domain has been created and the initial member servers and workstations have been joined to the domain, the internal zone will likely be relatively static, and will only be updated when new machines are joined to the domain and when DHCP clients obtain new leases. And as with other AD partitions, only changes to the DNS partition will be replicated between DNS servers that host the internal zones. So, replication traffic associated with having a DNS server at another site is likely to be negligible during normal operations.
So the best practice for DNS server placement will in most cases be the same as that for GCs – if you have already decided on another DC, then install DNS on it and configure the hosted zones to replicate to it. Although there are other options such as making a server at a site only a DNS server or only a DC/GC, or dedicating a separate server to each, there is most likely very little benefit to doing so. In a domain the size of a typical SBS domain, the overhead of performing each of these functions probably would not be significant enough to justify the cost of having a dedicated server for just one or each of them. So again, once you have made the decision to dedicate a machine at a site to one of these functions, you should go ahead and incorporate all 3 functions on the same machine.
Check firewall configuration
Make sure that no firewalls between the new DC and its nearest replication partner will block traffic required for replication, DNS, RPC, and other required traffic. See the following article for more details on what protocols and ports need to be allowed for Active Directory:
832017 Service overview and network port requirements for the Windows Server system;EN-US;832017
Usually if you have a VPN configured between the new DC and its replication partner, the necessary ports will be open.
Configure Sites and Subnets
Next, if you will have more than one site you will need to configure the additional sites in AD Sites and Services.
If you will only have one site then you need only confirm that you have the single default site “Default-First-Site-Name” and that all existing DCs are already in that site. If you require additional sites refer to this article for more details:
Step-by-Step Guide to Active Directory Sites and Services
In a nutshell these are the steps:
- Create new sites as needed
- Create new subnets and assign them to a the appropriate sites
- Define a bridgehead server at each existing site if there is more than one DC already at that site
- Run “Check Replication Topology” and verify the topology looks correct
Any new DCs will be moved to the appropriate sites automatically when they are promoted as long as the sites and subnets are defined correctly beforehand in AD Sites and Services.
The DCPROMO Process
Promoting a new DC into an existing SBS domain
This process is identical to the process used for promoting a replica DC into any AD domain.
Obtain a full backup of the new server, including system state, before making any changes.
If something goes wrong and you do not have a backup, you might be forced to rebuild the server from scratch.
Install and Configure DNS on the new server
It is vital that you install and configure DNS properly. Doing this correctly up front could save you a LOT of problems down the road.
You can install DNS by adding the role from the “Manage Your Server” program or from Add/Remove Programs, Add/Remove Windows Components.
Next, configure the properties of the network connection.
When verifying your current DNS configuration earlier you should have already decided on one DNS server in your domain to be the “master”. The “Preferred DNS Server” should point to the “master” DNS server and the “Alternate DNS Server” points to the new server itself.
In the advanced DNS properties make sure the following are selected:
- Append primary and connection specific DNS suffixes
- Append parent suffixes of the primary DNS suffix
- Register this connection’s addresses in DNS
Note: Do not manually create any zones. The internal zones will replicate from an existing DC/DNS Server after promotion.
Run DCPROMO
Just run the command DCPROMO. You do not need to join the server to the domain as a member server first.
If you encounter any errors during this process, stop and resolve them before continuing.
When you get the option of creating a new domain or joining an existing one select “Additional domain controller for an existing domain”.
The next screen prompts you for the credentials of a user with the right to DCPROMO the machine to the domain. I recommend just using the built-in Administrator account for the existing domain. The domain name can be either the FQDN or the NETBIOS name.
Next you are prompted for the name of the domain you want to join. You can specify the FQDN or browse to the domain on the network using the browse button. Browsing is a good way to verify that the domain can actually be found on the network.
Next you are prompted for the location of the AD database and log files. I recommend accepting the defaults unless you are short on free space on the C: drive or have other reasons for locating them elsewhere.
Then you will be asked for the location of the System Volume (SYSVOL). Again, I recommend the default unless you have good reasons to choose otherwise.
You will next be prompted for the DS Restore Mode password. I recommend choosing the same one that you use on the other DCs or at least one you can remember perhaps much later on (perhaps months or years). In SBS the DSRM password is automatically synchronized with the domain administrator’s password, but this is not automatic in non-SBS Windows Servers, although there are ways you can do it manually:
322672 How To Reset the Directory Services Restore Mode Administrator Account Password in Windows Server 2003;EN-US;322672
Finally you will get a summary of the options you chose. This is your last chance to go back and change any of them.
When the promotion process is complete the server will require a restart.
If you have configured everything correctly, the new DC should continue replicating AD from other DCs and GCs after the restart. Open AD Sites and Services on a pre-existing DC and verify the new DC is in the correct site. If it is not, verify that the sites and subnets have been defined correctly. If those are correct, don’t take any corrective action at first. Give the servers a chance to finish replicating and check again later.
Even though the SBS domain might not be very large, it still takes a while for replication to get completely caught up. If you start running health checks too early, you are likely to see errors and spend a lot of time troubleshooting issues that will go away once replication has had a chance to finish completely. This is the perfect opportunity to go have a meal, take a break, etc. You have worked really hard to get to this point and you deserve a break.
After you enjoy a meal and a siesta it’s time to finish up.
Open AD Sites and Services on a pre-existing DC again and verify the new DC is in the correct site. Also check to see if the KCC has detected the appropriate inbound replication partners for each server. Try forcing replication between the new DC and a pre-existing DC just to get an initial indication that everything is configured and talking properly. If you force replication and get an error, you need to address that issue before proceeding. Check the Directory Services event log for ant applicable errors.
If replication has completed and the new DC is still not in the correct site you can manually move it as simply as right-clicking the new server in AD Sites and Services and choosing “Move”, then selecting the desired site.
Promote the new DC to a Global Catalog Server
This a simple process and is documented:
313994 How to create or move a global catalog in Windows Server 2003, Windows 2000, or Small Business Server 2000;EN-US;313994
…but just go to the properties of the NTDS Settings object under the server in AD Sites and Services and check the box “Global Catalog”. After doing so, wait for event 1119 to appear in the Directory Services event log which indicates the DC is now acting as a GC before demoting or rebooting another DC or GC. Then force replication to other DCs from this one to ensure that change has been replicated.
Promoting a new Small Business Server as an additional DC in an existing domain
This process is well-defined in knowledge base article “884453 – How to install Small Business Server 2003 in an existing Active Directory domain”. I won’t go into all of the details here but in essence the steps are:
- Install only the base Windows Server 2003 OS from the SBS media and cancel the SBS integrated setup when it starts.
- DCPROMO the SBS server to the existing domain. (Same process outlined previously under “”Promoting a new DC into an existing SBS domain”)
- Install and configure DNS.
- Make sure the “Preferred DNS Server” value in the TCP/IP properties of the network connection points to an existing DNS server that , preferably the one and the “Alternate DNS Server” points to itself.
- Promote it to a GC.
- Transfer all FSMO roles to the SBS server.
- Complete the SBS integrated setup.
Be sure to follow 884453 completely and carefully and resolve any issues you encounter before continuing.
If the SBS is located at a site other than the default site, be sure to pre-define your sites and subnets as described previously so it will be placed into the correct site automatically.
Get fresh backups of all domain controllers after the DCPROMO and other changes
You want to make sure you don’t lose all of your work due to unforeseen circumstances. Get a good full backup including system state of every domain controller, both old and new.
Monitoring and maintaining a healthy network and Active Directory
The process for verifying the health of your network and domain after the new server promotion is pretty much the same as the process you followed before the promotion. Use NETDIAG, DCDIAG, REPLMON, and REPADMIN to check and monitor the health of the network, the domain, and replication. Also, make sure you add the new DC(s) to your regular backup procedures.
Join the conversationAdd Comment
thanks
The Official SBS Blog: Debunking Myths About Additional Domain Controllers In SBS Domains
PingBack from
The Official SBS Blog: Debunking Myths About Additional Domain Controllers In SBS Domains
Thanks for a great article. I’ve seen the information posted before, but it’s always good to have another reminder.
If you are going to run additional DCs in a virtual machine (VMware, XEN or Microsoft) make sure you check out KB 890893 and KB 888794 :
Note that you will encounter USN rollback problems if you use an AD-unaware program to backup and restore DCs.
thank you so much for posting this, excellent guide that came in very useful for me today!
how to remove small business server domain controller from AD ?? Any clue ?? I would be really grateful
my question isnthat an additional domain controler or RODC having global catalog
SBS 2011 supports, in the technical sense, trusts. It even works like clockwork. I have seen in a lab environment. | https://blogs.technet.microsoft.com/sbs/2007/10/04/debunking-myths-about-additional-domain-controllers-in-sbs-domains/ | CC-MAIN-2018-30 | refinedweb | 4,475 | 56.49 |
The CData Python Connector for EDGAR Online enables you to create ETL applications and pipelines for EDGAR Online data in Python with petl.
The rich ecosystem of Python modules lets you get to work quickly and integrate your systems more effectively. With the CData Python Connector for EDGAR Online and the petl framework, you can build EDGAR Online-connected applications and pipelines for extracting, transforming, and loading EDGAR Online data. This article shows how to connect to EDGAR Online with the CData Python Connector and use petl and pandas to extract, transform, and load EDGAR Online data.
With built-in, optimized data processing, the CData Python Connector offers unmatched performance for interacting with live EDGAR Online data in Python. When you issue complex SQL queries from EDGAR Online, the driver pushes supported SQL operations, like filters and aggregations, directly to EDGAR Online and utilizes the embedded SQL engine to process unsupported operations client-side (often SQL functions and JOIN operations).
Connecting to EDGAR Online Data
Connecting to EDGAR Online data looks just like connecting to any relational data source. Create a connection string using the required connection properties. For this article, you will pass the connection string as a parameter to the create_engine function.
- Navigate to and create an account.
- Register a new application and retrieve the AppKey. You should select one of the available Web APIs this application will use like HackPack, Insider Trades or Institutional Ownership.
Note: HackPack is the most important Web API that an application can use since it supports a large number of endpoints. If you are getting the "Access Denied" error you must create a new app and select the correct Web API which supports the resource you are querying.
- After successfully creating a new app, you can access your keys through your "my account" area. Set the AppKey connection property value equal to the Key of your application.
After installing the CData EDGAR Online Connector, follow the procedure below to install the other required modules and start accessing EDGAR Online through Python objects.
Install Required Modules
Use the pip utility to install the required modules and frameworks:
pip install petl pip install pandas
Build an ETL App for EDGAR Online.edgaronline as mod
You can now connect with a connection string. Use the connect function for the CData EDGAR Online Connector to create a connection for working with EDGAR Online data.
cnxn = mod.connect("AppKey=20dd8ce9904d422ed89ebde1ad40d")
Create a SQL Statement to Query EDGAR Online
Use SQL to create a statement for querying EDGAR Online. In this article, we read data from the Subscriptions entity.
sql = "SELECT Id, Name FROM Subscriptions WHERE SubscriberEmail = 'user@domain.com'"
Extract, Transform, and Load the EDGAR Online Data
With the query results stored in a DataFrame, we can use petl to extract, transform, and load the EDGAR Online data. In this example, we extract EDGAR Online data, sort the data by the Name column, and load the data into a CSV file.
table1 = etl.fromdb(cnxn,sql) table2 = etl.sort(table1,'Name') etl.tocsv(table2,'subscriptions_data.csv')
In the following example, we add new rows to the Subscriptions table.
Adding New Rows to EDGAR Online
table1 = [ ['Id','Name'], ['NewId1','NewName1'], ['NewId2','NewName2'], ['NewId3','NewName3'] ] etl.appenddb(table1, cnxn, 'Subscriptions')
With the CData Python Connector for EDGAR Online, you can work with EDGAR Online data just like you would with any database, including direct access to data in ETL packages like petl.
Free Trial & More Information
Download a free, 30-day trial of the EDGAR Online Python Connector to start building Python apps and scripts with connectivity to EDGAR Online data. Reach out to our Support Team if you have any questions.
Full Source Code
import petl as etl import pandas as pd import cdata.edgaronline as mod cnxn = mod.connect("AppKey=20dd8ce9904d422ed89ebde1ad40d") sql = "SELECT Id, Name FROM Subscriptions WHERE SubscriberEmail = 'user@domain.com'" table1 = etl.fromdb(cnxn,sql) table2 = etl.sort(table1,'Name') etl.tocsv(table2,'subscriptions_data.csv') table3 = [ ['Id','Name'], ['NewId1','NewName1'], ['NewId2','NewName2'], ['NewId3','NewName3'] ] etl.appenddb(table3, cnxn, 'Subscriptions') | https://www.cdata.com/kb/tech/edgaronline-python-petl.rst | CC-MAIN-2021-21 | refinedweb | 674 | 54.73 |
Recently I needed to know if a program I was running was using Python2 or Python3.
There are a couple of ways to do this inside the Python interpreter.
The most obscure way (IMO) is probably the most reliable
import sys major_version = sys.version_info[0] print(major_version)
This method is reliable but how did I know to look at position 0 in sys.version_info? That looks odd and feels like magic.
In Python 2.6 sys.version_info was a tuple. It was not a class so sys.version_info[0] is the major number (aka 2). In Python 2.7 and up the sys.version_info became effectively a class and this type of code became valid
print(sys.version_info.major)
That code above will fail in an older Python so the safe way to check your version is the ugly way :(
Discussion (0) | https://dev.to/tonetheman/detecting-python-version-in-a-script-2c5n | CC-MAIN-2021-39 | refinedweb | 142 | 78.35 |
Python#
Grist formulas are written in Python, the most popular language for data science. The entirety of Python’s standard library is available to you. For those with a spreadsheet background, we’ve also added a suite of Excel-like functions, with all-uppercase names. Here’s the full list of functions. Python formulas are evaluated in a sandbox, without internet access, and without a persistent filesystem.
Supported Python versions#
We currently support two versions of Python:
- Python 3 (specifically 3.9 at the time of writing)
- Python 2 (specifically 2.7)
Newly created documents on our hosted service use Python 3 by default, while older documents
(created before November 2021 approximately) use Python 2 by default. To tell which version of Python
a specific document uses, look at its Document Settings.
The
Engine setting may be
python2,
python3, or blank.
A blank setting implies
python2.
If you have editing rights on a document, you can change the
Engine setting,
and the document will then reload with all formulas now interpreted using the
version of Python you have specified. We recommend caution in doing so.
A formula that works as intended in one version of Python may give errors
in another, or (worse) give the wrong results.
Some formulas may fail or give wrong results if used with a version of Python that is different from the one for which they were written.
Python 2 reached its end of life in January 2020, so if you look online for python help, the answers you find are more and more likely to be for Python 3. If you have a document that uses Python 2, and you’d like to switch it to use Python 3, we recommend reading Testing the effect of changing Python versions and Differences between Python versions. Be sure to check all tables and columns, and both regular formalas and trigger formulas. We’d be interested to hear your experience, and to help with any problems, on the community forum.
Self-hosted Grist may use any version of Python you configure it with, but bear in mind we actively test only the supported versions.
Testing the effect of changing Python versions#
Grist has some features that can help you evaluate the consequences of changing the Python version a document uses.
- The Work on a Copy feature is useful to experiment with changing the Python version without affecting your document until you are ready. There is a “Compare with original” option that will let you visualize which cells changed, if any. Be sure to look at all tables and columns.
- The Activity tab of Document History (with “All Tables” selected) lets you review in more detail what has changed.
- Be careful to test any trigger formulas you may have, since the Python code in them won’t be exercised until you specifically trigger these formulas.
- You can use the code viewer to quickly remind yourself of all formulas in a document, so you can systematically check them all.
Differences between Python versions#
There are important differences between Python 2 and 3. Formulas may need to be changed in order to give the same results when switching between Python versions. There are many online resources such as this compatibility cheatsheet which can help figure out what the issue is when you hit a difference, and get ideas on how to resolve it. Here, we list common cases we’ve seen in Grist formulas.
Division of whole numbers#
In Python 2, dividing whole numbers gives a whole number, so
9 / 2 is
4.
In Python 3, it is
4.5. For a spreadsheet, this is a much more sensible answer,
but if you rely on the Python 2 behavior, we suggest you switch to the
// operator
which is consistent between versions (
9 // 2 is
4 for both).
For example the General Ledger
template had a Python 2 formula for computing the quarter from a date (so a
Date of
2021-08-15 gave a
Quarter of
2021 Q3) as follows:
"%s Q%s" % ($Date.year, CEILING($Date.month, 3) / 3)
when switching to Python 3, this needed correcting to:
"%s Q%s" % ($Date.year, CEILING($Date.month, 3) // 3)
Otherwise Quarters became fractional!
Some imports are reorganized#
Python has a useful standard library, but some parts of it were
moved around between Python 2 and 3.
For example, several of our templates have formulas to construct URLs,
to open custom searches for example, or to open a pre-populated email
with calculated
To,
CC, and
Subject values.
Python has handy helpers for constructing URLs,
but they moved around a bit between Python versions.
Our Lightweight CRM
example had a Python 2 formula like this to kick off a search for emails in
Gmail:
from urllib import quote_plus "Gmail search" % quote_plus($Email)
In Python 3, the import line needed changing to:
from urllib.parse import quote_plus
Subtle change in rounding#
Python 3 switches the built-in function
round() from rounding the way many people learned in school
(where when rounding
.5, you always round up)
to what is called “banker’s rounding” (where you round from
.5 to the
nearest even number). This is generally accepted as an improvement, mitigating
a bias to larger numbers that can become significant at scale.
But it could be a surprise to see numbers change like this in an established
document.
If you really need Python 2’s rounding, replace any calls to Python’s
round function with the Excel-compatible ROUND function. For example:
round($val, 2)
would be replaced with:
ROUND($val, 2)
Unicode text handling#
Python 2 does not shine at handling international text and emojis.
We have mitigated many problems by setting the default encoding
to
utf8 for all documents. Nevertheless, when switching from Python 2 to
Python 3, you may see type changes or errors. Consider this Python 2 formula
to generate a one-way hash of an email address:
import hashlib hashlib.sha256($Email).hexdigest()
In Python 3 this fails with
TypeError: Unicode-objects must be encoded before hashing,
which can be resolved by replacing
import hashlib hashlib.sha256($Email.encode()).hexdigest() | https://support.getgrist.com/python/ | CC-MAIN-2021-49 | refinedweb | 1,023 | 60.75 |
C++ <cstdio> - SEEK_SET, SEEK_CUR, SEEK_END
The C++ <cstdio> SEEK_SET, SEEK_CUR, SEEK_END macro constants are used to set origin, which is the position to which offset is added in the fseek() function.
Example:
In the example below, a file is created using fopen() function. The initial content of the file is written to the file using fputs() function. Then, by using fseek() function current file position indicator is set to 10 bytes measured from beginning of the file. After that, agian by using fputs() function, the content of the file is modified.
#include <stdio.h> int main (){ FILE *pFile = fopen("test.txt", "wb"); //writes content in the file fputs("This is a test file.", pFile); //set the current file position indicator to //10 bytes measured from beginning of the file fseek(pFile, 10, SEEK_SET); //modify the content after 10 bytes fputs("modified content.",; }
After the code is successfully executed, the test.txt file will contain:
This is a modified content.
❮ C++ <cstdio> Library | https://www.alphacodingskills.com/cpp/notes/cpp-cstdio-fseek-arguments.php | CC-MAIN-2021-43 | refinedweb | 162 | 65.62 |
React’s ⚛️ new Context API
It’s way more ergonomic, it’s no longer “experimental,” and it’s now a first-class API! OH, AND IT USES A RENDER PROP!
NOTE: This is a cross-post from my newsletter. I publish each email to my blog() {
return (
<ThemeProvider>
<ThemeContext.Consumer>
{val => <div>{val}</div>}
</ThemeContext.Consumer>
</ThemeProvider>
)
}
}() {
return (
React 16.3-alpha just hit npmjs and can be downloaded and added to your project. What are the biggest, most interesting…medium.com
Some tweets from this last week:
P.S. If you like this, make sure to subscribe, follow me on twitter, buy me lunch, support me on patreon, and share this with your friends 😀
Also, retweeting this is a great way to share this with your friends:
👋 Hi! I’m Kent C. Dodds. I work at PayPal as a full stack JavaScript engineer. I represent PayPal on the TC39. I’m actively involved in the open source community. I’m an instructor on egghead.io, Frontend Masters, and Workshop.me. I’m also a Google Developer Expert. I’m happily married and the father of four kids. I like my family, code, JavaScript, and React.
| https://medium.com/dailyjs/reacts-%EF%B8%8F-new-context-api-70c9fe01596b | CC-MAIN-2018-47 | refinedweb | 196 | 70.6 |
It works for me. Please post an example, including the error message you are getting or issues you are seeing. One common source of problems is file paths. When you run a script from the shell, you are in your home directory, or you have explicitly changed to a specific directory. When you run a script with a Process object, the current directory is down in the system tree. Unless you use full path names for all of your referenced files and modules, your script is unlikely to find them. Note that each time you run something from a Process object, you are starting with a new execution context. So you can use a Process call to change directory, then assume that the next Process call will be running in that directory - that won't work. What you want to do does work, i do it all the time. Please provide more details so we can figure out why it's not working for you.
You say nothing happens - what are you expecting to happen?If you post your sketch and your Python script, as well as a description of what you expect it to do, we can be more helpful. Otherwise, we can only talk in generalities.
from __future__ import print_functionimport loggingimport osimport subprocessimport sysimport gphoto2 as gpdef main(): logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) camera = gp.check_result(gp.gp_camera_new()) gp.check_result(gp.gp_camera_init(camera)) print('Capturing image') file_path = gp.check_result(gp.gp_camera_capture( camera, gp.GP_CAPTURE_IMAGE)) print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name)) target = os.path.join('/tmp', file_path.name) print('Copying image to', target) camera_file = gp.check_result(gp.gp_camera_file_get( camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result(gp.gp_file_save(camera_file, target)) subprocess.call(['xdg-open', target]) gp.check_result(gp.gp_camera_exit(camera)) return 0if __name__ == "__main__": sys.exit(main())
That's half f the picture. If you run this from the command shell, it runs properly, correct? Does it run no matter what directory you are in? Try changing to some different directories, and make sure it runs properly. Note that I do mean from the command shell, not from a Python prompt....
#include <Bridge.h>void setup(){ Bridge.begin(); capture(); }void loop(){ }void capture(){ Process p; p.begin("python"); p.addParameters("capture-image.py"); p.run(); }
I try to put the script in various directories and it works.
The script is in the same directory of the sketch
p.begin("python"); p.addParameters("capture-image.py"); p.run();
p.begin("python"); p.addParameters("/mnt/sda1/capture/capture-image.py"); p.run();
while (p.available()>0) { char c = p.read(); Serial.print(c); } Serial.flush();
I think you misunderstood me, I must not have been clear. I wasn't suggesting that you move the script to various directories. Keep the script in your desired directory, and then change to other directories and try running the script...
In my experience you must use a full path to your script file, or the Process object will not be able to find it. ...
Another thing that may be helpful, at least during development, is to echo any output you get from the Process object to the Serial port (or Console if you are working over a network connection.) That way, if the Process object returns any error messages, you can see what they are. My guess is that it is returning a message that it can't find capture-image.py.
I also try this, but nothing, no message is written on the Serial Monitor, and I've setup Serial port withSerial.begin(9600)
while (!Serial);
#include <Bridge.h>void setup() { Serial.begin(9600); // Initialize serial USB port while (!Serial); // Wait for Serial Monitor to connect Serial.println("Starting Bridge..."); Bridge.begin(); Serial.println("Bridge started.");}void loop() { Serial.println(); Serial.println("Calling capture()"); capture(); Serial.println("capture() returned"); delay(2000); // A little delay to prevent messages being printed too quickly}void capture() { Process p; // Call the Python script. p.begin("python"); p.addParameter("/mnt/sda1/PythonTest.py"); p.run(); if (p.available()) // Is there any output from the script? { Serial.print("Output from script: \""); while (p.available()) // As long as there is output waiting from the script... { char c = p.read(); // Read a character of output Serial.print(c); // Echo the character to the serial port } Serial.println("\""); // Print a closing quote character and new line } else Serial.println("No output received from script");}
Starting Bridge...Bridge started.Calling capture()No output received from scriptcapture() returned
print "PythonTest script!"
Starting Bridge...Bridge started.Calling capture()Output from script: "PythonTest script!"capture() returned
... Try running the code I posted above, and see if it works for you. If so, please post your updated sketch, the one that echos the output and references the Python script with a full path name, and I will try it on my Yun. (Note that the sketch you posted earlier doesn't compile - you are calling p.addParameters(), when the function name is actually p.addParameter() - the name is not plural.)
Is it relevant that I'm using Raspberry Pi3 with Ubuntu Mate?
Anyway, the path I used is /home/raspberry-desktop/test-python.py , that is like your script with only the println; the path is that of the file properties. This path properly works from the command shell.
Yes, that would be a very important detail! Now I'm very confused. I thought you were using a Yun. How does the RPi factor into this? Just what are you trying to do, and what is your overall configuration?I didn't look too deeply at the Python code you provided, I was just looking to see if it made any relative references to files. I saw that it was using an image capture library, but I didn't look at it, I just figured you were trying to capture an image from a USB camera plugged into the Linux side of the Yun. Are you running the Python script on the RPi and trying to capture an image from the Pi's camera? If so, a very different mechanism is going to need to be used, as the Process object just runs a command on the local Linux processor. You will need to get into some networking and remote procedure calls to execute something on the RPi.Is that the Yun's or the Pi's command shell? Above, when I ask if you can run the script from any directory using the command shell, I mean the command shell you get when you SSH int your Yun. | http://forum.arduino.cc/index.php?PHPSESSID=vqk10h7o22tncqmte7t30jtji6&topic=526915.0 | CC-MAIN-2018-09 | refinedweb | 1,108 | 59.8 |
import "github.com/stefantalpalaru/pool"
Package pool provides a worker pool.
type Job struct { F func(...interface{}) interface{} Args []interface{} Result interface{} Err error // contains filtered or unexported fields }
Job holds all the data related to a worker's instance.
type Pool struct { // contains filtered or unexported fields }
Pool is the main data structure.
func New(workers int) (pool *Pool)
New creates a new Pool.
func (pool *Pool) Add(f func(...interface{}) interface{}, args ...interface{})
Add creates a Job from the given function and args and adds it to the Pool.
func (pool *Pool) Results() (res []*Job)
Results retrieves the completed jobs.
func (pool *Pool) Run()
Run starts the Pool by launching the workers. It's OK to start an empty Pool. The jobs will be fed to the workers as soon as they become available.
func (pool *Pool) Status() stats
Status returns a "stats" instance.
func (pool *Pool) Stop().
func (pool *Pool) Wait()
Wait blocks until all the jobs in the Pool are done.
func (pool *Pool) WaitForJob() *Job
WaitForJob blocks until a completed job is available and returns it. If there are no jobs running, it returns nil.
Package pool imports 5 packages (graph) and is imported by 2 packages. Updated 2014-01-16. Refresh now. Tools for package owners. | http://godoc.org/github.com/stefantalpalaru/pool | CC-MAIN-2015-18 | refinedweb | 212 | 77.64 |
----------------------------------------------------------- This is an automatically generated e-mail. To reply, visit: -----------------------------------------------------------
Advertising
Review request for mesos, Chi Zhang and Vinod Kone. Repository: mesos Description ------- Forced the network isolator to use the mount namespace. The code of the network isolator actually relies on the fact that the child is in a seprate mount namespace. For example: It originally depends on mount namespace, but was removed in this patch: That was a bug to me. It didn't cause any issue because we don't clone the mounts (since we are not using mount namespace) anymore after the above patch. So the kernel won't have an extra reference to the mount when we try to umount it in `_cleanup()`. Diffs ----- src/slave/containerizer/isolators/network/port_mapping.cpp 3f6e9df8711995d0dd3903c6170fdd5ad61aac5a Diff: Testing ------- sudo make check Thanks, Jie Yu | https://www.mail-archive.com/reviews@mesos.apache.org/msg06123.html | CC-MAIN-2018-05 | refinedweb | 134 | 64.2 |
This round of questions has to do with how to handle globalization issues when it comes to BiDi (Bi-Directional) languages like Arabic and Hebrew.
I would like to know what it is that makes an international version of Windows such as the Arabic BiDi? Is it special editions of common controls such as comctl32 and other controls, or is it something else? Is there at all a hidden API function to support RTL writing in Windows Me English edition, and is there a tool for defining keyboard layouts? Last but not least, if Microsoft has separated localization info such as menu item names and start menu name, is it in a special file or something and can it be changed to localize a Windows English or Arabic localized to Persian or any other language, what are the files?
Yours Sincerely From The Internet
Dear, From the Internet
There are no "hidden" or undocumented APIs. Everything Microsoft uses for mirroring is available to you as well. A brief article on mirroring in Windows can be found at.
The resources, including the text in the UI, in Win32 are stored as a part of the binaries, in resource sections. Localization can change these resources without recompilation. This takes both special tools and a lot of expertise in how OS components interact, so this task is far from being trivial. But the good things are: Arabic localized OS exists already; unfortunately, Persian localization can not be done for Windows ME, because Farsi is not fully supported by ANSI, and Windows ME is not a Unicode-based OS (in contrast to Windows 2000)
I am trying to develop dual Arabic/English Application using Visual C++ 6.0 under Windows 2000 Arabic. I read the documents which you suggest to create a Satellite DLL for each Language. I tried to create Resource File (.rc) for Arabic, but when I run the application I can see garbage. I went to Visual C++ 6.0 Resource Editor to choose the language for the Resource but I couldn't find Arabic.
Also I downloaded a Unicode RC from the Internet, but The Visual C++ Resource Editor can't open this Unicode File, although I can use the Compiled DLL but I can't Modify the Resource File.
What is the Best Method to Create an Arabic Resource File in Visual C++ ??
Arabic needed Software Engineer
Dear, Arabic needed
I understand your frustration since I went thru the same problems before. Here are two possible solutions:
Some versions of Windows operating system has a technology called "Mirroring" which reflects the appearance of all windows and controls to the Right-to-Left direction. You can achieve this by using the API function "SetWindowLong". Regardless the RightToLeft property, the Mirror Technology gives you a real RTL direction. As shown in the figure bellow.
Mirror Technology works 100% correct with the Visual C++ and Delphi. But when applying it with Visual Basic, a lot of problems occur, I wrote this code:
Option Explicit WS_EX_LAYOUTRTL As Long = &H400000 Private Sub Form_Load() Dim L As Long L = GetWindowLong(Me.hwnd, GWL_EXSTYLE) SetWindowLong Me.hwnd, GWL_EXSTYLE, L Or WS_EX_LAYOUTRTL End Sub
But it doesn't give me a good results especially when applying to Windows Common Controls L I really need your help for that.
from the internet 2
Dear Internet 2
Setting Window class at run-time is possible, but it is not the best solution for mirroring windows. The reasons are:
How can I determine (with APIs) whether the OS version is "Local" Hebrew/Arabic, or it's another version ("Enabled" Middle-East, or non-Middle-East at all)?
Searching for enlightenment
Dear, Searching
Here is how it really works depending on the OS version:
Windows 2000 / Windows XP
Win9x / WinME
Windows NT
Here is some sample code on how you might do this (please note that this code is provided as is and is given here as an illustrating example only).
// Load and check the language of version stamping of NTDLL.DLL // For East Asian countries that might be a multilingual // version, we only take non-English ones in consideration. hLib = LoadLibrary(_TEXT("ntdll.dll")); if (hLib == NULL) { // we fail to load the file and exit... return (FALSE); } EnumResourceLanguages(hLib, RT_VERSION, MAKEINTRESOURCE(1), EnumResLangProc, NULL); FreeLibrary(hLib); // we have an English version stamping. We still might // be dealing with an enabled language (Arabic, // Hebrew, or Thai) if (g_wLangID == US_LANG_ID) { UINTuiACP; uiACP = GetACP(); switch (uiACP) { case 874: // Thai code page activated, it's a Thai enabled system g_wLangID = MAKELANGID(LANG_THAI, SUBLANG_DEFAULT); break; case 1255: // Hebrew code page activated, it's a Hebrew enabled system g_wLangID = MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT); break; case 1256: // Arabic code page activated, it's a Arabic enabled system g_wLangID = MAKELANGID(LANG_ARABIC, SUBLANG_ARABIC_SAUDI_ARABIA); break; default: break; } } /*************** ***************/ BOOL CALLBACK EnumResLangProc(HANDLE hModule, LPCTSTR lpszType, LPCTSTR lpszName, WORD wIDLanguage, LONG_PTR lParam) { if (!lpszName) return FALSE; if (wIDLanguage != US_LANG_ID) g_wLangID = wIDLanguage; return TRUE; }
How can I set the locale?
anonymous
Dear, Anonymous
I have been asked this question over and over. And the only answer I can give is: which locale are you referring to? So lets have a look together into "locales". I will call this Locale 101.
Michelle is living in the US. Her location is set to the United States because she wants to use a national ISP or she wants to get weather forecasts for the US. Her user locale is set to Spanish-Chile because she wants to see formatted data within her native country's standards.
Michelle is also fluent in Korean. She recently purchased a Korean word-processor (ANSI app!) that she wants to run on her English machine. She sets her system locale to Korean. To start using her app, beside the English keyboard, she installs a Korean IME as a second input locale. Her husband, sharing the same computer and not being comfortable with English, can set the UI language to Spanish for his own account (if running MUI [Multilingual User Interface version of Windows 2000/XP])!. Use GetACP / GetOEMCP APIs to retrieve that value. No API available to set this locale (by design).
User Locale: Or "Standards and formats" in Windows XP. This per user variable defines user's preferences for formatting locale sensitive data (date, time, currency ...). Your application should be using that setting to display formatted data. Use GetUserDefaultLCID to retrieve that value. No API available to set this locale (by design).
Input Locale: Called the same in Windows XP.This per process locale is a combination of input language (e.g. Greek) and input method (e.g. keyboard). Use GetKeyboardLayout & LoadKeyboardLayout to retrieve/set that value.
Thread Locale: This per thread locale is initialized with the currently selected user locale value. Formerly used to retrieve language specific resources from a multilingual resource file (see GetThreadLocale/SetThreadLocale for more info). Should only be used to synchronize the thread locale of a server application with the user locale of a client machine. This can only be set programmatically.
Location: Or geographic ID. This per user variable is newly introduced in Windows XP to define the country where the user lives. Use GetGeoInfo to retrieve that value. No API is available to set this locale (by design). Users can change it thru the Region Options tab of the Regional and Language Options applet (can be set on the fly).
UI Language: This per user variable defines the language in which menus, dialog boxes, help files ... are translated, and is only found on the MUI (Multilangual User Interface version of Windows 2000/XP). Use Get[User/System]DefaultUILanguage to retrieve its value. No API's are available to set this locale (by design).
I hope you learned all this because there may be a pop quiz in the next Dr. International article.
I'm concerned about supporting non-ASCII computer names on Win9x and NT4 clients connected to a Windows 2000 Server. Do other Microsoft operating systems support non-ASCII computer names and NET BIOS names if the default system locale is the same on all machines including the server?
Karla in Seattle
Dear, Karla
The same rule applies for both your Win9x and WinNT machines. They only support non-ASCII computer names that are compatible with the system's code page. For example, if you're Windows 2000 is set to the Japanese system locale and is has a Japanese computer name, you can only see that machine from machines running a Japanese version of Win9x or NT.
Suggestion: to allow down-level compatibility and to avoid a computer setting dependency, it's highly suggested to keep ASCII computer names in a multilingual environment.
See you next time and don't forget to study for that possible Locale 101 pop quiz.
Dr. International
Windows Division | http://www.microsoft.com/globaldev/drintl/columns/009/default.mspx | crawl-002 | refinedweb | 1,462 | 54.73 |
"python"
and then create a Voltage axis graph, "Plot what?" doesn't list any sections.
Code: Select all
from neuron import h,gui soma = h.Section() dend = h.Section()
I get an even stranger response when I launch "nrngui -python". "Plot what?" displays a really messed up picture, which appears to be empty.
I have tried to fix this by giving the section a name:
To no avail.
Code: Select all
from neuron import h,gui soma = h.Section(name='soma') print soma.name()
The following method does work:
I don't know how hard this is to fix. This might be confusing to those new to Neuron+Python.
Code: Select all
from neuron import h,gui h('create soma') soma = h.soma
On a related note, the "Distributed Mechanisms" menu item does list sections created via the "soma = h.Section(name='soma')" method. However, when I try to access them, I get:
I am not sure if this is a related bug.
Code: Select all
NEURON: syntax error near line 2 {.L} ^ nrnsecmenu(-1, 1) MenuExplore[0].execute("nrnsecmenu(-1,1)") MenuExplore[0].make_menu() doNotify() Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/neuron/gui.py", line 36, in run self.fun() File "/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/neuron/gui.py", line 17, in process_events h.doNotify() RuntimeError: hoc error
As always, thanks for all the work on Neuron! | https://www.neuron.yale.edu/phpBB/viewtopic.php?f=2&t=1988&p=7288 | CC-MAIN-2020-16 | refinedweb | 271 | 62.54 |
On 5/3/2012 2:23 AM, Nick Coghlan wrote: > On Thu, May 3, 2012 at 2:37 PM, PJ Eby <pje at telecommunity.com> wrote: >> Still, code that expects to do something with a package's __file__ is >> *going* to break somehow with a namespace package, so it's probably better >> for it to break sooner rather than later. > > My own preference is for markers like "<frozen>", "<namespace>" and "<builtin>". It looks like "<frozen>" is indeed used, but built in modules do not set __file__. So I don't really see that as a precedent for setting it to something, but I do agree with most of your points below. > They're significantly nicer to deal with when dumping module state for > diagnostic purposes. If I get a KeyError on __file__, or an > AttributeError on NoneType when all I'm trying to do is display data, > it's annoying. > >) > > That should really only blow up in get_data(), *not* on the > os.path.join step. Ideally, you should also be able to do this: > > data_ref = os.path.join(mod.__file__, relative_ref) > data = mod.__loader__.get_data(data_ref) While I embrace the pattern, I don't see how it could ever work for a namespace package. The defining quality is that the namespace package itself doesn't contain any files. And NamespaceLoader doesn't define get_data for this reason. > I see it as being similar to the mandatory file attribute on code > objects - placeholders like "<stdin>" and "<string>" are a lot more > informative when errors occur than just using None, even though > neither of them is a valid filesystem path. So the 4 options on the table are: 1. Add a (possibly meaningless) trailing slash character. 2. Use None. 3. Do not set it. 4. Set it to "<namespace>". We'll discuss it today at our sprint. | http://mail.python.org/pipermail/import-sig/2012-May/000502.html | CC-MAIN-2013-20 | refinedweb | 305 | 73.37 |
If you're a fan of HBO's Silicon Valley, you'll remember when they launched a real AI-powered mobile app that classifies hotdogs from a given image (or not). Using Google's Vision API, let's try to recreate a working model of the application in React Native.
Google's Vision API is a machine learning tool that classifies details from an image provided as an input. The process of these classifications is based on thousands of different categories that are included in pre-trained API models. The Vision API enables access to these pre-trained models via a REST API.
What are we building?
Table of Contents
- Prerequisites
- Setup Firebase Project
- Integrate Firebase SDK with React Native app
- Generate a Google Vision API Key
- Setting Permissions for Camera & Camera Roll
- Create a Header component
- Adding an Overlay Spinner
- Access Camera and Camera Roll
- Add functionality to determine a Hot dog
- Display final results
- Conclusion
Prerequisites
To follow this tutorial, please make sure you have the following installed on your local development environment and have access to the services mentioned below:
- Node.js (>=
10.x.x) with npm/yarn installed.
- expo-cli (>=
3.0.9), previously known as create-react-native-app.
- a Google Cloud Platform account
- Firebase Storage setup
- Expo Client app for Android or iOS, used for testing the app
Setup Firebase Project
In this section, let us set up a new Firebase project. If you are already familiar with the process and know how to get a config keys from a Firebase project, you can skip this step.
Visit Firebase and sign-in with your Google ID. Once signed in, click on a new project and enter a name. Lastly, hit the Create project button.
After creating the project and being redirected to the dashboard screen, on the left side menu, click the settings icon, and then go to Project settings.
The whole the
firebaseConfig object, as shown above, is required to integrate Firebase with a React Native or Expo app. Save them somewhere or make sure you know how to navigate to this page.
The next step is to setup Firebase storage rules such as to allow to upload image files through the app. From the left-hand side menu in the Firebase console, open Storage tab and then choose Rules. Modify them as follows.
service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write } } }
Firebase setup is complete.
Integrate Firebase SDK with React Native app
To get started, create a new React Native project. For this demonstration, let us use
expo-cli, an awesome tool that helps to create React Native apps at a faster rate. Open a terminal window, and run the following series of commands.
# generate a new app expo init not-hotdog-app # navigate inside the app folder cd not-hotdog-app # install the firebase SDK & other dependencies yarn add firebase@6.0.1 expo-permissions expo-image-picker uuid react-native-elements
Also, this tutorial is using
yarnas the package manager but you are most welcome to use
npm.
Now that the project is generated open the directory in your favorite text editor. Then create a new folder called
config and inside it, a new file called
Firebase.js. This file will be responsible for integrating Firebase with the Expo app.
import * as firebase from 'firebase' const firebaseConfig = { apiKey: 'XXXX', authDomain: 'XXXX', databaseURL: 'XXXX', projectId: 'XXXX', storageBucket: 'XXXX', messagingSenderId: 'XXXX', appId: 'XXXX' } // Initialize Firebase firebase.initializeApp(firebaseConfig) export default firebase
All the Xs are values of each key in the
firebaseConfig object from the previous section. This completes the step to integrate a Firebase Web SDK with an Expo app.
Generate a Google Vision API Key
Once you are signed in to Google Cloud Platform, you can visit the Google Cloud Console, to create a new project.
From the dropdown menu center, select a project. Then click the button New Project in the screen below. Notice you have already generated a Firebase project, select that from the list available.
Right now you are at the screen called Dashboard inside the console. From the top left, click on the menu button and a sidebar menu will pop up. Select APIs & Services > Dashboard.
At the Dashboard, select the button Enable APIs and Services.
Then search for the Vision API and make sure to click the button Enable.
Now, go back to the Dashboard and go to Credentials to generate an API key. Click the button Create Credentials and you will undergo a small process to generate the API key.
Once it is done, save the API key in
App.js file after all the import statements.
const VISION_API_KEY = 'XXXX'
The setup is complete. Let us move to the next section and start building the application.
Setting Permissions for Camera & Camera Roll
To set permissions in any Expo app, all you need is to utilize an asynchronous method from the module
expo-permissions. For this clone, there are two permissions that need to be set. The required permissions are for Camera and Camera Roll (or Photos of your device).
Camera roll is used in a case where the user wants to upload an image. For iOS simulator devs, you cannot access the camera so if you are not planning to use a real device until the end of this tutorial, but want to follow along. It is recommended to add Camera Roll functionality.
Import the permissions module in
App.js file.
import * as Permissions from 'expo-permissions'
Next step is to set an initial state that will control the
View in the
render method by determining whether the user has granted the permission to your app to use Camera and Camera roll or not.
class App extends Component { state = { hasGrantedCameraPermission: false, hasGrantedCameraRollPermission: false, }
Next, using a lifecycle method
componentDidMount(), define a promise for each permission. In the below snippet, you will find two functions
cameraRollAccess() and
cameraAccess() performing this operation. Respectively, each of these permission component has a permission type:
- for Camera Roll:
Permissions.CAMERA_ROLL
- for Camera:
Permissions.CAMERA
async componentDidMount() { this.cameraRollAccess() this.cameraAccess() } cameraRollAccess = async () => { const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL) if (status === 'granted') { this.setState({ hasGrantedCameraRollPermission: true }) } } cameraAccess = async () => { const { status } = await Permissions.askAsync(Permissions.CAMERA) if (status === 'granted') { this.setState({ hasGrantedCameraPermission: true }) } }
Each of the permission components returns a
status value of
granted or
denied. In case of the permissions are granted, the value of state variables
hasGrantedCameraRollPermission and
hasGrantedCameraPermission are both set to true. The method
Permissions.askAsync() to prompt the user for the type of permission.
Next, go to the render method of the
App component and add condition using the two-state variables. If both are set to true, it will display the first screen of the application.
render() { const { hasGrantedCameraPermission, hasGrantedCameraRollPermission, } = this.state if ( hasGrantedCameraPermission === false && hasGrantedCameraRollPermission === false ) { return ( <View style={{ flex: 1, marginTop: 100 }}> <Text>No access to Camera or Gallery!</Text> </View> ) } else { return ( <View style={styles.container}> {*/ Rest of the content in the next section*/ } </View> ) } } // Corresponding StyleSheet Object const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff' } })
If either or both are not granted, the app will display the message
No access to Camera or Gallery!, also as shown below.
When tested on a real android device, it did ask for permissions.
Similarly, to use camera:
Create a Header component
Using
react-native-elements UI library for React Native, let us quickly create a useful header that will hold two buttons and the app's title in text. The left button will be to open the phone's gallery or camera roll consisting of user photos. The right button will be to open access the Camera on a real device.
Import the
Header component from the
react-native-elements library.
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native' import { Header, Icon } from 'react-native-elements'
The UI library has a pre-defined component called
Header that you can use right away. This component accepts the icons on the left and right side. Since the app needs these icons to be clickable, use
TouchableOpacity such that its
prop can be later used to open the camera or the camera roll.
<View style={styles.container}> <Header statusBarProps={{ barStyle: 'light-content' }} </TouchableOpacity> } centerComponent={{ text: 'Not Hotdog?', style: { color: '#fff', fontSize: 20, fontWeight: 'bold' } }} rightComponent={ <TouchableOpacity onPress={() => alert('soon')}> <Icon name="camera-alt" color="#fff" /> </TouchableOpacity> } /> </View>
The
Header component also has a
statusBarProps prop to change the color of the Status bar and works cross-platform. It will give the following output.
Both the icons are touchable, but right now they do not have an associated handler method except that a dummy
alert message.
The
react-native-elements library by default uses Material Icons and has a peer dependency of
react-native-vector-icons.
Adding an Overlay Spinner
The next element to add in the initial state object is
uploading with a value of false. This variable will be used in the app to display an animated spinner whenever an image is being uploaded from the Camera Roll or analyzed by the Vision API for the result.
state = { //... rest, uploading: false } // also make sure to include deconstruct the state inside render() const { hasGrantedCameraPermission, hasGrantedCameraRollPermission, uploading } = this.state
Create a new file inside
components/UploadingOverlay.js. This file is going to contain a presentational component with the same name as the filename. Using
ActivityIndicator from
react-native you can animate this component by using its prop called
animating.
import React from 'react' import { ActivityIndicator, StyleSheet, View } from 'react-native' const UploadingOverlay = () => ( <View style={[StyleSheet.absoluteFill, styles.overlay]}> <ActivityIndicator color="#000" animating </View> ) const styles = StyleSheet.create({ overlay: { backgroundColor: 'rgba(255,255,255,0.9)', alignItems: 'center', justifyContent: 'center' } }) export default UploadingOverlay
Adding
StyleSheet.absoluteFill to the
style prop of the
View component which holds the spinner, you can create an overlay screen. An overlay is just a screen or a
View in terms of React Native that allows the current screen to appear on top of other screens. Using the
backgroundColor property, you can add the
opacity in the last after defining RBG values.
For example, when asking permission to access the Camera, a dialog box appeared on the app screen (as shown in the previous section). Notice how the box was position on top of the screen in the background.
Now, go back to
App.js and add this component at the bottom of the
render() section, just before the root
View component is ending. Do not forget to import the component.
import UploadingOverlay from './components/UploadingOverlay' // ... rest { uploading ? <UploadingOverlay /> : null }
The above condition states that, if the value of
this.state.uploading is true, it will show the overlay screen. To test it out, temporarily set the value of
uploading in the state object to
true.
An endless spinner will continue to appear. Set the value of
uploading back to false before proceeding.
Access Camera and Camera Roll
In this section, you are going to add the functionality of accessing Camera and Camera Roll by defining three different handler functions in
App component. Make sure you are inside the file
App.js. First, import the following statement since this section is going to make use of Firebase's storage and
uuid module to create a unique referent to each image.
import firebase from './config/Firebase' import uuid from 'uuid'
Next, modify the initial state of the object to add the following for the final time.
state = { hasGrantedCameraPermission: false, hasGrantedCameraRollPermission: false, uploading: false, image: null, googleResponse: false }
To enable both of these functionalities in the current app, let us leverage another Expo module called
expo-image-picker. First, import the module after the rest of the import statements.
import * as ImagePicker from 'expo-image-picker'
Expo documentation has the best definition of what this module is used for. Take a look.
[Image Picker] Provides access to the system's UI for selecting images and videos from the phone's library or taking a photo with the camera.
That's all you need right now. Define the first function,
takePhoto that is going to access the phone's camera to click a photo.
takePhoto = async () => { let pickerResult = await ImagePicker.launchCameraAsync({ allowsEditing: true, aspect: [4, 3] }) this.handleImagePicked(pickerResult) }
The asynchronous method
ImagePicker.launchCameraAsync() accepts two arguments:
allowsEditingshows the UI to edit the image after it is clicked. Mostly used to crop images.
aspectis an array to maintain a consistent aspect ratio if the
allowsEditingis set to true.
Similarly,
ImagePicker.launchImageLibraryAsync() is used with the same set of arguments to access Camera roll.
pickImage = async () => { let pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [16, 9] }) this.handleImagePicked(pickerResult) }
Both of these asynchronous functions, return the
uri of the image selected (among other arguments that you can view in the official docs here). Lastly, both of these methods are calling another callback
handleImagePicked after their job is done. This method contains the business of logic of how to handle the image after it is picked from the camera roll or clicked.
handleImagePicked = async pickerResult => { try { this.setState({ uploading: true }) if (!pickerResult.cancelled) { uploadUrl = await uploadImageAsync(pickerResult.uri) this.setState({ image: uploadUrl }) } } catch (e) { console.log(e) alert('Image Upload failed') } finally { this.setState({ uploading: false }) } }
Initially, set the state of
uploading to true. Then, if an image is selected, call the custom method
uploadImageAsync (which will be defined at the end of this section) and pass the URI of the image selected. This will also set the value of the
image from the state object to the URL of the uploaded image. Lastly, set the state of the
uploading in the
finally block back to false if the results are positive and the image has uploaded without any errors.
The custom method
uploadImageAsync has to be defined outside the
App component. It will upload the image by creating a unique image ID or blob with the help of
uuid. It uses
xhr to make an Ajax call to send a request to the Firebase storage to upload the image.() }
Note that the source code for accessing and uploading an image to Firebase is taken from this example of using Expo with Firebase.
Now you can add both the functions,
pickImage and
takePhoto as the value of
onPress props for the corresponding icons.
<Header statusBarProps={{ barStyle: 'light-content' }} </TouchableOpacity> } centerComponent={{ text: 'Not Hotdog?', style: styles.headerCenter }} rightComponent={ <TouchableOpacity onPress={this.takePhoto}> <Icon name="camera-alt" color="#fff" /> </TouchableOpacity> } />
Here is an example of accessing Camera roll.
Add functionality to determine a Hotdog
As most of the app is now set up, this section is going to be an interesting one. You are going to leverage the use of Google's Vision API to analyze whether the image provided by the user is a hot dog or not.
Inside the
App component, add a new method called
submitToGoogle. It is going to send requests and communicate with the API to fetch the result when a button is pressed by the user after the image has been uploaded. Again, while analyzing and fetching results, this method is going to set the state variable
uploading to true. Then, it will send the URI of the image from the state object's
image as the body of the request.
Along with the URI, the type of category you want to use is also defined along with a number of results it can fetch as a response. You can change the value of
maxResults for the
LABEL category. Currently, the value of the is set to
7. There are other detection categories provided by the Vision API other the one being used below,
LABEL_DETECTION, such as a human face, logo, landmark, text, and so on.
submitToGoogle = async () => { try { this.setState({ uploading: true }) let { image } = this.state let body = JSON.stringify({ requests: [ { features: [{ type: 'LABEL_DETECTION', maxResults: 7 }], image: { source: { imageUri: image } } } ] }) let response = await fetch( `{VISION_API_KEY}`, { headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, method: 'POST', body: body } ) let responseJson = await response.json() const getLabel = responseJson.responses[0].labelAnnotations.map( obj => obj.description ) let result = getLabel.includes('Hot dog') || getLabel.includes('hot dog') || getLabel.includes('Hot dog bun') this.setState({ googleResponse: result, uploading: false }) } catch (error) { console.log(error) } }
In the above snippet, the result is fetched in an array. Each array, in the current scenario, will have seven different objects. Using JavaScript's
map let us extract the value of
description from each object. All you need is to detect whether the description contains the word
hotdog or not. This is done in the variable
result. Lastly, the state of
uploading overlay is set back to false, and the result of whether the uploaded image contains a hot dog or not is going to update
googleResponse as boolean.
On a side note, the Vision API uses HTTP Post request as a REST API endpoint to perform data analysis on images you send in the request. This is done via the URL. To authenticate each request, you need the API key. The body of this POST request is in JSON format. For example:
{ "requests": [ { "image": { "content": "/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z" }, "features": [ { "type": "LABEL_DETECTION", "maxResults": 1 } ] } ] }
Display final results
Using the boolean value from
googleResponse, the end result is going to be output. The output will be displayed using
renderImage.
renderImage = () => { let { image, googleResponse } = this.state if (!image) { return ( <View style={styles.renderImageContainer}> <Button buttonStyle={styles.button} onPress={() => this.submitToGoogle()} title="Check" titleStyle={styles.buttonTitle} disabled /> <View style={styles.imageContainer}> <Text style={styles.title}>Upload an image to verify a hotdog!</Text> <Text style={styles.hotdogEmoji}>🌭</Text> </View> </View> ) } return ( <View style={styles.renderImageContainer}> <Button buttonStyle={styles.button} onPress={() => this.submitToGoogle()} title="Check" titleStyle={styles.buttonTitle} /> <View style={styles.imageContainer}> <Image source={{ uri: image }} style={styles.imageDisplay} /> </View> {googleResponse ? ( <Text style={styles.hotdogEmoji}>🌭</Text> ) : ( <Text style={styles.hotdogEmoji}>❌</Text> )} </View> ) }
The
Button component used above is from
react-native-elements library. It is going to be disabled until no image is selected. On its prop
onPress the handle function
submitToGoogle is called. The second view displays the image, and beneath it, an emoji is showcased whether the image has the desired result or not. Do note that by default the cross emoji will be showcased since the default value of
googleResponse is set to false when defining the initial state. Only after clicking the button, the emoji displayed is the final result.
Lastly, do not forget to add
renderImage inside
App component's
render method, just before the
UploadingOverlay component.
// inside the render method { this.renderImage() } { uploading ? <UploadingOverlay /> : null }
Here is a short demo of how the app looks and works on a real android device using Expo client to run the app.
Here is complete source code for
StyleSheet object.
const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#cafafe' }, headerCenter: { color: '#fff', fontSize: 20, fontWeight: 'bold' }, renderImageContainer: { marginTop: 20, alignItems: 'center' }, button: { backgroundColor: '#97caef', borderRadius: 10, width: 150, height: 50 }, buttonTitle: { fontWeight: '600' }, imageContainer: { margin: 25, alignItems: 'center' }, imageDisplay: { width: 300, height: 300 }, title: { fontSize: 36 }, hotdogEmoji: { marginTop: 20, fontSize: 90 } }) export default App
If you visit the storage section in Firebase, you can notice that each image is stored with a name of base64 binary string.
Conclusion
By integrating Firebase storage and using Google's Vision API with React Native, you have completed this tutorial. The API is amazing with endless use cases. I hope you learned a thing or two by reading this post. The complete source code for this app is available at this Github repo. Some of the resources used in this post:
- react-native-elements UI component library
- expo-image-picker
- firebase-storage-upload-example with expo
- Vision AI
Originally published at Heartbeat
I often write on Nodejs, Reactjs, and React Native. You can visit me on amanhimself.dev or you can subscribe to my weekly newsletter to receive all updates on new posts and content, straight in your inbox 💌.
Discussion (15)
This is great. I am building it tomorrow because I have never used the vision api and this is a perfect time to try it out
Thank you!!
Glad to know I got you interested in this :)
Ok so I tried this out like I said because I am a man of my word. And because I have never used expo before. This was great! React native are really fun I need to dig into the documentation and use it more.
The only issue is I keep getting an error in the uploadImageAsync method
_Firebase.default.storage is not a function. (In '_Firebase.default.storage()', '_Firebase.default.storage' is undefined)
I know it has to do with firebase storage permissions but I have been coding all day and am at the wall of not being productive anymore lol
I will have to edit this later so weirdos do not try to use my google cloud smh
Thanks and this was a great walkthrough!!!
Hi,
Have you tried using firebase SDK version @6.0.1 instead of 6.5.x?
Some of the Firebase issues I face are due to using latest SDK version instead of a stable one.
Good idea. i uninstalled and am trying with 6.0.1
Fingers crossed
wow am i seeing a lot of errors now. it did not like that at all. said i need to install react-native-icons
ok i did that and am trying to install 6.0.1 again.
it definitely made the terminal angry with all those errors lol
second try same thing many errors popped up and node is mad at me
i am so close yet so far!!
You can check the package.json for exact versions of deps in this repo github.com/amandeepmittal/not-hotd...
_Firebase.default.storage is not a function. (In '_Firebase.default.storage()', '_Firebase.default.storage' is undefined)
Unable to resolve "firebase" from "config\Firebase.js"
Yep i definitely broke it now i am so close now a little farther!
i want to see what is a hot dog and what is not :-(
Let me try to run your repo and see what I can do.
Ok everything is the same except the firebase dependency and "react-native-unimodules": "0.5.4",
I did a bare install so I needed to use the unimodules for the icons to work
If i have to restart with a managed install i will but not tonight! it is midnight now i have been writing code for over 14 hours
i will check back with you in the morning but check out my repo maybe you can work some magic
i will reply later in the day if you are available if you have any other suggestions.
Thanks for the help!
Thank you! i must sleep now will check back later
You will need to install deps like
uuidand
expo-permissionsto make it work. As I said before, please check the package.json file I am using and make sure you have all the dependencies installed if you are not modifying
App.jsfile on your own.
Just found your blogs. Planning to follow them for learning react native and also subscribed to your newsletter.
Thanks, Anant.
This is great. Thanks for sharing amazing react stuff. I love it. I will try it asap. | https://dev.to/amanhimself/build-a-not-hotdog-clone-with-react-native-367m | CC-MAIN-2021-31 | refinedweb | 3,876 | 57.37 |
exceptions.TypeError: must be encoded string without NULL bytes, not str
Hi,
I get this same exception every second in the console.log file (exception below). Could somebody point me in the right direction to fault find the problem?
I send about 300 metrics every 20 mins at present and they are not all getting recorded, so I think this error may be the cause of my problems.
Many thanks
14/08/2012 09:52:02 :: Sorted 1012 cache queues in 0.000527 seconds
14/08/2012 09:52:02 :: Unhandled Error
Traceback (most recent call last):
File "/usr/lib/
self.
File "/usr/local/
result = context.call(ctx, function, *args, **kwargs)
File "/usr/local/
return self.currentCon
File "/usr/local/
return func(*args,**kw)
--- <exception caught here> ---
File "/opt/graphite/
writeCached
File "/opt/graphite/
for (metric, datapoints, dbFilePath, dbFileExists) in optimalWriteOrd
File "/opt/graphite/
dbFileExists = exists(dbFilePath)
File "/usr/lib/
os.stat(path)
exceptions.
Question information
- Language:
- English Edit question
- Status:
- Solved
- For:
- Graphite Edit question
- Assignee:
- No assignee Edit question
- Solved by:
- Mike Wylie
- Solved:
- 2012-09-07
- Last query:
- 2012-09-07
- Last reply:
- 2012-08-16
Hi thank you for the advice, it sounds sensible.
I altered my script that sends the metrics, so that it logged them all in a file. I have about 2.5k metrics and I've played with them with grep and excel and so far I can't find any problems with the metrics in the file?
I stopped sending metrics when I created this question (around 2 days ago), but the console.log file is still filling with one exception per second. Could it be stuck trying to do something?
Many thanks
PS I'm off on a 2 week holiday tomorrow, so my apologies if my reply is delayed
I had a look at the code in the exception trace and had a though....would I be taking my life in my hands if I altered the file /opt/graphite/
Would I need to restart something for the code to take affect?
I'm not a real python programmer, but I can understand the basics, I was thinking something along the lines of:
def optimalWriteOrd
"Generates metrics with the most cached values first and applies a soft rate limit on new metrics"
global lastCreateInterval
global createCount
metrics = MetricCache.
t = time.time()
metrics.
log.msg("Sorted %d cache queues in %.6f seconds" % (len(metrics), time.time() - t))
for metric, queueSize in metrics:
if state.cacheTooFull and MetricCache.size < CACHE_SIZE_
events.
# -------
# my new piece of code
#
log.
# -------
dbFilePath = getFilesystemPa
dbFileExists = exists(dbFilePath)
Null characters wont show with grep - you may want to try catting the file with cat -e which will display null characters as ^@
The log statement is fine - you may want to add another log message after the dbFileExists statement below it since that's the line it's going to blow up at if there are nulls.
I'm back from my holiday and working on this problem again.
I implemented the above logging which gave me some confusing results. The log message clearly shows some bad characters in the directory name:
¬ítúuk.
The text should start with "uk". However, I had shutdown carbon, restarted it and left it running for a while, then sent some values, but not the value above.
Basically the log files were clean for a few hours, then started getting this error for a metric I hadn't sent.
There was also an error for a metric I had sent, but I'm not sure if that's related:
¬ítQàuk.
I also log all the metrics to a test file at the same time as sending to graphite, these bad characters do not exist in the log file.
So I have 2 questions.
1) Is there a file of cached values I need to clear out, before running my tests
2) Is there some way anyone can see how I get these bad characters in the metric names?
Many thanks
I have a solution. To be clear there was no fault with the graphite tools either.
My code to send data to graphite is written in Jython and there were some problems with standard python code so the guy setting it up for me resorted to java and used an ObjectOutputStream to send the data.
It's taken me a while to figure it out, but ObjectOutput stream sends the text as an object, and must add a little binary padding at the start of my metrics, causing all of my problems. I swapped out to using a Java PrintWriter, which is specifically for text and hey presto. My metrics are now clean.
Thanks for the help Michael, you gave me enough to crack it in the end.
Carbon converts the metric name into a filesystem path with just a substitution:
settings. LOCAL_DATA_ DIR, metric. replace( '.','/' )) + '.wsp'
join(
os.path.exists() is complaining of a null byte so there must be a null byte getting sent in one of your metric names | https://answers.launchpad.net/graphite/+question/205774 | CC-MAIN-2019-18 | refinedweb | 839 | 71.55 |
Python alternatives for PHP functions
import csv
import io
def str_getcsv(string, delimiter=',', enclosure='"', escape='\\'):
with io.StringIO(string) as f:
reader = csv.reader(f, delimiter=delimiter, quotechar=enclosure, escapechar=escape)
return next(reader)
(PHP 5 >= 5.3.0)
str_getcsv —
Parse a CSV string into an array
Similar to fgetcsv() this functions parses a
string as its input unlike fgetcsv() which
takes a file as its input.
The string to parse.
Set the field delimiter (one character only). Defaults as a comma.
Set the field enclosure character (one character only). Defaults as a
double quotation mark.
Set the escape character (one character only). Defaults as a backslash
(\)
Returns an indexed array containing the fields read. | http://www.php2python.com/wiki/function.str-getcsv/ | CC-MAIN-2020-29 | refinedweb | 115 | 61.83 |
You might have heard of many different Deep Learning frameworks such as TensorFlow and PyTorch. They do everything for Deep Learning! You probably do NOT need any other framework! BUT…
Google Brain believes otherwise! In this tutorial, you become familiar with Trax and the motivations behind its development.
Trax uses the JAX library. It provides high-performance computing! According to Google, “JAX uses XLA to compile and run your NumPy programs on GPUs and TPUs.” Such implementation can significantly improve the performance of Trax.
Google built JAX that makes high-performance accelerator code from Python and Numpy. It connects Autograd and XLA for high-performance machine learning research. Autograd assists JAX to distinguish native Python and Numpy. XLA compiler optimizes TensorFlow computations, and JAX uses it to run NumPy operations on GPU and TPU.
Working with Trax
Here you become familiar with how to start with Trax and learn some basic functionalities. Let’s get started.
Installing Trax
Installing Trax could not be more comfortable! I suggest to install it in a python virtual environment. For further details, you can refer to the following post:
Now let’s assume you installed the virtual environment and activated it. Simply run the following in the command line:
pip install trax
You can do the following if you want to install a specific version:
pip install trax==x.x
where x.x is your desired version!
Trax Layers
First, let’s import layers to work with. As usual, we will import NumPy as well. You can investigate the full list of layers in the official documentation (layer section).
import numpy as np from trax import layers as ly
The ‘ly’ is a placeholder for the layers building block.
Activation Layers
Let’s define a Sigmoid activation function with Trax:
# Make a sigmoid activation layer # Sigmoid is of type trax.layers.base.PureLayer # Ref: sigmoid = ly.activation_fns.Sigmoid() # Some attributes print("name :", sigmoid.name) print("weights :", sigmoid.weights) print("# of inputs :", sigmoid.n_in) print("# of outputs :", sigmoid.n_out)
Above, we showcased some of the attributes. The attributes in the trax.layers.base.PureLayer object.
Combinators
We use combinators to composes layers (1) serially or (2) in parallel.
To compose layers serially, we use trax.layers.combinators.Serial. You can think of it as a simple neural network with multiple layers stacked together. An example would be as follows:
# Composing layers serially stacked_layers = ly.Serial( ly.LayerNorm(), ly.Relu(), ly.Dense(n_units=2), ly.LogSoftmax()) print("name :", stacked_layers.name) print("weights:", stacked_layers.weights) print("sublayers :", stacked_layers.sublayers) print("expected inputs :", stacked_layers.n_in) print("promised outputs :", stacked_layers.n_out)
You can learn more with the useful help function:
help(ly.Serial)
Above, create to the following output:
Help on class Serial in module trax.layers.combinators: class Serial(trax.layers.base.Layer) | Serial(*sublayers, name=None, sublayers_to_print=None) | | Combinator that applies layers serially (by function composition). | | This combinator is commonly used to construct deep networks, e.g., like this:: | | mlp = tl.Serial( | tl.Dense(128), | tl.Relu(), | tl.Dense(10), | tl.LogSoftmax() | ) | | A Serial combinator uses stack semantics to manage data for its sublayers. | Each sublayer sees only the inputs it needs and returns only the outputs it | has generated. The sublayers interact via the data stack. For instance, a | sublayer k, following sublayer j, gets called with the data stack in the | state left after layer j has applied. The Serial combinator then: | | - takes n_in items off the top of the stack (n_in = k.n_in) and calls | layer k, passing those items as arguments; and | | - takes layer k's n_out return values (n_out = k.n_out) and pushes | them onto the data stack. | | A Serial instance with no sublayers acts as a special-case (but useful) | 1-input 1-output no-op. | | Method resolution order: | Serial | trax.layers.base.Layer | builtins.object | | Methods defined here: | | __init__(self, *sublayers, name=None, sublayers_to_print=None) | Creates a partially initialized, unconnected layer instance. | | Args: | n_in: Number of inputs expected by this layer. | n_out: Number of outputs promised by this layer. | name: Class-like name for this layer; for use when printing this layer. | sublayers_to_print: Sublayers to display when printing out this layer; | By default (when None) we display all sublayers. | | forward(self, xs) | Computes this layer's output as part of a forward pass through the model. | | Authors of new layer subclasses should override this method to define the | forward computation that their layer performs. Use `self.weights` to access | trainable weights of this layer. If you need to use local non-trainable | state or randomness, use `self.rng` for the random seed (no need to set it) | and use `self.state` for non-trainable state (and set it to the new value). | | Args: | inputs: Zero or more input tensors, packaged as described in the `Layer` | class docstring. | | Returns: | Zero or more output tensors, packaged as described in the `Layer` class | docstring. | | init_weights_and_state(self, input_signature) | Initializes weights and state for inputs with the given signature. | | Authors of new layer subclasses should override this method if their layer | uses trainable weights or non-trainable state. To initialize trainable | weights, set `self.weights` and to initialize non-trainable state, | set `self.state` to the intended value. | | Args: | input_signature: A `ShapeDtype` instance (if this layer takes one input) | or a list/tuple of `ShapeDtype` instances; signatures of inputs. | | ---------------------------------------------------------------------- | Methods inherited from trax.layers.base.Layer: | | __call__(self, x, weights=None, state=None, rng=None) | Makes layers callable; for use in tests or interactive settings. | | This convenience method helps library users play with, test, or otherwise | probe the behavior of layers outside of a full training environment. It | presents the layer as callable function from inputs to outputs, with the | option of manually specifying weights and non-parameter state per individual | call. For convenience, weights and non-parameter state are cached per layer | instance, starting from default values of `EMPTY_WEIGHTS` and `EMPTY_STATE`, | and acquiring non-empty values either by initialization or from values | explicitly provided via the weights and state keyword arguments. | | Args: | x: Zero or more input tensors, packaged as described in the `Layer` class | docstring. | weights: Weights or `None`; if `None`, use self's cached weights value. | state: State or `None`; if `None`, use self's cached state value. | rng: Single-use random number generator (JAX PRNG key), or `None`; | if `None`, use a default computed from an integer 0 seed. | | Returns: | Zero or more output tensors, packaged as described in the `Layer` class | docstring. | | __repr__(self) | Return repr(self). | | backward(self, inputs, output, grad, weights, state, new_state, rng) | Custom backward pass to propagate gradients in a custom way. | | Args: | inputs: Input tensors; can be a (possibly nested) tuple. | output: The result of running this layer on inputs. | grad: Gradient signal computed based on subsequent layers; its structure | and shape must match output. | weights: This layer's weights. | state: This layer's state prior to the current forward pass. | new_state: This layer's state after the current forward pass. | rng: Single-use random number generator (JAX PRNG key). | | Returns: | The custom gradient signal for the input. Note that we need to return | a gradient for each argument of forward, so it will usually be a tuple | of signals: the gradient for inputs and weights. | | init(self, input_signature, rng=None, use_cache=False) | Initializes weights/state of this layer and its sublayers recursively. | | Initialization creates layer weights and state, for layers that use them. | It derives the necessary array shapes and data types from the layer's input | signature, which is itself just shape and data type information. | | For layers without weights or state, this method safely does nothing. | | This method is designed to create weights/state only once for each layer | instance, even if the same layer instance occurs in multiple places in the | network. This enables weight sharing to be implemented as layer sharing. | | Args: | input_signature: `ShapeDtype` instance (if this layer takes one input) | or list/tuple of `ShapeDtype` instances. | rng: Single-use random number generator (JAX PRNG key), or `None`; | if `None`, use a default computed from an integer 0 seed. | use_cache: If `True`, and if this layer instance has already been | initialized elsewhere in the network, then return special marker | values -- tuple `(GET_WEIGHTS_FROM_CACHE, GET_STATE_FROM_CACHE)`. | Else return this layer's newly initialized weights and state. | | Returns: | A `(weights, state)` tuple. | | init_from_file(self, file_name, weights_only=False, input_signature=None) | Initializes this layer and its sublayers from a pickled checkpoint. | | In the common case (`weights_only=False`), the file must be a gziped pickled | dictionary containing items with keys `'flat_weights', `'flat_state'` and | `'input_signature'`, which are used to initialize this layer. | If `input_signature` is specified, it's used instead of the one in the file. | If `weights_only` is `True`, the dictionary does not need to have the | `'flat_state'` item and the state it not restored either. | | Args: | file_name: Name/path of the pickeled weights/state file. | weights_only: If `True`, initialize only the layer's weights. Else | initialize both weights and state. | input_signature: Input signature to be used instead of the one from file. | | output_signature(self, input_signature) | Returns output signature this layer would give for `input_signature`. | | pure_fn(self, x, weights, state, rng, use_cache=False) | Applies this layer as a pure function with no optional args. | | This method exposes the layer's computation as a pure function. This is | especially useful for JIT compilation. Do not override, use `forward` | instead. | | Args: | x: Zero or more input tensors, packaged as described in the `Layer` class | docstring. | weights: A tuple or list of trainable weights, with one element for this | layer if this layer has no sublayers, or one for each sublayer if | this layer has sublayers. If a layer (or sublayer) has no trainable | weights, the corresponding weights element is an empty tuple. | state: Layer-specific non-parameter state that can update between batches. | rng: Single-use random number generator (JAX PRNG key). | use_cache: if `True`, cache weights and state in the layer object; used | to implement layer sharing in combinators. | | Returns: | A tuple of `(tensors, state)`. The tensors match the number (`n_out`) | promised by this layer, and are packaged as described in the `Layer` | class docstring. | | weights_and_state_signature(self, input_signature) | Return a pair containing the signatures of weights and state. | | ---------------------------------------------------------------------- | Data descriptors inherited from trax.layers.base.Layer: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | has_backward | Returns `True` if this layer provides its own custom backward pass code. | | A layer subclass that provides custom backward pass code (for custom | gradients) must override this method to return `True`. | | n_in | Returns how many tensors this layer expects as input. | | n_out | Returns how many tensors this layer promises as output. | | name | Returns the name of this layer. | | rng | Returns a single-use random number generator without advancing it. | | state | Returns a tuple containing this layer's state; may be empty. | | If the layer has sublayers, the state by convention will be | a tuple of length `len(sublayers)` containing sublayer states. | Note that in this case self._state only marks which ones are shared. | | sublayers | Returns a tuple containing this layer's sublayers; may be empty. | | weights | Returns this layer's weights. | | Depending on the layer, the weights can be in the form of: | | - an empty tuple | - a tensor (ndarray) | - a nested structure of tuples and tensors | | If the layer has sublayers, the weights by convention will be | a tuple of length `len(sublayers)` containing the weights of sublayers. | Note that in this case self._weights only marks which ones are shared.
You can see help gives you great deal of information!
Of course, you can compose layers in parallel too! It can be done by trax.layers.combinators.Parallel. The layers that were paralleled together will be applied to a series of inputs based on determining which layer takes how many inputs and the results are going to be concatenated together.
For example, suppose one has two layers in parallel and we expect the following number of inputs and outputs for each:
- A: 1 input and 1 output.
- B: 2 inputs and 3 output.
Then the Parallel(A, B) object has:
- inputs:
Another good example can be found in the official documentation.
Custom Layer
You can define a custom layer with trax.layers.base.Fn. It can be define as follows:
def Custom_layer(): # Set a name layer_name = "custom_layer" # Custom function def func(x): return x + x^2 return ly.base.Fn(layer_name, func) # Create layer object custom_layer = Custom_layer() # Check properties print("name :", custom_layer.name) print("expected inputs :", custom_layer.n_in) print("promised outputs :", custom_layer.n_out) # Inputs x = np.array([0, -1, 1]) # Outputs print("outputs :", custom_layer(x))
That lead to the following output:
name : custom_layer expected inputs : 1 promised outputs : 1 outputs : [ 2 -4 0]
Ok, that was a brief overview of Trax layers with some examples. Feel free to explore more!
Conclusion
In this tutorial, I talked about Trax, the new Google Brain Deep Learning framework. Here, some of the main advantages of Trax and its high-level structure was described. In future tutorials, I will go through how to train a neural network with Trax in a real-world application.
Stay tuned and feel free to comment below if you have any questions and point of view. | https://www.machinelearningmindset.com/trax-google-brain-deep-learning/ | CC-MAIN-2021-04 | refinedweb | 2,195 | 58.99 |
C++ Condition Statements
The if statement
The if statement can cause other statements to execute only under certain conditions. You might think of the statements in a procedural program as individual steps taken as you are walking down a road. To reach the destination, you must start at the beginning and take each step, one after the other, until you reach the destination.
Program below illustrates the use of an if statement. The user enters three test scores and the program calculates their average. If the average equals 100, the program congratulates the user on earning a perfect score.
#include <iostream.h> #include <iomanip.h> using namespace std; int main() { int score1, score2, score3; double average; // Get the three test scores cout << "Enter 3 test scores and I will average them: "; cin >> score1 >> score2 >> score3; // Calculate and display the average score average = (score1 + score2 + score3) / 3.0; cout << fixed << showpoint << setprecision(1); cout << "Your average is " << average << endl; // If the average equals 100, congratulate the user if (average == 100) { cout << "Congratulations! "; cout << "That's a perfect score!\n"; } return 0; }
Output: Enter 3 test scores and I will average them: 80 90 70 Your average is 80.0 Output (if average==100): Enter 3 test scores and I will average them: 100 100 100 Your average is 100.0 Congratulations! That's a perfect score!
The if else statement
The if else statement will execute one set of statements when the if condition is true, and another set when the condition is false.The if...else statement is an expansion of the if statement.
This program uses the modulus operator to determine if a number is odd or even. If the number is evenly divisible by 2, it is an even number. A remainder indicates it is odd.
#include <iostream.h> #include <iomanip.h> using namespace std; int main() { int number; cout << "Enter an integer and I will tell you if it\n"; cout << "is odd or even. "; cin >> number; if (number % 2 == 0) cout << number << " is even.\n"; else cout << number << " is odd.\n"; return 0; }
Output: Enter an integer and I will tell you if it is odd or even. 17 17 is odd
The else part at the end of the if statement specifies one or more statements that are to be executed when the condition is false.
When number % 2 does not equal 0, a message is printed indicating the number is odd. Note that the program will only take one of the two paths in the if...else statement.
Ads Right | https://www.infocodify.com/cpp/if-else-condition-statements | CC-MAIN-2020-45 | refinedweb | 426 | 64 |
Constructors are similar to methods and are different in the following sense.
They do not have any return type.
The name of the constructor is the same as the name of the class.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
A class can have more than one constructor.
class A { public int a; //default constructor public A() { this(-1); } //parameterized constructor public A(int a) { this.a = a; } } public class Tester { public static void main(String[] args) { //new object created using default constructor A a1 = new A(); System.out.println(a1.a); //new object created using parameterized constructor A a2 = new A(1); System.out.println(a2.a); } }
-1 1 | https://www.tutorialspoint.com/Constructors-in-Java | CC-MAIN-2021-43 | refinedweb | 143 | 59.5 |
After the router is powered off and restarted, how does eap8266 automatically connect to the wifi and blynk servers?
(Make) ESP8266 automatically connect to the wifi and blynk servers (after disconnection)
By reading the documentation and searching the forum for solutions
I have encountered the same problem. After the router is powered off and restarted, how does eap8266 automatically connect to the wifi and blynk servers? Please help me, thank you very much!
And since you already have a topic about this, please do not post the same question in other, older, topics. Thanks.
PS I moved your post back here.
Thanks a lot, I tried your code, but it doesn’t work. Is there a problem here? " timer.setTimeout(30000L, { . . .
Mainly used these codes:
- List item
#define BLYNK_PRINT Serial // This prints to Serial Monitor
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
char auth[] = “xxxxxxxxxx”;
char ssid[] = “xxxxxxxxxx”;
char pass[] = “xxxxxxxxxx”;
//char server[] = “xxx.xxx.xxx.xxx”; // IP for Local Cloud Server
char server[] = “blynk-cloud.com”; // URL for Blynk Cloud Server
int port = 8080;
int ReCnctFlag; // Reconnection Flag
int ReCnctCount = 0; // Reconnection counter
BlynkTimer timer;
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT);
WiFi.begin(ssid, pass); // Non-blocking if no WiFi available
Blynk.config(auth, server, port);
Blynk.connect();
}
BLYNK_CONNECTED() {
Serial.println(“Cconnected”);
ReCnctCount = 0;
}
void loop() {
timer.run();
if (Blynk.connected()) { // If connected run as normal
Blynk.run();
} else if (ReCnctFlag == 0) { // If NOT connected and not already trying to reconnect, set timer to try to reconnect in 30 seconds
ReCnctFlag = 1; // Set reconnection Flag
Serial.println(“Starting reconnection timer in 30 seconds…”);
timer.setTimeout(30000L, { // Lambda Reconnection Timer Function
ReCnctFlag = 0; // Reset reconnection Flag
ReCnctCount++; // Increment reconnection Counter
Serial.print(“Attempting reconnection #”);
Serial.println(ReCnctCount);
Blynk.connect(); // Try to reconnect to the server
}); // END Timer Function
}
}
Why are you reposting the same code I gave you the link for?? And posting it UNformatted as well
I tried your code, but it doesn’t work.
hello , I used their code, but if the channels are active during a disconnection of the network, they are still active, ideally disconnecting the channel from the relay with the network | https://community.blynk.cc/t/make-esp8266-automatically-connect-to-the-wifi-and-blynk-servers-after-disconnection/32301/2 | CC-MAIN-2022-21 | refinedweb | 358 | 59.3 |
This action might not be possible to undo. Are you sure you want to continue?
05/29/2014
text
original
Creating a Web Form Write programs with corresponding output screens to demonstrate the above concepts. a) WEB FORM LIFE CYCLE: • Initialize: Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized. • Load View State: The View State property of the control is populated. The View State information comes from a hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the View State property is set. This can be modified via the LoadViewState ( ) method: This allows ASP.NET to manage the state of your control across page loads. So that each control is not reset to its default state each time the page is posted. • Process Postback Data: During this phase, the data sent to the server in the posting is processed. If any of this data results in a requirement to update the View State, that update is performed via the LoadPostData ( ) method. • Load: CreateChildControls ( ) is called, if necessary, to create and initialize server controls in the control tree. State is restored, and the form controls show client-side data. You can modify the load phase by handling the Load event with the OnLoad method. • Send Postback Change Modifications: If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent ( ) method. • Handle Postback Events: The client-side event that caused the postback is handled. • PreRender: This is the phase just before the output is rendered to the browser. It is essentially your last chance to modify the output prior to rendering using the OnPreRender ( ) method. • Save State:. • Render: This is where the output to be sent back to the client browser is generated. You can override it using the Render method. CreateChildControls ( ) is called, if necessary, to create and initialize server controls in the control tree. • Dispose: This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections. You can modify it using the Dispose ( ) method. • b) CREATING A WEB FORM To create the simple Web Form that will be used in the above example, go to the option start up Visual Studio .NET and open a New Project named ProgrammingCSharpWeb. Select the Visual C# Projects folder (because C# is your language of choice), select ASP.NET Web Application as the project type, and type in its name, ProgrammingCSharpWeb.. The code-behind file does not appear in the Solution Explorer. To see the code behind (.cs) file, you must place the cursor within Visual Studio .NET, right-click the form, and choose "View Code" in the pop-up menu. You can now tab back and forth between the forms. code-behind files: Start by renaming WebForm1.aspx to HelloWeb.aspx. To do this, close WebForm1.aspx,and then right-click its name in the Solution Explorer. Choose Rename and enter the name HelloWeb.aspx. After renaming it, open HelloWeb.aspx and view the code; it is seen that code-behind file has been renamed as well to HelloWeb.aspx.cs.When you create a new Web Form application, Visual Studio .NET will generate a bit of boilerplate code to get you started, as shown below: <%@ Page language="c#" Codebehind="HelloWeb.aspx.cs" AutoEventWireup="false" Inherits="ProgrammingCSharpWeb.WebForm1" %>
the browser and Web server are disconnected.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content=". as explained later in the section "Cookies and Session State. if you try to store more.<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. the browser stores all the cookies separately. Most browsers allow only 20 cookies per site. more browsers will accept cookies from your site. when a user visits your site. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials. all relating to helping the Web site remember users. Cookies help Web sites store information about visitors. presenting pertinent identification that helps an application know how to proceed.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7. If you define a P3P privacy policy and place it in the root of your Web site. Generally.NET Introduction: Cookies provide a means in Web applications to store user-specific information. For example. an identifier such as a user ID. Many times. Cookie Limitations: • • Most browsers support cookies of up to 4096 bytes. usually 300. you might have to avoid cookies altogether and use a different mechanism to store user-specific information. you can use cookies to store user preferences or other information. Because of this small limit. A cookie therefore acts as a kind of calling card. Browsers also impose limitations on how many cookies your site can store on the user's computer. the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. of performing state management. For example. cookies are best used to store small amounts of data. Cookies are associated with a Web site. A common method for storing user information is session state. A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. on the number of cookies they will accept from all sites combined. the oldest cookies are discarded. Describe the following with respect to State Management in ASP. cookies are one way of maintaining continuity in a Web application—that is. however. the application can retrieve the information it stored earlier. Session State c. Except for the brief time when they are actually exchanging information. not with a specific page. Cookies in ASP. Some browsers also put an absolute limit.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> </form> </body> </html> Run the page by pressing Ctrl-F5 (or save it and navigate to it in your browser). However.Net: a. When the user visits your Web site another time. Users can set their browser to refuse cookies." • Writing Cookies . so the browser and server will exchange cookie information no matter what page the user requests from your site. a site conducting a poll might use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. it's useful for the Web server to recognize users when they request a page. each site might send a cookie to the user's browser as well. Cookies are used for many purposes. For example. or better yet. The cookie contains information the Web application can read whenever the user visits the site. but session state depends on cookies. As the user visits different sites.microsoft. Application State a)COOKIES IN ASP. Each request a user makes to a Web server is treated independently of any other request.NET b. 2.
Response. A session is considered active as long as requests continue made with the same SessionID value. If no SessionID value is supplied.NET worker process. and so on) can be a challenge.NET session-state variables are easily set and retrieved using the Session property. Session Variables: Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext: Session property.Cookies ["userName"]. Each cookie must have a unique name so that it can be identified later when reading it from the browser.NET page.NET application. the cookie is created but it is not stored on the user's hard disk. aCookie.AddDays (1). meaning that your Web server treats each HTTP request for a page as an independent request. HTTP is a stateless protocol. you specify a Name and Value. You can access the HttpResponse object as the Response property of your Page class. building Web applications that need to maintain some cross-request state information (applications that implement shopping carts. ASP. the cookie is discarded. Instead.NET page for the first and last name of a user. Any cookies that you want to send to the browser must be added to this collection. you can also configure the application to store SessionID values in the URL for a "cookieless" session. store session information using a stand-alone service so that session information is preserved if the ASP.NET Framework type.NET applications. Because cookies are stored by name. The collection of session variables is indexed by the name of the variable or by an integer index. the session is considered expired. Session Events: . by default. in a SQL Server so that session information is available to multiple Web servers in a Web farm (and also persists if the ASP. Session Modes:ASP. Response.NET application by default. in a SQL Server database. Cookies are sent to the browser via the HttpResponse object that exposes a collection called cookies. The following example shows the method using C# code to write cookies: Response.Expires = DateTime. In an ASP. The following example shows how to create session variables in an ASP.NET stores session information in the memory space of the ASP.NET application is restarted. you can set the session mode to Off.The browser is responsible for managing cookies on a user system. which stores session variable values as a collection indexed by name. b) SESSION STATEASP. The default behavior is to store session variables in the memory space of the ASP. HttpCookieaCookie = new HttpCookie ("lastVisit"). However.Cookies.Now.Now.Now. and provides the ability to persist variable values for the duration of that session. or in a custom data store. or in a custom data source.NET pages that make up a Web application.NET application is restarted). As a result.Cookies ["userName"]. ASP. Each option is identified as a session-state Mode type. the current session variables are exposed through the Session property of the Page object. ASP. you can also specify that session state should be stored in a separate process. If you do not set the cookie's expiration. We can optionally. ASP. When session state is enabled for an ASP. Session variables can be any valid . If the time between requests for a particular session exceeds the specified time-out value in minutes.Expires = DateTime.to be ASP. Session Identifiers:Sessions are identified by a unique identifier that can be read by using the SessionID property. SessionID values are stored in a cookie. However.Add (aCookie). and set them to values retrieved from TextBox controls.AddDays (1). You can add cookies to the Cookies collection in a number of ways. If you do not want session state enabled for your application. Session variables are created by referring to the session variable by name. aCookie. When creating a cookie.NET starts a new session and the SessionID value for that session is sent to the browser with the response. data scrolling.Value = "patrick". When the user closes the browser. You do not have to declare a session variable or explicitly add it to the collection.NET session state is enabled by default for all ASP.Value = DateTime.NET also provides several other options for persisting data within an application besides session state. Requests made with an expired SessionID value result in a new session. ASP. the cookie is maintained as part of the user's session information. naming two cookies the same will cause one to be overwritten. By default.NET session state identifies requests received from the same browser during a limited period of time as a session. each request for a page in the application is examined for a SessionID value sent from the browser.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.ToString (). the server retains no knowledge of variable values used during previous requests.NET session state supports several storage options for session variables.
you do so in a thread-safe manner by including built-in synchronization support.NET provides two events that help you manage user sessions. Supporting values that are based on the session Mode setting.NET application. such as a database. If your application runs in multi-processor or multi-server environments.Net: a. c)APPLICATION STATE Application state is a data repository available to all classes in an ASP. we can add objects to the StaticObjects collection via an <object runat="server"> declaration in your Web application's Global. Application state defined in this way can then be accessed from code anywhere in your application.NET application. which is specific to a single user session. which is the default mode. It sets the Timeout value to 30 minutes. The sessionStateelement enables you to specify the following options: • The mode in which the session will store data.Integrated Security=SSPI.asax file. <sessionState mode="SQLServer" cookieless="true” We can disable session state for an application by setting the session-state mode to off. Configuring Session State Session state is configured by using the sessionState element of the system. 3. access. as in a Web farm. you must be aware of the following important considerations: • Resources: Because it is stored in memory. • Concurrency: Application state is free-threaded. Therefore. Your application therefore cannot rely on application state containing the same data for application state across different servers or processes. Describe the following with respect to Web Services in .
It’s easy to write Web services. At a minimum.NET Framework SDK (and that is integrated into Visual Studio .NET displays a page that you can use to test the Add method (Figure 8.NET HTTP handler) in Machine. Web service classes can be attributed with optional WebService attributes. The name and description in the ASMX file’s WebService attribute appear at the top of the page.NET Framework class library (FCL) and a codegenerator named Wsdl.7).a) WRITING AND TESTING A WEB SERVICE b) Writing a Web Service: The ASMX file shown in Figure below. If you put Calc. Calc. near the top of the page.NET (specifically. You can build helper methods into a Web service – methods that are used internally by Web methods but that are not exposed as Web methods themselves – by omitting the attribute. to an ASP. ASP.asmx in his or her browser. the Web service’s local URL is. Copy Calc. Click ―Add. The proxy insulates you from the low-level details of the Web service and of the protocols that it uses. c) IMPLEMENTING A WEB SERVICE CLIENTS: Web service clients – that is. The one in this example assigns the Web service a name and a description that show up in the HTML page generated when a user calls up Calc.asmx in wwwroot. Writing Web service clients is even easier.asmx. The methods in the proxy class mirror the Web methods in the Web service. The WebService attribute also supports a Namespace parameter that can be used to change the name of the XML namespace that scopes the Web service’s members. The Wsdl.NET Framework: • • • Web services are implemented in ASMX files.asmxin the browser’s address bar.asmx. and ASP. They also let you explore a Web service built with the . the proxy packages up the input parameters and invokes the Web method using the protocol encapsulated in the proxy (typically SOAP). The XML returned by the Web method appears in a separate browser window The forms that ASP.exe utility that comes with the . applications that use.net/terraservice. A Web service proxy is an object that provides a local representation of a remote Web service. It even generates an HTML form that you can use to call the Add method with your choice of inputs. You’ll learn more about Description and other WebMethod parameters in the section entitled ―The WebMethod AttributeTesting a Web Service: • For testing an ASMX Web service. The WebMethod attributes in Figure 8. the directive must contain a Class attribute identifying the class that makes up the Web service. .asmx by generating an HTML page that describes the Web service.NET knows the method name and signature because it reads them from the metadata in the DLL it compiled from Calc.NET responded to the HTTP request for Calc. type the following URL into your browser’s address bar: to wwwroot and type. For kicks.NET generates on the fly from ASMX files enable you to test the Web services that you write without writing special clients to test them with. ASP. Web Service Proxies: The key concept to grasp when writing Web service clients is that of the Web service proxy.asmx That’s the URL of the Microsoft TerraService. A proxy is instantiated in the client’s own application domain. ASMX is a special file name extension registered to ASP. It implements two Web methods: Add and Subtract. If you have a WSDL contract describing a Web service (or the URL of a DISCO file that points to a WSDL contract). complete with the descriptions spelled out in the WebMethod attributes. an ultra-cool Web service that provides a programmatic interface to a massive database of geographic data known as the Microsoft TerraServer.config. Web methods are declared by tagging public methods in the Web service class with WebMethod attributes. ASMX files begin with @ WebService directives. call it in the browser. but calls to the proxy flow through the proxy and out to the Web service that the proxy represents.NET) generates Web service proxy classes from WSDL contracts. User will be greeted as shown in the figure.asmx demonstrates several important principles of Web service programming using the . If the Web service exposes Web methods named Add and Subtract. thanks to some high-level support lent by the .5 also assign descriptive text to their Web methods. the Web service proxy also contains methods named Add and Subtract.NET Framework simply by pointing your browser to it. Web methods. Underneath is a list of Web methods that the service exposes. Both take two integers as input and return an integer as well. When you call one of these methods. Deploying the Web service is as simple as copying it to a directory on your Web server that is URLaddressable. or consume. Type 2 and 2 into the ―a‖ and ―b‖ boxes and click Invoke. It even parses the XML that comes back and makes the result available as managed types.
asmx".cs and enter the code in Figure. } If the Web service moves.com/calc.cs.com/calc.com/calc. you can use Wsdl.asmx produces the following class constructor: publicCalculatorWebService() { stringurlSetting = System. If you installed Calc.Simple Web Service Client:To write a client.asmx" /> </appSettings> </configuration> . you’ll have to modify the CS file and regenerate the proxy.exe to create a proxy class for Calc.cs "Calculator Web Service.cs" Run CalcClient.asmx".WriteLine ("2 + 2 = " + sum).asmx.asmx in wwwroot.Url = urlSetting. } } Avoiding Hard-Coded Service URLs: Look through a CS file generated by Wsdl. CalcClient.exe.wintellect.cs using System.wintellect. and you’ll see the Web service proxy class as well as the methods that wrap the Web service’s Web methods.wintellect.Configuration. The resulting output proves beyond the shadow of a doubt that Calc.config file. classMyApp { public static void Main () { CalculatorWebServicecalc = new CalculatorWebService (). } } Now you can assign a value to ―CalcUrl‖ in the appSettings section of a local Web.exe responds by creating a file named Calculator Web Service.asmx Wsdl. 2). the proper command is wsdl. You’ll also see that the Web service’s URL is hardcoded into the CS file in the proxy’s class constructor.exe instantiates a Web service proxy and calls the service’s Add method. The command wsdl /urlkey:CalcUrl["CalcUrl"]. Eg: publicCalculatorWebService() { this. To avoid having to update code when a Web service’s URL changes. } else { this.ConfigurationSettings. if ((urlSetting != null)) { this.wintellect. like so: <configuration> <appSettings> <add key="CalcUrl" value=" is smart enough to add 2 and 2 CalcClient. • Create a new text file named CalcClient. • • Compile the CS files into a console application with the following command: cscCalcClient.exe. following are the steps: • Use Wsdl. int sum = calc.exe’s /appsettingurlkey (abbreviated /urlkey) switch.com/calc.Url = " (2.Url = ". Console.
• • • For enhanced security. This isolates the test version of the application. to a set of worker processes) that service a group of applications. if you want to configure an application to run with its own unique set of properties. and ensure that your applications remain available even when a worker process serving an application pool is recycled because of a faulty application.0 is available only when running in worker process isolation mode.NET Framework version 1.NET APPLICATIONS Deploying ASP. you can make your server more efficient and reliable.1 of the .NET applications on a newly installed Web server requires no understanding of earlier versions of IIS or the .0 (IIS 6.0 metabase properties. process boundaries separate each worker process from other worker processes so that when an application is routed to one application pool. Deploying ASP.config and Web. In an application pool. reliable.0) b.NET Framework. If there is a test version of an application on the same server with the production version of the application. Version 1. except for the <processModel>section of the Machine.0.0. By creating new application pools and assigning Web sites and applications to them.NET Framework is installed with Windows Server 2003.1 with the operating system installation. in the case of a Web garden. separate the two versions into different application pools. Use an account with the least user rights possible. When IIS 6. you can make your server more efficient.config. Configuring Application Pools in IIS 6.0): This feature of IIS 6. As a design consideration.If another application fails because of the volume of requests that it receives.config file.config files are configured the same way in IIS 6.NET applications on a newly installed server running Internet Information Services (IIS) 6. An application pool is a configuration that links one or more applications to a set of one or more worker processes.0 in worker process isolation mode. an application in one application pool is not affected by problems caused by applications in other application pools. Most ASP. even when the worker process serving the new application pool has problems.NET Framework.0 : The process for deploying new ASP.NET Applications a) CREATING APPLICATION POOLS(IIS 6. Creating Application Pools (IIS 6. No code changes are required 4. such as Network Service in the IIS_WPG group. By using an application pool.0) Microsoft® Windows® Server 2003 includes support for ASP.NET Applications in IIS 6.NET applications and the Microsoft . . you can isolate different Web applications or Web sites in pools.0 (IIS 6.If the URL changes. some of the attributes in the <processModel>section of the Machine.config file are now in equivalent IIS 6. create a unique application pool for that applicationDEPLOYING ASP. Because applications in an application pool are separated from other applications by worker process boundaries. The URLs that you assign to an application pool can be for an application.Net: a.0)When we run IIS 6. configure a unique user account (process identity) for each application pool. Deployment Process using IIS 6. By creating new application pools and assigning Web sites and applications to them. a Web site. applications in other application pools do not affect that application. or a virtual directory. which are called Application Pools. Describe the following with respect to Web site deployment in ASP. and secure. you can set the application pools worker process to recycle when the application exceeds a specified number of requests. a Web directory.NET configuration sections in the Machine.0 is configured to run in worker process isolation mode. All the ASP. Guidelines for Creating Application Pools: To isolate Web applications on a Web site from Web applications on other sites running on the same computer. create an individual application pool for each Web site.1 of the . we can assign specific configuration settings to a worker process (or. This chapter describes how to deploy ASP. An application pool is a group of URLs that are routed to one or more worker processes that share the same configuration. you can update the proxy simply by editing Web.NET applications run without modification on version 1. as well as making your other applications always available.
Depending on the method you select.3. class MainClass { static void Main(string[] args) { int a. you must configure IIS 6. Basic arithmetic operations b. e = d / 2.NET applications need to retain session state.WriteLine(b). f = e % 2.f. Console. if your ASP.d. c = b .b. b = a + 6. you might need to configure the ASP.In addition.0 to use the appropriate ASP. d = c * 2. a = 1. Console. Console.WriteLine(f).c. a) BASIC ARITHMETIC OPERATION: using System.WriteLine(e). Finding greatest of n numbers Write separate programs for each of the above points. 5. Write a program in C# language to perform the following operations: a.WriteLine(c).NET state service or Microsoft SQL Server™ to act as the repository for centralized state storage.e.NET application sessionstate method. } } b) FINDING GREATER OF N NUMBERS public static void FindLargestAndSmallest() { . Console.WriteLine(d). Console.
properties. see Static Classes and Static ClassMembers (C# Programming Guide). Class Inheritance public class Manager : Employee { // Employee fields. a fundamental characteristic of object-oriented programming. If the class is declared as static. then only one copy exists in memory and client code can onlyaccess it through the class itself.. Declaring classes public class Customer { //Fields. //we will now use TryParse to get the numeric value entered isNum = Int32. methods and events. out arraySize). //read in the value string sizeString = Console. If the class is notdeclared as static. methods and events go here.. int[] numArray = new int[50] //ask the user for the size of their array Console. properties. Thevariable remains in memory until all references to it go out of scope. } Creating object Customer object1 = new Customer(). methods and events are inherited // new Manager fields. client code can use it by creating objects or instances which are assigned to a variable.TryParse(sizeString. Unlike structs. classes support inheritance.int arraySize.ReadLine(). methods and events go here. Describe the steps involved in creating classes and objects with the help of a program in C#. } // Method . } EXAMPLE public class Person { // Field public string name. not an instance variable. int largestNum. It defines the data and behavior of a type. // Constructor Public Person () { name = "unknown". For more information.. A class is a construct that enables you to create your own custom types by grouping together variables of othertypes..WriteLine("Enter the size of Array"). //now we will determine if the value is numeric if (isNum) 6. properties. bool isNum. At that time. the CLR marks it as eligible forgarbage collection. A class is like a blueprint.
WriteLine(person.WriteLine("Press any key to exit. } } /* Output:unknownJohn Smith*/ . // Keep the console window 3 Console. person. Console. } } classTestPerson{static void Main() { Person person = new Person().public void SetName(string newName) { name = newName.name).").SetName("John Smith"). Console.name).ReadKey(). Console.WriteLine(person.
This action might not be possible to undo. Are you sure you want to continue? | https://www.scribd.com/doc/142188806/Mc-0081-Solve | CC-MAIN-2015-48 | refinedweb | 4,648 | 60.82 |
tag:blogger.com,1999:blog-5867361961981983212017-11-17T09:53:34.177-08:00Parenting GeeklyWe've moved! Head to Feliciano've moved!This is the last update I'll be making over here on the blogger site!<br /><br />ParentingGeekly 2.0 now lives at:<br /><br /><a href="" target="_blank"> </a><br />(the url was just redirected here up until now).<br /><br />You can follow me on twitter here:<a href="" target="_blank"></a><br /><br />And on facebook here: <a href="" target="_blank"></a><br /><br />This is the last update I'll be making over here on the Blogger site!<img src="" height="1" width="1" alt=""/>Sharon Feliciano Tips and Etiquette<div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="400" width="285" /></a></div><br />Last week I had a chance to participate in a <a href="" target="_blank">Seattle AntiFreeze Event </a>at the Museum of History and Industry. This fun monthly event features people from different Seattle communities sharing some of the things that makes Seattle special. I am on the Board of <a href="" target="_blank">GeekGirlCon</a> and I presented with Board President, Kristine Hassell. We talked about what makes GGC special and how Seattle, with it's plethora of conventions, is a great place to be a geek!<div><br /></div><div><a href="" target="_blank">Emerald City Comicon</a>, is coming up soon and it kicks off the start of Seattle's Con Season. Between now and November there is at least one con a month including <a href="" target="_blank">SakuraCon</a>, <a href="" target="_blank">PAX</a>. <a href="" target="_blank">Norwescon</a>, <a href="" target="_blank">Jet City Comic Show </a>as well as some smaller more specialized offerings (<a href="" target="_blank">Supernatural Con,</a> anyone?)<div><br /></div><div>I am a seasoned con-goer at this point and one the most frequently asked questions ParentingGeeky gets is "What can I expect at my first con?" So, whether you are new to cons or a seasoned pro, these tips will help you make the most of your con experience!<br /><br /><h2>What to Wear</h2><b><u>Deodorant </u><.<br /><b><u>Comfortable shoes -</u></b> This is not the time to try out your sweet new stilettos. You will be on your feet for hours, take care of them! Even if your cosplay requires fancy feet, bring something comfy to change into.<br /><b><u>Layers</u> - </b>Going from a stuffy a exhibition hall to an overly air conditioned auditorium can make staying comfortable tricky. Dress in layers so you are prepared for any situation.<br /><u><b>Sun Protection</b></u> -.<br /><h2>What to Bring:</h2><b><u>Hand sanitizer/Disinfectant Wipes</u></b> - Cons are germy places. Hand sanitizer can be used before and after shaking hands, though it isn't a substitute for frequent hand washing. Wipes can be used on communal game controllers, pens, etc.<br /><b><u>Snacks and Water </u></b>- Con food is expensive and sometimes hard to come by. Tidy snacks like jerky, granola bars, and trail mix can stave off low blood sugar. You can refill water bottles in sinks and water fountains for free.<br /><b><u>Sharpies</u></b> - Always good to have your own supply for signings.<br /><b><u>Folder, backing board, poster tube</u></b> - For keeping new purchases from getting rumpled.<br /><b><u>Patience</u></b> - Lines are long, sometimes even moving through the crowd in the expo halls can take a long time. Be patient and kind, even when everyone else isn’t.<br /><b><u>Line Entertainment</u></b> - Especially important if you have kids. Books, tablets, a Gameboy all help lines go faster.<br /><b><u>WiFi Hotspot </u></b>- If you have one, bring it. Con wifi is notoriously slow, if it’s even available. Even 4G data can get pretty clogged with so many users in one place, so keep expectations low and download entertainment before hand rather than counting on streaming while there.<br /><b><u>Money (and a budget)</u></b> - Cons are expensive! Make a loop around the whole vendor area before you spend. Otherwise you might blow your whole budget before you've even seen everything.<br /><b><u>A backpack, but not a BACKPACK </u></b>-.<br /><h2>How to approach guests, speakers, creators, etc.</h2><b><u>Those you know and admire</u></b> - <div><i>If they are sitting at their table or another public area of the con where they are clearly working</i>: say hi! Keep interactions short, especially if there is a line. Don’t get too personal. Respect personal space and any rules posted about autographs and photos; at many cons pictures are not allowed at tables because there is a professional photographer to buy photos from. If no rules or prices are posted, ask before taking photos. It is a surprise to many first time con-goers that media guests and celebrities frequently charge for an autograph. These fees can range from $15 to hundreds of dollars (Sylvester Stallone notoriously charged $395 at NYCC in 2013) - though prices usually cap off around $100 for event the biggest celebrities.<br /><br /><i>If you bump into them in a con area restaurant, shop or a bathroom, or roaming the con as an attendee:</i> A simple smile and nod is appropriate. Notables need some downtime to recharge, be polite and let them have it.<br /><br /><b><u>People you are unfamiliar with</u><!<br /><br /><br />As a parent who frequently has my geeklings in tow, I also wrote a guide to bringing them to conventions: <a href=""></a><br /><br /></div></div></div><img src="" height="1" width="1" alt=""/>Sharon Feliciano it Worth Your Allowance?: Grow Home<i>Is it Worth Your Allowance? </i>Is a weekly column written by 14 year old Nate. Nate reviews inexpensive games and lets your geeklings know if it's worth spending their hard earned allowance on. Have a game to suggest? You can email Nate <a href="mailto:nate@parentinggeekly.com">here.</a><br /><br /><div>Game: Grow Home </div><div>Genre: sandbox, climbing, adventure, casual</div><div>Cost: $7.99</div><div>Developer: <a href="" target="_blank">Ubisoft reflections</a><br />To buy: <a href=""></a></div><div><br /></div><div class="separator" style="clear: both; text-align: center;"></div><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="189" width="320" /></a></div><div><br /></div><div>Grow Home is a game where you play as B.U.D. (botanical utility droid) who is a small red wobbly robot made to grow and climb star plants. Your objective is to grow a star plant into space. Along the way the star plant will create a tangled web of branches that you bring all the way up to your mothership. </div><div><br /></div><div>The artstyle is very colorful and charming. Its low poly count creates a blocky look, but makes for a smooth game play experience, because there is less strain on the hardware. The game is easy to play but still challenging. At any second you could fall off of a mile high floating island and either have climb back up or use one of the teleporters scattered around the map. But if you do fall you can die, though the only punishment is that you’ll have to climb up again, this can be prevented by using things like your jet pack or glide leaf or fall flower (giant daisy that acts like a parachute). I like that you can go out of your way to collect energy crystals and have a different experience than if you didn't, because when you collect enough crystals you get upgrades. I have a lot of fun using the glide leaf and the jet pack together to fly around the web of branches that I have made. I recomend this game for ages 8 and up.<br /></div><div>Overall, my final rating for this game is 8/10 and I definitely think it’s worth your allowance.</div><div><br /></div><img src="" height="1" width="1" alt=""/>Sharon Feliciano Guide to Cinderella: Can I bring my 5 year old to Cinderella?I have had four family members ask me this weekend if Cinderella is okay for their kids. Here is a my quick review and parent guide.<div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" /></a></div><div><br /><div><br /></div><div". </div><div><br /></div><div.</div><div><br /></div><div?</div><div><br /></div><div. </div><div><br /></div><div>Cinderella is playing in theaters now.</div><div><br /></div><div><br /></div></div><img src="" height="1" width="1" alt=""/>Sharon Feliciano it Worth Your Allowance? - Beseige<i>Is it Worth Your Allowance?</i>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="149" width="320" /></a></div><div>Reviewed by Nate</div><div><br /></div><div><u>Besiege</u></div><div>Genre: building, physics<br />Cost: $6.99</div><div>Developer: Spiderling Studios<br />If you’re interested in buying this game go to this link <a href=""></a><br /><br />Besiege is a game where you build medieval siege machines to complete a given objective. I recomend this game for people ages 10 and up because it has cartoon violence and minor gore (you can burn or run over people, though it’s not realistic). </div><div><br /></div><div>The games allows you to make almost anything from the wide variety of given parts. It has 15 levels for you to go through with challenges ranging from destroying buildings to moving boulders. The developers are still adding content like levels and building materials. </div><div><br /></div><div>I dislike that the camera is always manually controlled, but that isn't really a problem - more of a preference. This is an early access game which means that it isn't 100 percent finished, but the game is completely playable and the devs are still adding and changing things. </div><div><br /></div><div>The most impressive machine I built was an airship that had 7 flamethrowers on the bottom, which I used in a challenge to kill sheep. My airship is nothing compared to the things the community has built, like transformers and giant walkers.</div><div><br />Overall, my final rating for this game is 8/10 and I definitely think it’s worth your allowance.<br /><br /><br /><i>Have an idea for an inexpensive, teen friendly game Nate should review? Email him <a href="mailto:nate@parentinggeekly.com">here.</a></i></div><img src="" height="1" width="1" alt=""/>Sharon Feliciano Staycation Part 2: John Howie Steak.This is the second part of my Bellevue Staycation wrap up! Read the first part <a href="" rel="nofollow" target="_blank">here</a>.<br /><div class="separator" style="clear: both; text-align: center;"></div><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="320" width="180" /></a></div><br />I have been ruined. After the amazing anniversary dinner we had at John Howie Steak, I don't know if I'll ever want to eat "normal" food again. I dream of the delicious food we served that night, and I am a little hesitant to even share it with you, lest you suffer my fate. But, it's kind of my job to share with you, so I will.<br /><br />When we first started thinking about where to celebrate our 15th Anniversary, many friends suggested iconic Seattle restaurant Canlis. We loved the idea of eating at a premier high-end restaurant, but Canlis is a pretty dressy-uppy place (they actually won't seat you near a window if you aren't wearing a jacket) and while I love to get dolled up, it's not Super-Dad's thing. One of our favorite parts of dining at John Howie was its "come as you are" attitude. I was wearing a causal dress, and SD had on dark jeans and a sweater. We were totally comfortable and didn't feel at all out of place. Looking around we saw many other couples dressed like us, a party really dressed to the nines and one couple who was very casual with the lady in a tank top. Everyone was treated with the same fantastic service. It is hard to enjoy yourself if you feel like everyone is judging you, so John Howie Steak's welcoming atmosphere was definitely a highlight<br /><br />We were comfortable at John Howie, and it just added to the magnificent experience, but don't get me wrong, John Howie is FANCY. White table cloths, the waiters wear white coats and bow ties. In between courses they cleared the table with a crumb scraper; I didn't even think those were real things any more. When we arrived our awesome waiter brought us a great selection of bread and crackers and an amuse bouche of soup. I had a taste of the creamy crab and smoked salmon chowder, Super-Dad is gluten free, and they accommodated him with a taste of tomato soup. We were each a little jealous, salmon chowder is one of his favorites, and I love tomato soup. I was able to taste his, but thanks to his Celiac Disease, I couldn't share the chowder (Darn, more for me!).<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="" height="112" width="200" /></a></div>We started our meal with a spinach salad prepared tableside. It was so fun to watch one of the waitstaff "captains" prepare salad. We watched him sautee the bacon and shallots, made the vinaigrette and tossed the whole thing together with some Marcona Almonds, the whole thing was topped off with perfectly fried quail eggs, which made a unctuous sauce with its yolk. The salad was <br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="" height="200" width="112" /></a></div>delicious, with just the perfect amount of wilt on the spinach. He cooked over a single piece of charcoal, which was much cooler than the sterno or hot plate we've seen at other restaurants. <br /><br />Then it was time for my favorite thing to eat: meat. Look, we know beef. Super-Dad's parents own a cattle ranch in Washington's Skagit Valley. We're not talking a giant, commercial farm here. Hemlock Highlands is a boutique ranch that raises a small herd of Scottish Highland Cattle for beef. Their beef is aged for 21 days, an artisanal process that most big farms that supply restaurants don't have time to devote to. This is why seeing that John Howie offers steaks aged for 28, 35 or an astonishing 42 days blew our minds. Most restaurants are more concerned about getting their product to the customer as quickly as possible, John Howie cares about quality, and it shows.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="180" width="320" /></a></div>For our entree we had a terrible time deciding which cuts of meat to order, everything sounded so good. We decided that since it was an anniversary dinner we would go with a Tableside for Two choice. We chose the 36 oz. Prime Bone-in Rib Eye Steak. In case your math is bad, that's two and quarter pounds of steak! It came out looking like something from the Flintstones, just a huge, beautiful cut of meat with a big bone sticking out of it. It's served with roasted vegetables and a Bordelaise sauce that the chef specially prepared to be gluten free. The tableside service means that this perfectly medium rare beauty was sliced and plated right in front of us. It was so, so good. SD ate all of his steak, the vegetables and the side of wild mushrooms we ordered. I ate as much of mine as I could and (probably a bit more), and I still had enough leftovers to make an amazing meal the next day.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="" height="200" width="112" /></a></div>We almost passed up dessert, but we just can't say no to creme brulee, and this was the best creme brulee we had ever had. It was perfectly smooth, without a hint of graininess, and just a touch of sweet vanilla. It was served with a cute heart shaped candle in honor of anniversary. SD accompanied his with what he called an "awesome" Irish Coffee, and I had an expertly crafted latte.<br /><br />We left with a few truffles, very full bellies, a wonderful Anniversary memory and plans to return (they have a Sunday Family Dinner that I bet my geeklings would love)! The service was impeccable, we especially appreciated the care with which they accommodated Super-Dad's dietary restriction. The atmosphere was elegant but comfortable, and the food was some of the best we've enjoyed. Thanks, John Howie Steak for hosting our Anniversary dinner!<br /><br />For more information and reservations: <a href=""></a><br /><br /><div class="separator" style="clear: both; text-align: center;"></div><img src="" height="1" width="1" alt=""/>Sharon Feliciano ParentingGeekly at SAM Remix on</a></div><br />Hey Seattle Area geeks! I am jazzed to be one of Seattle Art Museum's guest tweeters for their SAM Remix party on March 13th, in celebration of their Indigenous Beauty exhibit. I will be taking over the <a href="" target="_blank">@iheartsam</a> twitter handle for an hour (Exact time TBA) and will be live tweeting the rest of the event from my twitter handle - <a href="" target="_blank">@ParentingGeekly. </a><br /><br /><br />From SAM:<br /><blockquote class="tr_bq">Choose your own adventure from this fabulous late night of performances, activities, dancing, and more with <a href="">Indigenous Beauty: Masterworks of American Indian Art from the Diker Collection</a> and SAM’s fantastic collection. No two #SAMRemix events are the same!</blockquote>Tickets and more info can be found here: <a href="" target="_blank"> </a><br />.<br /><br /><img src="" height="1" width="1" alt=""/>Sharon Feliciano Anniversary Staycation: The Awesomeness of the Hyatt Regency Bellevue<div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="320" width="180" /></a></div><div><br /></div><div><br /></div>I. <div><br /></div><div>We headed over to Bellevue, WA, a short 15 minute drive from our Seattle house. Bellevue is where is Super-Dad grew up, and there was a time not that long ago that taking any kind of trip to Bellevue would have been laughable. It was known for it’s giant shopping mall and wealthy suburbanites, but that’s about it. In the past few years, Bellevue has had a geek renaissance. Microsoft has a huge presence there, T-Mobile is there, Valve (and Steam) are headquartered there. Expedia, Clearwire, Bungie, 5th Cell - all have Bellevue offices. It’s the age of the geek, and Bellevue is the place to be. No longer just Seattle’s dorky neighbor, it’s become a destination all on it’s own. We set out to experience it like tourists, and we had our expectations blown away. </div><div><br /></div><div>A particular quirk of downtown Bellevue is that many of the buildings are connected. You never have to leave the indoors and you can even cross streets using a series of skybridges. I had been to the Hyatt Regency Bellevue’s lobby before on a couple of occasions. It opens to a retail area on the lower floor where I’ve met clients for a coffee meeting. I also attended a fantastic event all about holiday tech hosted by the people over at Techlicious in one of the hotel’s spacious meeting spaces. During that event, the Hyatt Regency Bellevue showed off some of it’s cool tech (which I will highlight later), food, rooms and service. It was also at that event that I was gifted a night’s stay at the hotel. </div><div class="separator" style="clear: both; text-align: center;"><="112" width="200" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">An anniversary card signed by the hotel staff!</td></tr></tbody></table><div>I contacted the hotel a few days before we were planning on visiting to let them know that I would be coming, that I wanted to write it up as a part of this staycation piece, and that Super-Dad and I would be using the opportunity to celebrate our 15th Wedding Anniversary. From that point on, we felt like rock stars. The hotel sent us maps,info on local hot spots and information about making our reservation at the hotel’s restaurant, Eques (not only for hotel guests, it’s one of the most popular brunches in Bellevue).</div><div><br /></div><div>When we arrived, we were delighted to find that we were upgraded to the Kemper Suite, a gorgeous huge suite on the top floor. The room was awesome. Standing in the middle of two seating areas, a dining table that seats 8 and a kitchenette, we decided that when we renew our wedding vows in a few years we will throw a dinner party in the Kemper suite! There was a big TV, and a desktop computer ready to access the internet. Hyatt did a beautiful job of making a room that was both business friendly and luxe. We would have been as comfortable hosting a meeting as we were celebrating a weekend away.</div><div><br /></div><div><a href="" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="" height="200" width="112" /></a>The bedroom had an amazing king poster bed with some of the nicest linens we’ve ever experienced. Seriously, after staying there, Super-Dad suggested that we get new sheets for our king-sized bed, the flannel and t-shirt knit sheets are no longer cutting it. The Kemper Suite has a big soaking tub that is positioned kind of halfway in the bathroom and halfway into the bedroom which was fun because it gave me a view of the TV while I soaked. </div><div><br /></div><div><a href="" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="" height="200" width="112" /></a>I have a real problem with people who greedily snatch up all the hotel toiletries upon leaving a room. Like, how many tiny bottles of shampoo could you possibly need? It has always seemed so greedy and unnecessary to me - until now. The Hyatt Regency stocks KenetMD bath products, and I’m only a little embarrassed to admit that we pocketed them all. I fell in LOVE with a minty pulse point oil that I swear has given me a little extra pep and patience when I need it. Super-Dad loved a combo linen/facial mist that had a light, spicy (cardamom maybe?) scent. I think we are going to have to go back and stay another night, because we’re both running low.</div><div><br /></div><div>I could go on and on….we visited the Regency Club for some hors d'oeuvres and a cocktail, lounged some more in our room with a bottle of Hyatt’s exclusive Canvas wine, and enjoyed an early morning room service breakfast (before hitting up the Regency Club again for our mid-morning snack, before hitting up Eques for brunch -we legit ate like Hobbits on this trip). But I know the readers of this blog, and you want to know geeky details. </div><div><br /></div><div><br /></div><div class="separator" style="clear: both; text-align: center;"></div><div>>What sets the Hyatt Regency Bellevue apart for geeks? It’s at this point that I have to mention the bedroom TV. Super-Dad and I love to settle into bed and watch TV. We have a 42 inch TV in our home bedroom (yes, we know it’s not ideal for sleep hygiene), so we were a bit disappointed that there was no television in the bedroom. As I was about to get into the bath, Super-Dad noticed a remote on the footboard of the bed. It only had buttons for up and down. SD pushed the up button and lo and behold, a TV rose out of the bottom of the bed - turns out it was a motorized TV console positioned to look like a footboard. The TV rotated in all directions, allowing us to watch in the tub, on the sofa facing the bed and in the bed. The TV WAS A TRANSFORMER, you guys! This was probably our favorite part of the room, because we are dorks.</div><div><br /></div><div>Another favorite feature? Text based concierge. You can text the front desk to ask questions, have toiletries delivered, and arrange transportation or entertainment. The key cards are RFID enabled, so after that bottle of red we didn’t have to worry about sticking key cards in slots the right way, you just touch the key to the door. The lobby has two huge Surface coffee tables. We played a little piano and had a game of chess while hanging out in the lobby.</div><div><br /></div><div>In case you can’t tell, we love, love, loved staying at the Hyatt Regency Bellevue. It’s right in the middle of everything (look for upcoming stories on the food we ate at John Howie Steak and the games we played at Lucky Strike - both within walking distance). Not only was it great for a relaxing couples’ weekend, but with a pool, the fun coffee tables, and the almost continuous availability of snacks in the Regency club, our kids would be totally at home as well.</div><div><br /></div><div>I also want to take this opportunity to give a shout out the amazing staff. Every single person we dealt with from check in to check out seemed genuinely excited to work with us. It’s was a real delight to work with such competent, lovely people and it made our stay even more delightful.</div><div><br /></div><div>If you would like to stay at the Hyatt Regency you can find them online <a href="" rel="nofollow" target="_blank">here</a>.</div><img src="" height="1" width="1" alt=""/>Sharon Feliciano finally gets a Superhero Alter-Ego<br /><br />Okay, so she's still a princess for whatever reason, but I feel about this much like I feel about <a href="">pink Lego</a>. If this is what gets an otherwise uninterested kid into super heroes (especially female ones!) I'm down. My own daughter likes Barbie AND superheroes, so it's great to see the folks at Barbie embrace that you can be a girly girl and like to take down the villains too!<br /><br /><div style="text-align: center;"><a href=""><img border="0" height="320" src="*" width="275" /></a></div><br />Here is the synopsis from Universal Home Entertainment: <br /><br />SYNOPSIS Barbie Princess Power: Barbie™ stars as Kara™, a modern-day princess with an everyday life. One day, after being kissed by a magical butterfly, Kara™ soon discovers she has they discover the kingdom’s true enemy, can they put aside their differences to form one super team? Soar to new heights and discover that there’s no greater power than the power of friendship!<br /><br /><br />The movie is released on DVD and Blu-ray on March 3rd. Want a copy? Universal Studios Home Entertainment has offered me FIVE(!) copies of the blu-ray to give to ParentingGeekly readers. Enter for your chance below.<br /><br /><a class="rcptr" href="" rel="nofollow" data-a Rafflecopter giveaway</a><script src="//widget-prime.rafflecopter.com/launch.js"></script><img src="" height="1" width="1" alt=""/>Sharon Feliciano Wearables! G G Watch R and Martian Notifier<div><br /><" src="" height="160" width="320" /></a></div><br /></div><div><br /></div>I LOVE Wearable technology. Love, love, love it. It combines some of my favorite things; the ability to be always connected, metrics and data, and shiny jewelry and tech. Team Feliciano has tried tons of wearables, and we love getting the opportunity to try out more.<br /><br />Recently AT&T Seattle loaned me some watch style wearables to try. For the past month or so we have been giving the Martian Notifier and LG G Watch R a go. Here’s what we thought:<br /><br />LG G Watch R<br />This is a sexy watch. I loved the way it looked, especially it’s circular face with a true circular display (the Moto 360, a watch with a similar look and round face, still had a weirdly rectangular display that showed its bottom edge). It looks, for the most part, like a watch. Unlike every other smart watch we’ve tried, this one has a real leather band, which can be swapped with any appropriately sized watch band of your choosing. This is a neat feature that not only allows you to personalize the watch, but helps extend the life. The drawback here is that the watch face is pretty darn big. This is definitely sized like a men’s watch. I have very petite wrists and It was pretty uncomfortable for me to wear. Nate, at age 14, has wrists a bit bigger than me, found it to be just fine. After I deemed the watch too uncomfortable, he wore it for the most of the month.<br /><br />The G Watch R is also a “Pure” Android device. it runs Google’s Android Wear, as opposed to a watch like the Samsung Gear, which runs proprietary software over the Android framework. This seemed to make the watch a bit more zippy, with virtually no lag. Coming off the Samsung experience, there was a bit of a learning curve with the interface. Not surprisingly, Nate was the first to really get it, and once he did he found it very easy to navigate. <br /><br />Nate’s favorite features were the pedometer and the heart rate monitor. He really liked that there are many watch faces to choose from, and his favorite looked like a regular watch that had subtle dials for steps taken and current heart rate. We have offered him wearables that were simply for step tracking, but he has never really been interested. I think that the fact that the G Watch R looks like a cool watch, but has the ability to show steps discreetly makes this a health tracking device that even an image conscious teenager can get behind.<br /><br />The charging situation with smart watches has been a problem since their introduction, and I don’t think that any of the ones we have tried have really solved that yet, and this is no exception. The charging cradle has the benefit of a magnet, which only slightly mitigates the awkward cradle fit. <br /><br />It has a nice, crisp OLED display. The battery conserving properties of the OLED allows the G Watch R to have an “always on” mode that always shows the time, just another step towards smart watches actually working like a traditional watch.<br /><br /><br />Nate got about 3 - 4 days of battery life when the watch wasn’t connected to his phone (to honestly use it as a watch and not a “device” at school, it was better for him to sync it at home). When it was constantly connected via bluetooth, the battery life was about 2 days, which is pretty respectable, and a small improvement over other smart watches we’ve tried.<br /><br />Nate was upset when I told him our review period was over and he’d have to give the watch back. This is the first piece of tech that I’ve brought home that has really gotten him excited. WIth a $300 price tag, I’m not sure that it’s in the budget as a gift for a teen. This is totally a contender for me to buy for myself once my current smart watch bites the dust, though.<br /><br /><br />Martian Notifier Smartwatch<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="180" width="320" /></a></div><br /><br />We took this one out, and Kitty summarized all of our feelings about it pretty well. “PopPop would like that”. This is a smartwatch that is first and foremost a watch. It, once again, was too big for my tiny wrists (c’mon smartwatch designers, ladies like gadgets, too!). The face was a bit more comfortable for me than the G Watch R, but the rather large rubbery watch band once again made this look more like a man’s watch than a unisex time piece. The face size shouldn't be too much of an issue on this one, a majority of the face is an actual, analog watch with just a small sliver along the bottom for the screen. Hopefully Martian will be able to offer a Ladies’ Notifier in the future. Currently the Notifier comes in red, white or black. AS with the G Watch R, the straps are interchangeable with any watch band, and the Martian also offers “quick change” watchbands in nine colors ($20) that can be swapped out without using tools. <br /><br />If subtlety is your game, this is the smart watch for you. I can imagine this being used by anyone who wants to discreetly stay connected without the flash of a OLED, touch screen, and speaker equipped mini-computer. It syncs with both Android and iOS devices, making it one of the few options out there for Apple devotees. It will sync with almost any app that can push notifications to your phone. You can change the watch’s settings to vibrate differently for each app, a helpful feature for knowing which of your notifications need your immediate attention (waiting for an important text or email?) and allowing you to ignore notifications that can be saved for later (SportsCenter, Facebook, and Clash of Clans, all apps that can be set up to send notifications).<br /><br />I love that you can set up the Notifier as a “leash”, it will tell you when your phone is out of range; and you can have the Notifier make your phone ring if you've ever misplaced it. It’s one of the valuable features for me, as I seem to misplace my phone multiple times a day. <br /><br />There are a few detractors here, even when taking it’s purposely limited scope into consideration.<br /><br />The Martian Notifier is *this* close to having the charging system I want to see in wearables. It has a port right on the side of the watch, and you just plug it in, which is awesome. The downside? The micro USB port is set really deeply into the side of the watch, meaning it needs a ridiculously long proprietary USB connector that seems really delicate to me. I didn’t have any problems when I used it, but being in an active household with two kids, I was constantly concerned that it would snap off the cord. The charging port on the watch requires a cover to be snapped into place to keep the splash resistant qualities intact. Yes, it’s splash resistant and not water proof, which seems a step in the wrong direction considering all of the other current smart watches are water proof. You could wear the Notifier while washing your hands, but you’ll have to take it off if you’re going to take a shower. It doesn’t have an onboard speaker, which is probably fine as I would imagine anyone opting for this aesthetic would feel pretty silly talking into their wrist anyway. <br /><br />Two other points in the Martian Notifier’s favor? This is an affordable piece of tech at $130 MSRP. I also loved the five day battery life and the fact that when that battery does die it still works as...a watch.<br /><br />Both of these devices are available from AT&T retail stores, your carrier or online.<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"> </a> </div><img src="" height="1" width="1" alt=""/>Sharon Feliciano a Red Boom Swimmer Speaker - A perfect Geeky Valentine's GiftWe are media obsessed here, and with our Samsung Galaxy S 5s, we have taken to streaming shows while we shower. The shower can be pretty loud, and having a waterproof Bluetooth speaker is a necessity.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="218" width="320" /></a></div><br />I suppose you could also play some sweet, sexy tunes and run your Valentine a bath with, like, flowers or whatever, but if you're a reader of this blog you're just as likely to want to watch Game of Thrones during that bath. Either way, AT&T has your back. Their “Sweet Heart Sale” happening <span class="aBn" data-<span class="aQJ">Feb. 6-19</span></span>: Get 2 Boom Swimmer speakers (any color - though the red is especially Valentines-y) for $99. (save $31).<br /><br />The Boom Swimmer Speakers are especially cool because they have a little bendable "tail" that allows you to hang it in a bunch of ways, and attach it to multiple things or coil it into a stand. It also has a suction cup, for sticking to the shower wall.<br /><br /><div class="separator" style="clear: both; text-align: center;"></div>Check out the Boom Swimmer Speaker and AT&T's other gift suggestions at <a href="" rel="nofollow" target="_blank"></a><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="214" width="320" /></a></div>Want to win a red Boom Swimmer Speaker, courtesy of AT&T Seattle? Enter below!<br /><br /><a class="rcptr" data-a Rafflecopter giveaway</a><script src="//widget-prime.rafflecopter.com/launch.js"></script><img src="" height="1" width="1" alt=""/>Sharon Feliciano's coming up? <p dir="ltr">Hey Geeky Parents! Thought I'd do an quick a post to let you know what you can expect here soon! </p><p dir="ltr". </p><p dir="ltr">My obsession with wearables continues. We've been testing out the LG G watch R and the Martian Notifier, and will have those reviews up at the end of this week. </p><p dir="ltr">Super-Dad and I celebrated our 15th wedding anniversary on Thursday! I will have a feature on our anniversary "staycation" on the blog soon! </p><p dir="ltr">Finally, I am reading "Orbital Perspective" by Astronaut Ron Garand. I got to speak with Garand while he was orbiting the earth on the ISS a few years ago (how lucky am I!?) so I'm excited to read his insights! </p><p dir="ltr". </p><p dir="ltr">For the most frequent info from me follow me on <a href="">Twitter</a> and <a href="http:// Facebook.com/parentinggeekly">Facebook.</a> </p><div class="separator" style="clear: both; text-align: center;"> <a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"> <img border="0" src=""> </a> </div><img src="" height="1" width="1" alt=""/>Sharon Feliciano TrailerDisney released the first (human sized!) trailer for Ant-Man last night during the premiere of Agent Carter.<br /><br /><iframe allowfullscreen="" frameborder="0" height="225" src="//" width="400"></iframe> <br /.<br /><br />The screenplay was written by Adam McKay, who is known for Anchorman, Talladega Nights and The Other Guys. So this should be pretty funny, though you wouldn't really know it from this teaser.<br /><br />Are you excited for Ant-Man? It'll be released right around my birthday in July, so I'm pretty pysched!<img src="" height="1" width="1" alt=""/>Sharon Feliciano I'm Thankful for our Christmas Flu<div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="266" width="320" /></a></div><br /><br /.<br /><br />It sounds pretty terrible, huh? It was. It sucked. I have to say, though that I am thankful for our Christmas flu. <br /><br />No, the fever did not affect my brain (though it did reach a kinda scary 104.2!), I'm not<i> glad</i>!<br /><br /.<br /><br /.<br /><br /.<br /><br / <i>little </i>puke.<br /><br />Also: Get your flu shot. It's not too late. All this silver-lining stuff is nice, but the flu can kill you.<br /><br /><img src="" height="1" width="1" alt=""/>Sharon Feliciano Walking with Dinosaurs Scary? Educational? Scientifically Accurate?<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="225" width="400" /></a></div><br />Last?).<br /><br /. <br /><br />The combo animatronic/remote control/human powered puppets were really where we thought they'd lose us. We were expecting some clunky four wheelers with paper mache dino bodies smacked on top. We were pleasantly surprised to experience <i>very</i>!<br /><br /><b>Is Walking with Dinosaurs scary?</b><br />I've already have had a few people on <a href="" target="_blank">Twitter</a>.<br /><br /><b>Is Walking with Dinosaurs violent?</b><br /. <br /><br /><b>Is Walking with Dinosaurs scientifically accurate?</b><br />The shows producers insist it is. And while I'm no Paleontologist, I am a proponent of presenting audiences, especially young audiences, with the most scientifically accurate info. Everything presented seemed to jive with what *I* understand to be the most up to date scientific information.<br /><br /><b>Is Walking with Dinosaurs educational?</b><br /.<br /><br /><b>How long is Walking with Dinosaurs?</b><br /.<br /><br />Walking with Dinosaurs plays the Tacoma Dome through December 21, 2014. Discount codes for select shows can be found <a href="" rel="nofollow" target="_blank">here.</a><br /><br />For more information and to see when Walking with Dinosaurs is playing in your area visit <a href="" rel="nofollow" target="_blank"></a><br /><br /><div><br /></div><img src="" height="1" width="1" alt=""/>Sharon Feliciano: Samsung Galaxy Gear>The original Galaxy Gear in smashing rose gold (bottom), and the much improved Galaxy Gear 2 (top, with Pip-Boy watch face)</i></td></tr></tbody></table>As we march headlong into 'the future is now!' one of the big new fields is wearable tech. I am all about metrics and data and information, so as soon as the Galaxy Gear became available, I wanted one. Super-Dad got me a Samsung Galaxy Gear (original version, in rose gold of course ) for our anniversary last year - my kind of jewelry! Sometimes being an early adopter has its disappointments. The general concepts are there, answering calls and texts from your wrist, a camera, and a pedometer; they just aren't executed super well. I found the software to be buggy and the hardware to be clunky. The camera is inconveniently placed and constantly brushed against stuff. The charging port was a ridiculous contraption that wrapped around the entire watch face. But, this isn't a review of the Original Galaxy Gear, it’s a review of the far superior follow up attempt, the Galaxy Gear 2.<br /><br />The Galaxy Gear 2 may only be a second generation device, but in this age of super fast development cycles, that means more than it once did. The interface has improved dramatically, with significantly less bugginess than the original. It has a great list of features including IR (can be used to screw with your friends’ TVs! Or just to change the channel on your own set ) a heart rate monitor, a more accurate pedometer, and a sleep monitor. The Gear 2 also offers a more robust list of apps from which you can get notifications. SD is a constantly on call Systems Engineer, and the ability to check these alerts for urgency without fumbling around for his phone it great. It offers him both quick convenience and subtlety when we are out and about. This has been the true selling point for him. He, like so many of us, had given up on wearing a watch. It’s a relic in a time when everyone has a phone in their pocket. He was reminded of how convenient it is to easily check the time from your wrist, and the Gear 2 has the added bonus of allowing you to also check message and mail. It’s quite the time saver. <br /><br />The ability to customize the watch has greatly improved since the original Galaxy hit the scene as well. There are a ton of watch faces available whether you want a fancy multiface analog style watch or something a little more geeky, like the Fallout Pip-Boy display.<br /><br />The hardware has also gone through a major update with the two major design flaws - the obtrusive camera lens and the bulky charger - both being replaced with sleeker more integrated design. The charging port is still a separate piece that snaps onto the back of the watch face, and a downside to it being smaller is that it’s much easier to potentially lose. I’d find a permanent home for it, and just leave it plugged in.<br /><br />Super-Dad did accidentally “wrist dial” people a few times. Mostly me, but it did lead to at least one awkward conversation with a business associate. SD also found that the icons would rearrange themselves on the home screen, which was annoying. These complaints could be avoided by addressing one of our other complaints and adding a lock screen. The Gear 2’s <span style="text-align: center;">accelerometer also locked up once during the three weeks he tested it. This went unnoticed for a few days, SD just figured it wasn't tracking sleep for some reason, but was easily fixed with by restarting.</span><br /><span style="text-align: center;"><br /></span>So what’s the verdict? Well, our Gear 2 is on loan from AT&T for review purposes, and SD really doesn't want to give it back. Guess it’s a good thing that Christmas is just a few short days away. The Gear 2 would make a great gift for any Samsung Galaxy user. I can actually see it being really practical for our teen as well. Phones are supposed to stay in pockets at school, but a watch is a useful tool and a watch that also gives my ADHD kid reminders? I think that could be pretty great.<br /><br />You can check out AT&T’s collection of wearable devices here: <a href=""></a><br /><br />And you can see the whole family of Galaxy Wearables here: <a href=""></a><br /><br /><span style="font-size: x-small;">I was not compensated for this post, I was offered the Galaxy Gear 2, on loan, for reivew purposes from AT&T.</span><img src="" height="1" width="1" alt=""/>Sharon Feliciano with Dinosaurs - Discount CodeKitty is seven years old, and like many seven year olds, she is obsessed with dinosaurs. So I'm really excited that the folks from Walking with Dinosaurs invited us to join them for opening night in the Seattle area! We haven't yet seen the show, but are looking forward to what the creators bill as a "$20,000,000 spectacular". <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="213" width="320" /></a></div><br /><br />I will be posting a review of the show the night of the 17th, so if you're on the fence about seeing it when it comes to your town, keep an eye out!<br /><br />For more information on the show and for dates near you: <a href=""></a><br /><br />For my Seattle area readers:<br />For tickets and more info visit: <a href=""></a><br /><br />Discount codes for Parenting Geekly Readers:<br />$5 off Price Level 2: $44.50 (reg. $49.50)<br /><br />$3 off Price Level 3: $26.50 (reg. $29.50)<br />Offer Code: KIDFUN<br /><br />Valid on all Tacoma Dome shows except Sat 11am/3pm & Sun 1pm<img src="" height="1" width="1" alt=""/>Sharon Feliciano for Buying your Kids a Smartphone this Holiday<br /><br />I haven't started my Christmas shopping yet. With the exception of one gift for each kid, I have yet to check anything off my list! Nate really wants a new smartphone this year. He has been getting our hand me down phones, so it might be time for a new phone all his own to put under the tree<br /><br /><br />I'm pretty phone saavy, and I'm sure most of my readers are as well, but this list from AT&T has some great reminders. I know that I want a quad core processor, unlimited data and a durable case, but sometimes I go into the store and have an "Oooh, shiny!"moment and forget all that. I love the idea of bringing a checklist. This is especially helpful if you plan is to buy whatever phone is a good deal. If it's not one of the big two (iPhone or Samsug Galaxy S series) you may not be as familiar with the specs. Keeping a list with you will make sure you get exactly what you want for the best price.<br /><br />Here are the tips from AT&T:<br /><iframe src=""></iframe><br /><u>Smartphone Buying Tips for Parents </u><br />When it comes time to buy your child his or her first smartphone, there are several considerations and decisions to make. Determine exactly how your child plans to use the new cell phone. Parents can alleviate confusion and potential disappointment by finding out this key information before buying a phone. <br /><br />Parents may want to prioritize the features of a wireless device that will be most important to their child, so they can narrow down the choices and make a wise purchase decision. Wireless carrier stores offer a wide variety of options. For example, AT&T stores stock nearly 70 wireless phones. There’s a device that’s just right for everyone; you just need to know what features will be most useful. Consider ranking the child’s mobile wish list using these criteria: <br /><ul><li>Text messaging </li><li>Send/receive e-mail </li><li>Social media </li><li>Take and share photos </li><li>Games </li><li>Listen to streaming music and mp3 files of music they already own </li><li>Watching TV (YouTube or streaming video) </li><li>Apps </li><li>Browsing Web </li><li>Video chat </li></ul>Bring the list of priorities along when shopping for a wireless phone. A store salesperson can then offer several devices in a variety of price ranges that will meet those needs. If a child enjoys video games and streaming video, a smartphone with larger display screens may be a better choice. It’s also helpful to know how a child will use the phone when selecting the right voice and data plan. Streaming audio and video use more data than email and social media posts, so the mobile data plan you select should match how the phone will be used to avoid any surprises later. <br /><br />After selecting a wireless phone, mobile protection insurance should also be on the shopping list. Anyone can drop a phone, no matter their age. Another key decision a parent should make is whether to choose a wireless device that requires a contract or not. The latter may be a good option for a parent trying to teach a child financial responsibility—the parent may purchase the device and make the child pay the monthly cost of voice, data and texting. A no-contract option has no activation charge or contract. Choices of prepaid phones range from basic voice phones to quick messaging devices all the way up to smartphones.<br /><br /><br /><span style="font-size: x-small;"><br />I was <u>not</u> compensated for this post, I just think there are some smart considerations here. Thanks, AT&T. </span><img src="" height="1" width="1" alt=""/>Sharon Feliciano Sesame Street Celebrate their 45th Birthday on this Giving Tuesday<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="320" width="203" /></a></div><br />Last month Sesame Street celebrated its 45th Birthday! If you've read this blog before you know that not only am I a huge fan of the show, but I am a big supporter of Sesame Workshop, the non-profit behind the television production. This being Giving Tuesday, I encourage you to <a href="" target="_blank">make a donation</a> to Sesame Workshop, or any non-profit that you support.<br /><br />The story of Sesame Street's creation is an amazing one, and lots has been written about it (I recommend <a href="">Street Gang: The Complete History of Sesame Street</a><img alt="" border="0" src="" height="1" style="border: none !important; margin: 0px !important;" width="1" /> and <a href="">Sesame Street: A Celebration of 40 Years of Life on the Street</a><img alt="" border="0" src="" height="1" style="border: none !important; margin: 0px !important;" width="1" />) Here are the highlights:<br /><br />Sesame Street and the Children's Television Workshop (now Sesame Workshop) were created by Joan Ganz Cooney, a woman who was compelled to work in educational television as soon as she learned that such a thing existed. She originally appiled to be a publicist for her local station, but upon being told that they needed producers, she told them that she could do that, despite never having done it before. She's said: "I've never been qualified for any job I've been hired for". This is a woman who heard her calling and went for it. She's one of my personal heroes, and I hope some day to get to tell her that in person.<br /><br />Anyway, Cooney had this idea that they could take the addictive properties of television, a concern that was already being expressed by the mid 60's, and turn them into a way to benefit children. Children's Television Workshop was started and conducted over two years of research on the best ways to prepare children for school through the medium of television.<br /><br />For many kids, it was the only program on television that showed a street like theirs, in a neighborhood like theirs, with neighbors like theirs. Sesame Street, the place, was gritty and urban. The people in the neighborhood were white, latino, and black. They showcased kids and adults who were deaf and in wheelchairs. Some grownups were hippies, some were preppies (Bob!). There were women in the fix-it shop and women who were moms. There have been births, deaths (my surrogate grandfather Mr. Hooper!), divorce and deployment. Sesame Street showcased the reality of many of its young, urban viewers, something was revolutionary then, and still rare now.<br /><br />By 1979 (the year *I* started watching Sesame Street) over nine million kids were watching Sesame Street daily. I watched Sesame Street every single day from about age one until I was probably developmentally way too old to be watching it. My parents couldn't really afford early childhood education for us, and my mother cites Sesame Street as a big reason that I was an early talker, an early reader, and was educationally ready for kindergarten.<br /><br />These days Sesame Workshop works around the globe to help young children cope with the issues that affect them. Their current initiatives in the U.S. include fighting childhood obesity, a program to help children grieving the loss of a parent, and a program to help children in families who are experiencing job loss/economic uncertainty. In Indonesia two thirds of children watch Jalan Sesama, the local version of Sesame Street, which aims to teach children in super diverse Indonesian archipelago about their share cultural identity. In India, Galli Galli Sim Sim, actually comes to the children. A repurposed vegetable cart outfitted with a DVD player travels to the Indian slums, giving the children there access to an early childhood education program. <br /><br />I wholeheartedly believe that if we wish to see great change in our world, we need to educate our children. All of our children, all over the world. Sesame Workshop is doing just that, Happy, happy birthday to my friends at Sesame Street. And many, many returns.<br /><br />For more information and to donate to Sesame Workshop visit their website at <a href="">SesameWorkshop.org</a><br /><br /><i><span style="font-size: x-small;">Book links are affiliate links through amazon.com. Any purchase made through those links makes me a few pennies (literally pennies) which help me pay for the upkeep for the site. </span></i><img src="" height="1" width="1" alt=""/>Sharon Feliciano Tickets to See ANNIE Before it Hits Theaters (Seattle) and a Gift Pack (US.<br /.<br /><br /.<br /><span id="goog_842546082"></span><span id="goog_842546083"></span><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" /> /><br />Enter to win either a 4 pack (2 winners) or a two-pack (1 winner) of VIP Tickets to the preview screening of ANNIE on December 13th at 10:30 AM at Pacific Place in Downtown Seattle (Seattle and vicinity only)<br /><a class="rafl" href="" id="rc-873158835" rel="nofollow">a Rafflecopter giveaway</a><br /><br />Enter to win a Promotional Gift Pack of ANNIE Merchandise (open to all residents of the US)<br /><a id="rc-873158836" class="rafl" href="" rel="nofollow">a Rafflecopter giveaway</a><script src="//widget.rafflecopter.com/load.js"></script><img src="" height="1" width="1" alt=""/>Sharon Feliciano Kindle Fire HD Kids Editionitty teaching her cousin about the states at a local Red Robin. Making dinner time education time!</td></tr></tbody></table>With the holidays coming up we were starting to toss around the idea of getting Kitty her own tablet. Her desire to use my laptop and my tablet was beginning to take a toll on both my productivity and my hardware. <br /><br /”.<br /><br /.<br /><br />If you are going to buy your kids a tablet this holiday season, I strongly recommend the Amazon Fire Kindle HD Kids Edition. Here's why:<br /><br /><br /><ul><li><b>It’s Kitty Proof </b>-.</li><li><b>Two year No Questions Asked Warranty -</b>.</li><li><b>Sooo many apps - </b.</li><li><b>The parental controls were clearly designed by parents</b> -.</li><li><b>It’s a real tablet </b>-.</li><li><b>It may be a real tablet, but it was designed for kids -</b>.</li></ul><br /><br /.<br /><br />I was given an Kindle Fire HD Kids Edition to facilitate this review, but my love for it is all my own. If a tablet for a kid is on your shopping list this holiday season, this is a good bet. <br /><br />The <a href="" rel="nofollow" target="_blank">Kindle Fire HD Kids Edition starts at $149</a><img alt="" border="0" height="1" src="" style="border: none !important; margin: 0px !important;" width="1" /> and includes a case, a two year Worry Free Guarantee and one year of Amazon Freetime. ( if you buy from that link I get some pennies [literally a few cents] to help with blog maintenance.<img src="" height="1" width="1" alt=""/>Sharon Feliciano Hero 6 Fun FactsIf you <a href="" target="_blank">read my review</a> you know that I *loved* Big Hero 6, as did the rest of my family. It's rare to find a family-friendly film that is truly entertaining for our whole family (a fidgety 7 year old, a jaded teen, and two cynical parents), but Disney once again did the job. Apparently everyone everywhere agrees, because Big Hero 6 was the #1 movie this week. <br /><br /!<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="270" /></a></div><br /><br /><h4><b><u>CHARACTERS</u></b></h4><b>SLAM DUNK</b> – Baymax is 6 feet tall and 75 pounds—until Hiro mechs him out. Baymax, in <br />his super suit, is more than 7 feet tall and can lift 1000 pounds. “He’s all air,” says head of animation Zach Parrish.<br /> <br /><b>GO AHEAD</b> – Artists looked at actors like John Wayne, Clint Eastwood, Gary Cooper and other cowboys to study cool, emotionally reserved traits while developing GoGo Tomago’s look and personality.<br /><br /><b>IT’S ALL ABOUT THE BLINK</b> –.”<br /><br /><b>NEED FOR SPEED</b> – Artists looked at speed skaters to inform the body type and movement for GoGo Tomago, a passionate student of speed. <br /><br /><b>DUUUUUUDE</b> – Artists studied snowboarders, skateboarders and surfers to develop movement and posture for Fred. <br /><br /><b>CHILL OUT<. <br /><b><u><br /></u></b><br /><b>LOOSE TOOTH<u> </u></b>– To ensure Hiro’s charming gap-toothed grin stayed intact from any angle, controls were added to his teeth so animators could make adjustments as needed. <br /><br /><b><u>TALENT</u></b><br /><b>ROBOT LOVE</b> – Ryan Potter, who voices Hiro in “Big Hero 6,” was obsessed with building robots as a kid. “I was 9 or 10 when I got a robotics kit,” he says. “I absolutely love science.”<br /><br /><b>MORE ROBOT LOVE</b> –.”<br /><br /><b>SMART GUY</b> – James Cromwell, who lends his voice to Professor Robert Callaghan, <br />studied at Carnegie Mellon University (then called Carnegie Tech). “Big Hero 6” filmmakers spent time at the school, learning all about the innovative field of soft robotics, which ultimately inspired Baymax, a huggable vinyl robot that takes care of people. <br /><br /><b>FULL CIRCLE</b> – As a child, Damon Wayans Jr., who provides the voice of Wasabi, wanted to be an animator when he grew up. He even studied animation after graduating high school before he decided to pursue acting. <br /><br /><h4><u>FILMMAKING</u></h4><b>LET IT GROW</b> – The “Big Hero 6” animation team topped 100 members (103, to be exact). That’s about 15 more animators than 2013’s feature film “Frozen.” <br /><b><u><br /></u></b><br /><b>MARTIAL ARTISTS</b> –.<br /><b><u><br /></u></b><b>I CAN FLY</b> – Filmmakers consulted with flight specialist Jason McKinley, who worked on both “Disney’s Planes” and “Planes: Fire & Rescue,” to choreograph and execute the flight sequences with Baymax and Hiro.<br /><br /><b>670’S A CROWD</b> – Walt Disney Animation Studios’ proprietary system Denizen allowed filmmakers to create bigger, more believable crowds for “Big Hero 6.” created around 670 unique characters, compared to 270 in “Frozen,” 185 in “Wreck-It Ralph” and 80 in “Tangled.” <br /><ul><li>Each of the 670 characters has up to 32 different clothing look combinations, plus 32 different hair and skin tones. That means, filmmakers could invite 686,080 unique characters to the San Fransokyo party before there were any exact repeats. </li><li.”</li></ul><br /><b>COUNT ON IT</b> -- The "Port of San Fransokyo" scene has over 6000 people in it<br /><ul><li>23 districts were built in 3D.</li><li>83,149 lots of the 150,000 in all of San Francisco were built.</li><li>18.8 million building parts.</li><li>215,000 streetlights.</li><li>260,000 trees.</li></ul><img src="" height="1" width="1" alt=""/>Sharon Feliciano Device that Saved Drive TimeThe City of Seattle is doing a "Neighborhood Revitalization Project" in my neighborhood. This is fancy talk for "fixing the streets". They are totally gutting the roads, putting in new drainage pipes, making them bigger, repaving with more durable materials. It is a crazy ambitious project that by the time it's done in the beginning of next year, will have lasted two years. And it's all happening right outside my front door. I live on a major thoroughfare and this project, which will eventually be a major improvement, is currently a major pain in my rear.<br /><br /. <br /><br />As I've written about before, it can be very difficult for us to get out of the house. On many mornings I have resorted to<strike> bribery</strike> rewards. With the construction making our commute painful, one of the best "rewards" I can offer Kitty is the ability to watch a show in the car. Problem is, with my current Data Plan (not through AT&T), my data is throttled after I reach 5 GB. I don't frequently use that much data, even if we do watch a few shows, but letting Kitty stream Netflix, or a show from her Kindle Fire Kids Edition does use a bit of data, and I never want to be stranded somewhere, unable to use the data on my phone because Kitty was too engrossed in Wild Kratts.<br /><br /! <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="279" width="320" /></a></div><br /><span id="goog_1086317845"></span><span id="goog_1086317846"></span><br /><br /. <br /><br /.<br /><br /.<br /><br />.<br /><br /><i><span style="font-size: x-small;">I was given an AT&T Unite and 1.5 GB of data to facilitate this review. I have to say it, but you already know that all opinions are mine.</span></i><br /><br /><br /><img src="" height="1" width="1" alt=""/>Sharon Feliciano I take my 5 year old to Big Hero 6?Last night the whole family went to a screening of Big Hero 6, the newest offering from Disney Animation Studios. The film was delightful.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" height="222" width="400" /></a></div><br /><br /. <br /><br /.<br /><br /.<br /><br /><br />Parent's Guide:<br /><br /. <br /><br /.<img src="" height="1" width="1" alt=""/>Sharon Feliciano, Spiderman and Gender RolesIf you follow me on Twitter (<a href="" target="_blank">@ParentingGeekly</a>), you may have seen this tweet this evening. <br /><blockquote class="twitter-tweet" lang="en">Hey <a href="">@Target</a> *Why* are these <a href="">@Marvel</a> <a href="">@Starwars</a> How to Train Your Dragon and <a href="">@Minecraft</a> toys specifically for Boys? <a href="">pic.twitter.com/FYbecADOYX</a><br />— Parenting Geekly (@ParentingGeekly) <a href="">November 6, 2014</a></blockquote><br />This is the second time we've seen that same sign at Target. Here it is from April, when a store manager told me "the signs just come that way from corporate".<br /><blockquote class="twitter-tweet" lang="en"><a href="">@Target</a> calls superhero & Minecraft toys "Boy's Toys". Guess I'll buy them for my girl somewhere else <a href="">pic.twitter.com/HqCc0LrC1J</a><br />— Parenting Geekly (@ParentingGeekly) <a href="">April 18, 2014</a></blockquote><script async="" charset="utf-8" src="//platform.twitter.com/widgets.js"></script>Some.<br /><script async="" charset="utf-8" src="//platform.twitter.com/widgets.js"></script><img src="" height="1" width="1" alt=""/>Sharon Feliciano | http://feeds.feedburner.com/blogspot/WuxMU | CC-MAIN-2017-47 | refinedweb | 11,674 | 60.95 |
In my last post, I added authentication to my Aurelia application by adding an Auth0 Lock process. I can sign in and sign out, but I’m not yet utilizing the information of whether I am authenticated or not. I can authenticate with Microsoft, Twitter, Facebook and Google+, or any number of authentication sources that Auth0 supports (which is a long list). I can still get to all the routes I defined (the home page and the Flickr photo review).
What I would like to do is to authenticate the flickr page. When I am signed in, the Flickr link appears on the top bar and I can click it and it acts normally. When I am signed out, the Flickr link does not appear on the top bar. If I go to the URL that I know, I want an alert telling me to log in.
Authentication
Aurelia has a pipeline structure for the navigation pipeline. When a request comes in, the request is first passed through a series of extensibility steps where you can add your own code. There are two steps defined by default – authorize and modelbind. You can define your own as well and fit them into the pipeline. Authorize comes before modelbind. I can use this to authenticate users.
First of all, I created a new class called AuthorizeStep. I placed this class in the app.ts file since it is relatively small. I basically followed the instructions in the Aurelia documentation substituting my logged-in check for the blank code:
class AuthorizeStep { run(routingContext, next) { if (routingContext.nextInstructions.some(i => i.config.auth)) { var isLoggedIn = AuthorizeStep.isLoggedIn(); if (!isLoggedIn) { alert("Not Logged In!\nClick the Sign In icon to log in"); return next.cancel(); } } return next(); } static isLoggedIn(): boolean { var auth_token = localStorage.getItem("auth_token"); return (typeof auth_token !== "undefined" && auth_token !== null); } }
The isLoggedIn() method checks for my auth_token is local storage and returns a boolean – the user is either logged in or not. I made this method static so other things can use this check just by using the AuthorizeStep.isLoggedIn() method. The run() method is a duplicate of the method within the documentation. I’ve just added a check to my new isLoggedIn() method (highlighted) and changed the redirect to a login page to an alert.
Note that I am checking the configuration of the route for a field called auth – if it’s there and it’s true then the authorize check is run. That means I need to adjust the route in the App class to trigger it. I also need to add the AuthorizeStep class to the router configuration:
export class App { public router: any; configureRouter(config, router) { config.title = 'Aurelia'; config.addPipelineStep('authorize', AuthorizeStep); config.map([ { route: 'welcome', name: 'welcome', moduleId: './pages/welcome', nav: true, title: 'Welcome' }, { route: 'flickr', name: 'flickr', moduleId: './pages/flickr', nav: true, auth: true, title: 'Flickr' }, { route: '', redirect: 'welcome' } ]); this.router = router; } }
When you run this project, you will note that the Flickr link still appears. However, clicking on Flickr tells you to log in. I could, of course, emulate the sign-in logic by simulating a login button. For example:
run(routingContext, next) { if (routingContext.nextInstructions.some(i => i.config.auth)) { var isLoggedIn = AuthorizeStep.isLoggedIn(); if (!isLoggedIn) { console.log("User is not logged in - clicking on app-authenticator"); var authButton = <HTMLDivElement>(document.getElementById("app-authenticator")); authButton.click(); return next.cancel(); } } return next(); }
In this case, I am simulating a click on the DIV element within the app-authenticator. This then pops up the authentication screen that then authenticates the user prior to accessing the Flickr page. I like this functionality for “entry-points” – where you want to show a small number of entry pages. The user doesn’t have to sign in. When they access a restricted area, they are automatically prompted to sign in.
Navigation
It’s all well and good to be showing off the links then asking for authentication. However, maybe I want to hide the authenticated pages unless the user is signed in. Aurelia has a navigation data model that it constructs from the route map. It is triggered by the nav property on each route. So far, all our routes have had nav: true on them.
However, if we adjust the nav to be the value of AuthorizeStep.isLoggedIn(), then the links will disappear from the navigation model when the user is not logged in. I can adjust my route configuration as follows:
config.map([ { route: 'welcome', name: 'welcome', moduleId: './pages/welcome', nav: true, title: 'Welcome' }, { route: 'flickr', name: 'flickr', moduleId: './pages/flickr', nav: AuthorizeStep.isLoggedIn(), auth: true, title: 'Flickr' }, { route: '', redirect: 'welcome' } ]);
However, we do introduce a bug here. Run this project, sign in and note that the Flickr link appears. Then sign out. Note that the Flickr link does not disappear. Refresh the screen and note that the link is gone. In short, the navigation does not get redrawn when the user signs out.
There are a few ways to deal with this bug. A complicated mechanism would be to adjust app-authenticator and nav-bar so that they know about one another. When the user clicks on sign out, the app-authenticator sends a signal to the body of the document that says “signed out”. The nav bar can then listen to that and delete or hide the li elements that are authenticated. One can get these by using the ${row.config.auth} to get the configuration of the route. I’m not a fan of the complicated methodologies and will always opt for something simpler over complicated if it gets the job done.
My method is a little more straight forward. One needs to reload the page after removing the token from localStorage. Since the token doesn’t exist on the reload, the nav bar will go back to normal.
Simply use history.go(0) to refresh the screen. For some reason, window.location.reload() nor adjusting the window.location.href worked in my testing on Chrome. Using the history worked for all the browsers I tried. The click() method in app-authenticator.ts now looks like the following:
click() { console.log("[AppAuthenticator] click "); let auth_token = localStorage.getItem("auth_token"); if (auth_token) { // We clicked on the sign-out sign localStorage.removeItem("auth_token"); history.go(0); } else { // We clicked on the sign-in sign localStorage.setItem("auth_redirect", window.location.href); this.lock.show({ authParams: { scope: "openid" } }); } }
With in-browser cache, the reload of the application should not be too painful.
Of course, the fine folks that write Aurelia could choose to do something with authorize such that I can bind the isLoggedIn() method and the nav-bar can auto-update when I log out. This saves a page reload, which isn’t a big thing in the first place – it’s not like I’m reloading the application all the time.
Wrap Up
What I’ve done in this article is provide two mechanisms for page hiding within Aurelia. The first is the utilization of the authorize pipeline and the second is to adjust the visibility of links within the nav-bar. Both are valid and should be used in conjunction to secure your application.
I have not done any data security yet. In the next article I will investigate grabbing authenticated data from ASP.NET application, secured by the JSON Web Token. Until then, you can get the code for this article from my GitHub Repository. | https://shellmonger.com/2015/07/12/using-authentication-in-an-aurelia-app/ | CC-MAIN-2017-51 | refinedweb | 1,239 | 67.65 |
What's new in Windows Phone SDK 8.0
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Welcome to Windows Phone SDK 8.0. Windows Phone 8 brings a number of new and updated features to app developers, including native gaming development, a phone-specific version of the Windows Runtime, and a new kernel. We’ve put together this introduction to help you become acquainted with new and updated features in Windows Phone 8 and Windows Phone SDK 8.0. We’re proud of the tools you have at hand in the SDK. They’re tools that can help you create the Windows Phone apps that give your users even more reasons to love their Windows Phone. Here we give you a glimpse of the features available to you to use in your app development, and how to learn more about them.
This topic contains the following sections.
- Windows Phone 8 Update 3 Emulators
- Windows Phone 8 Update 3
- SDK 8.0 Update for Windows Phone 8.0.10322
- Visual Studio 2012 Update 3
- Visual Studio 2012 Update 2
- Multilingual App Toolkit for Visual Studio 2012
- SDK Update for Windows Phone 7.8
- SDK tools
- Tiles and notifications
- Lock screen
- Maps and navigation
- Location
- Speech
- Wallet
- Multi-resolution
- Direct3D and games
- App models
- Camera and photos
- Media
- User interface
- Communications
- Data and extensibility
- Windows Phone Store
- Ready for Business
- Localization and globalization
- App manifest file
- App compatibility
- Common language runtime
- Related Topics
Windows Phone 8 Update 3 Emulators update requires either Visual Studio 2012 with Update 4 or later, or Visual Studio 2013.
To download the update, go to Windows Phone SDK 8.0 Update 3 Emulators.
Windows Phone 8 Update 3
Windows Phone 8 Update 3 (version 8.0.10492 and above) includes the following new or changed features for app developers.
Support for devices with 1080p display resolution. For more info, see Taking Advantage of Large-Screen Windows Phones and Multi-resolution apps for Windows Phone 8.
Increased memory cap for apps. On 2-GB phones, the maximum memory available for apps that have Windows Phone 8 Update 3 is 570 MB. For more info about memory caps, see App memory limits for Windows Phone 8.
Increased memory cap for background audio apps. On devices that have 1 GB of memory, the memory cap for background audio apps has increased from 20 MB to 25 MB. For more info about background audio apps, see Background audio overview for Windows Phone 8.
New Uri schemes for additional settings. There are new Uri schemes to display the Battery Saver settings page or the Screen Rotation settings page. (The Screen Rotation settings page is also new in Windows Phone 8 Update 3.) For more info, see URI schemes for launching built-in apps for Windows Phone 8.
Additional use of app icon. In the task switcher, the app icon and app title are now displayed along with the screenshot of the last active page of the app.
Custom sounds for toast notifications. You can now use reflection to specify custom sounds for toast notifications. For more info, see Toasts for Windows Phone 8.
New property related to push notifications. A new Boolean property - Windows.Phone.System.Power.PowerManager.PowerSavingModeEnabled – is available through reflection. The new property indicates whether battery saving mode is turned on. It complements the existing PowerSavingMode property, which indicates whether battery saving mode is active. When PowerSavingModeEnabled is true, an app can warn users that push notifications are not received. For more info, see Setting up your app to receive push notifications for Windows Phone 8.
Changed behavior of device-width. The behavior of device-width when used with viewport settings has changed in the WebBrowser control and in Internet Explorer. For more info, see Web development for Windows Phone 8.
Changed behavior of toast notifications. Toast notifications are now displayed when the target app is running in the foreground but is obscured by other activity such as a phone call or the lock screen. Previously, toast notifications were not displayed when the target app was running in the foreground, even when the app was obscured.
For more info about the new and changed features for app developers in Windows Phone 8 Update 3, see the following post on the Windows Phone Developer Blog: Introducing Windows Phone Preview for Developers.
You can use the following code to test whether a device has Windows Phone 8 Update 3.
private static Version TargetedVersion = new Version(8, 0, 10492); public static bool IsTargetedVersion { get { return Environment.OSVersion.Version >= TargetedVersion; } }
SDK 8.0 Update for Windows Phone 8.0.10322.
To download the update, go to SDK 8.0 Update for Windows Phone 8.0.10322.
Visual Studio 2012 Update 3
Visual Studio 2012 Update 3 installs a fix to prevent potential compatibility issues when you install and run Windows Phone 8 Emulator on Windows 8.1 Preview.
Visual Studio 2012 Update 3 is the latest update and is a cumulative update that includes features released in earlier Visual Studio 2012 updates.
To download the update, go to Visual Studio 2012 Update 3.
Visual Studio 2012 Update 2
Visual Studio 2012 Update 2 installs the following new features for Windows Phone apps.
Unit testing for Windows Phone apps. Create unit test projects for Windows Phone apps and run the tests from Test Explorer. For more info, see Unit testing apps for Windows Phone 8.
Command-line deployment. Deploy Windows Phone apps at the command prompt. You can also deploy apps from a script or custom app. For more info, see How to deploy and run an app for Windows Phone 8.
Command-line precompilation and signing for company apps. Precompile and sign company apps at the command prompt when you build them by using the Microsoft Build Engine (MSBuild). You also can build, precompile, and sign apps from a script or custom app. For more info, see Preparing company apps for distribution for Windows Phone.
To get the features that were originally released in Visual Studio 2012 Update 2, download Visual Studio 2012 Update 3. This is a cumulative update that includes features released in earlier Visual Studio 2012 updates, including Visual Studio 2012 Update 2.
Multilingual App Toolkit for Visual Studio 2012
The Multilingual App Toolkit for Visual Studio 2012 helps you localize your Windows Phone apps by providing translation support, translation file management, and editor tools that are integrated with Visual Studio. To learn more about the Multilingual App Toolkit, watch the short video, Introduction to the Multilingual App Toolkit.
To download the toolkit, go to Multilingual App Toolkit for Visual Studio 2012.
SDK Update for Windows Phone 7.8
With Windows Phone SDK Update for Windows Phone 7.8 you can provide the Windows Phone 8 Start screen experience in apps that target Windows Phone OS 7.1, using small, medium, and wide Tiles. For more info, see Adding Windows Phone 8 and Windows Phone 7.8 Tile functionality to Windows Phone OS 7.1 apps.
You can also test how your apps and games will run on Windows Phone 7.8 devices with new Emulator 7.8 and Emulator 7.8 256-MB deployment options.
To download the SDK Update, go to Windows Phone SDK update for Windows Phone 7.8.
SDK tools
Windows Phone SDK 8.0 includes the following new tools and features for developing, debugging, and testing apps.
Development tools and features
Visual Studio includes the following new features.
Project templates for Direct3D apps. For more info about project templates, see How to create a new app project from a template for Windows Phone 8. For more info about Direct3D apps, see the section Direct3D and games in this topic.
Enhanced localization support in project templates. Project templates now include built-in support for localization. You can easily begin to use best practices to develop a localized app without a lot of configuration steps. For more info, see How to build a localized app for Windows Phone 8.
Debugging managed or native code. On the Debug page of Project Designer, you can choose whether to debug the managed code or the native code portion of your app. If your app communicates with a background agent, you can also choose whether to debug the managed code or the native code portion of the background agent independently. You can debug both the app and the background agent in the same debugging session.
Debugging apps launched from a tile or notification. You can now debug an app that targets Windows Phone 8 when it's launched from a Tile or a push notification, not only when it's launched directly. When you launch your app with debugging on Windows Phone 8 Emulator or on a Windows Phone 8 device, click the Back button to exit the app; the debugger remains attached. After you launch the app again by using the Tile or push notification, you can continue to debug the app. For more information, see Debugging apps for Windows Phone 8.
XNA Framework support. You can develop XNA Framework apps that run on Windows Phone 8. To do this, you must set the target to Windows Phone OS 7.1. For more info, see XNA Framework and app development for Windows Phone 8.
Windows Phone 8 Emulator includes the following new features.
Support for multiple resolutions. Emulator images are available for each of the three resolutions supported in Windows Phone 8. For more info, see Multi-resolution apps for Windows Phone 8.
**System requirements for Windows Phone 8 Emulator **. Windows Phone 8 Emulator runs on Windows Hyper-V and has the same hardware, software, and configuration requirements as Hyper-V. If your computer doesn’t support Hyper-V, you can still develop apps for Windows Phone 8 and debug and test them on a Windows Phone 8 device. For more info, see System requirements for the emulator for Windows Phone 8.
**Networking on Windows Phone 8 Emulator **. The Windows Phone OS 7.1 emulator uses the network connection of the development computer. However, the Windows Phone 8 Emulator configures itself as a separate device on the network. For more info about the impact of this change, see Windows Phone Emulator for Windows Phone 8.
Manifest Designer. You can now add, remove, and change elements in the app manifest file through a user-friendly user interface. For more info, see How to modify the app manifest file for Windows Phone 8.
Isolated Storage Explorer has new command-line options that let you specify the target device. For more info, see How to use the Isolated Storage Explorer tool for Windows Phone 8.
Testing tools and features
Testing your app’s native image. You can test the app’s native image to experience its performance as users will experience it. For more info, see How to test the retail version of your app for Windows Phone 8.
App monitoring and profiling. Windows Phone Application Analysis (formerly Windows Phone Performance Analysis) now includes app monitoring in addition to app profiling. The app monitoring feature captures the key metrics for your app that are relevant from a quality perspective, and then rates your app based on the metrics. The guiding principle is to help you ensure app quality and performance while you’re developing your app, and not as an afterthought. For more info, see App monitoring for Windows Phone 8.
Simulation Dashboard. You can use the Simulation Dashboard in Windows Phone 8 to determine in advance how your app will respond to real-life conditions. With this info, you can adjust your app to ensure that the app performs well in various real-life scenarios, and that your users are satisfied with the app.
You can use the Simulation Dashboard to test how your app will respond to the following conditions:
A low-bandwidth connection or poor signal
An interruption, such as a reminder or notification
The lock screen
For more info, see Simulation Dashboard for Windows Phone 8.
Screen shots. You can now capture screen shots of your app running on a physical phone by using a special key combination. For more info, see How to create screenshots for the Store for Windows Phone 8.
Store Test Kit. The Marketplace Test Kit is renamed the Store Test Kit. The Capabilities Validation test is not available for apps that target Windows Phone 8.
Tiles and notifications
Windows Phone 8 includes new Tile sizes, and new Tile templates, accessible with the following classes:
For more info about new Tiles in Windows Phone 8, see Tiles for Windows Phone 8.
Lock screen
In Windows Phone 8, a user can use your app as the lock screen background image provider, and choose to include your app in the lock screen notification area. For more info about using new lock screen capabilities in your Windows Phone 8 app, see Lock screen notifications for Windows Phone 8 and Lock screen background for Windows Phone 8.
Maps and navigation
Maps
Windows Phone 8 has a new Map control, available through the following namespaces:
For more info about the new Map control, see Maps and navigation for Windows Phone 8.
For useful extensions to the Map API, including a Pushpin, download the Windows Phone Toolkit.
Navigation
In Windows Phone 8 you can use the navigation protocol with the ms-drive-to or ms-walk-to Uri schemes to write an app that requests driving or walking directions, or to write an app that handles requests for driving or walking directions. For more info, see How to request driving or walking directions for Windows Phone 8 and How to respond to requests for directions for Windows Phone 8.
Location
Windows Phone 8 provides a new Windows Phone Runtime-based API set for getting the phone’s current location. The existing .NET Location API is still supported. For more info about the new APIs, see Location for Windows Phone 8.
Another new feature in Windows Phone 8 is the ability for location-tracking apps to continue to run in the background after the user navigates away from the app. This enables scenarios like run tracking and turn-by-turn navigation apps.
Speech
In Windows Phone 8, users can interact with your app using their voice. For more info about using new speech features in your Windows Phone 8 app, see Speech for Windows Phone 8.
Wallet
Windows Phone 8 introduces the Wallet, which app users can use to do the following:
Collect coupons, credit cards, memberships, loyalty cards, and more in one place.
Manage the payment instruments that they use in the app and music store.
Link items in the Wallet to apps on their phone.
Make contactless transactions, using Near-Field Communication (NFC), in some markets.
The Wallet gives app developers the ability to provide users with a richer experience by integrating with their Wallet items. Using the functionality provided through the Wallet namespace, you can create, read, write, and delete Wallet items from your app. Through the Windows Phone 8 Wallet experience, you can keep items up-to-date by using agents, and interact with the user with status messages and custom fields. The Wallet integration is additional functionality that allows you to better reach customers by being able to engage with them on an additional new surface area. In addition, Wallet items enable users to deep link in to your app so that you can provide a more meaningful in-app experience. For more info about the Wallet in Windows Phone 8, see Wallet for Windows Phone 8.
Multi-resolution
Windows Phone 8 supports WVGA, WXGA, 720p, and 1080p devices. The following table lists the new resolutions. All of these resolutions are supported in Windows Phone 8 Emulator.
For more info about multi-resolution support in Windows Phone 8 Update 3, see Multi-resolution apps for Windows Phone 8.
Direct3D and games
In addition to native development, Direct3D is being added to the family of Windows Phone technologies. This means that for the first time, a Direct3D-based PC game can share much of its code base with a phone version, and developers can use state-of-the-art middleware tools and engines that power the industry’s biggest game titles to develop games for Windows Phone.
Direct3D app refers to apps that are written entirely in native code, and which use only Direct3D for their UI. This type of app uses a completely different app model than managed apps, and can’t use many of the features of managed apps, such as live Tiles and push notifications. However, in Windows Phone 8 several new features were added for Direct3D apps to provide software keyboard input support, device theme, and screen resolution detection, and a set of Launchers and Choosers for adding many common phone tasks to your Windows Phone app. For more info about the native Direct3D app model and the features available to this type of app, see Direct3D app development for Windows Phone 8.
Also, you can use the DrawingSurface and DrawingSurfaceBackgroundGrid controls to incorporate Direct3D graphics into managed apps to take advantage of managed code features with a very small performance loss. Windows Phone 8 supports a subset of the Direct3D library at the 9_3 feature level. For info about Direct3D feature support and compatibility, see Direct3D for Windows Phone 8. For info about using Direct3D from managed apps, see XAML and Direct3D apps for Windows Phone 8.
In addition to Direct3D graphics support, you also have access to Microsoft Media Foundation APIs for playback and capturing audio and video. Also, the native audio libraries, XAudio2 and WASAPI, are now supported on the phone. For more info, see Walkthrough: Using Microsoft Media Foundation for Windows Phone 8 and Native audio APIs for Windows Phone 8.
App models
Windows Phone 8 supports two distinct app models on which you can base your app.
XAML
XAML is a declarative language that you can use to create user interface elements, such as controls, shapes, and text. XAML app development is primarily used by C# and Visual Basic developers to build general purpose apps. Existing Windows Phone apps that were written using these techniques are fully compatible with Windows Phone 8. XAML-based apps have gained new features such as new controls and auto-scaling to high resolution. XAML apps can reuse C++ code by including it in a Windows Runtime Component. New project templates allow you to incorporate Direct3D graphics into XAML apps. For more information about XAML, see User interface for Windows Phone 8.
Direct3D
Direct3D app development is an attractive choice for developers who want the graphics capabilities of Direct3D. It is primarily used by C++ developers to build games that require high performance. For more information, see Games for Windows Phone 8 and Direct3D app development for Windows Phone 8.
HTML
HTML-based phone apps aren’t a supported app model in Windows Phone 8. However, a developer can create a managed app with a XAML front end that uses an embedded browser control to display local HTML content, and it’s possible to access phone APIs by using the InvokeScript method and ScriptNotify events. Also, in Windows Phone 8, the phone’s browser has been upgraded to Internet Explorer Mobile 10, with a host of new features such as a robust HTML5/CSS3 implementation, Scalable Vector Graphics (SVG), ES5, IndexedDB, gesture events, and the addition of the high-performance scripting engine, creating new, interesting possibilities for Windows Phone 8 HTML developers.
For more information about developing with Internet Explorer Mobile 10, see the Internet Explorer 10 Guide for Developers.
Camera and photos
Windows Phone 8 introduces Lenses, the ability to auto-upload photos to a web service, new ways to extend the photos experience, and advanced capture APIs from the Windows Phone Runtime. This release also includes enhancements for working with photos.
Lenses
In Windows Phone 8, you can create a camera app called a lens that appears in the Windows Phone built-in camera app. A lens gives the user a consistent entry point into the viewfinder of your app. The lens feature is a type of extensibility available to apps that provide unique camera functionality via the camera APIs. As a lens, your app provides the user with a viewfinder experience and interacts directly with the camera. For more info, see Lenses for Windows Phone 8.
Working with photos
New extension methods have been added for the Picture class, including GetPreviewImage and GetPath. Use GetPreviewImage to help improve performance for displaying photos on the screen. This method returns photos in a resolution—WVGA, WXGA, or 720p—that is optimized for the user’s phone. The GetPath method returns the full path of the image in the media library; you can use this path to uniquely identify a photo. To use these methods, add a directive to Microsoft.Xna.Framework.Media.PhoneExtensions.
A new Launcher has been added, ShareMediaTask. Through the ShareMediaTask class, your app can directly access the share picker, so users can share photos like they do using the built-in photo viewer. For more info, see How to use the share media task for Windows Phone 8.
In addition, the PhotoChooserTask task now returns a more user-friendly file name. In the event handler, the OriginalFileName property returns the actual file name of the photo. For more info, see How to use the photo chooser task for Windows Phone 8.
Photo extensibility
Windows Phone 8 introduces new ways to extend the photos experience in Windows Phone. In addition to extending the Photos Hub, the photo apps picker, and the share picker, your app can now integrate with the photo edit picker or register as a rich media editor. For more info, see Photo extensibility for Windows Phone 8.
Auto upload
In Windows Phone 8, your app can automatically upload photos to a photo storage service using a resource-intensive background agent. By registering your app as an auto-upload app, your background agent can run without expiration. For more info, see Auto-upload apps for Windows Phone 8.
Advanced capture APIs
For apps that require fine control of the camera, the Windows Phone Runtime includes advanced capture APIs from the Windows.Phone.Media.Capture namespace. Use the PhotoCaptureDevice class to control photo properties such as ISO, white balance, and exposure. You can even programmatically adjust the focus position. The AudioVideoCaptureDevice class offers a similar level of control for video and audio recording. For more info about advanced capture APIs, see Capturing photos for Windows Phone 8 and Capturing video for Windows Phone 8.
In addition to those APIs, Windows Phone 8 provides a set of interfaces exclusively for native code. These interfaces provide access to uncompressed photo data and encoded audio/video samples. There also is a method you can use to fill a Direct3D 2-D texture with the current preview frame. For more info, see Camera APIs for native code (Windows Phone 8).
Media
Music media library
In Windows Phone 8 you can add and remove music files from the user’s music collection with the SaveSong and Delete methods that extend the MediaLibrary class. This new API is in the Microsoft.Xna.Framework.Media.PhoneExtensions namespace in the assembly Microsoft.Xna.Framework.MediaLibraryExtensions.dll.
Pictures media library
In Windows Phone 8, new GetPreviewImage extension method of the Picture class.
You can get the path to a picture with the new GetPath extension method of the Picture class. Use this method to provide a value for the FilePath property of the ShareMediaTask when the user wants to share a picture.
This new API is found in the Microsoft.Xna.Framework.Media.PhoneExtensions namespace in the assembly Microsoft.Xna.Framework.MediaLibraryExtensions.dll.
Background audio
In Windows Phone 8, you can capture info about the state transition from the PlayStateChangedEventArgs when the state of the BackgroundAudioPlayer changes. You can determine both the CurrentPlayState and the IntermediatePlayState that occurred before the audio player entered the current play state.
Here are some examples of the state transitions that you can handle with the info provided by the new event arguments:
For more info about background audio, see Background audio overview for Windows Phone 8.
User interface
Controls
Windows Phone 8 features the following new controls:
Windows Phone 8 includes a LongListSelector control that you can use to group, display, and scroll through long lists of data. It also provides a mechanism for users to jump to a specific section of a list.
In Windows Phone 8, Pivot and Panorama controls have been removed from the SDK and are now located in the phone’s read-only memory (ROM). This way your app can use a separate native input thread, which means a significant increase in the input responsiveness of these controls. The working set memory of the Panorama control also has been reduced.
The WebBrowser control is now based on Internet Explorer 10, which offers HTML5 and expanded CSS support for richer in-browser experiences.
The performance of the ProgressBar control has been improved. You should use this control to report value-based or indeterminate progress.
Launchers
You can use Launchers in your Windows Phone 8 app to help a user perform common tasks. The following Launchers are new in Windows Phone 8.
For more info about new Launchers in Windows Phone 8, see Launchers for Windows Phone 8.
Communications
VoIP
With Windows Phone 8, you can create Voice over IP (VoIP) apps that allow users to make audio and video calls over their data connection. VoIP apps are integrated into the built-in phone experience so that, for example, incoming calls are displayed using the same phone UI as regular cellular calls. For more information, see VoIP apps for Windows Phone 8.
Bluetooth
Bluetooth is a wireless communication technology that devices within a 10-meter proximity can use to communicate with each other. You can use new Bluetooth API introduced in Windows Phone 8 to create apps that communicate with other phones using Bluetooth technology. Core Bluetooth scenarios for Windows Phone 8 include app-to-app and app-to-device communication, and open up a wide range of possibilities you can use to make your app more connected. For more info, see Bluetooth for Windows Phone 8.
Proximity
Windows Phone 8 introduces a new API, the Proximity API that you can use to create apps that do the following:
Send data between devices using NFC.
Use a phone to interact with NFC tags.
Establish a Wi-Fi or Bluetooth connection between your app and an instance of your app on a proximate device.
On two phones that each have a Near-Field Communication (NFC) chip, app users can perform these scenarios simply by tapping their phones together.
For more info about Proximity, see Proximity for Windows Phone 8. Proximity on Windows Phone 8 also enables app-to-app connection using Bluetooth technology. For more info about Bluetooth for Windows Phone 8, see Bluetooth for Windows Phone 8..
Data sense
Windows Phone 8 introduces the new Data Sense feature which you can use to help your app users save money by staying within the limits of their data plans. In the Data Sense feature, a user can specify the limits of their data plans, and then Data Sense monitors data usage in relation to these limits. With this info, an app can help users save money by reducing data usage when the user is close to their data limit, or by discontinuing data usage when the user is over their data limit.
For more info about Data Sense in Windows Phone 8, see How to adjust data usage using the Data Sense API for Windows Phone 8.
Data and extensibility
Storage
Windows Phone 8 aligns with Windows 8 to support a subset of storage APIs from the Windows Runtime and Win32. This release also introduces the Microsoft.Phone.Storage namespace, a new .NET API for reading from an SD card. For more info, see Data for Windows Phone 8 and Reading from the SD card for Windows Phone 8.
Custom contact store
You can design your Windows Phone 8 app to create a set of contacts that are owned exclusively by the app, but which are visible through the built-in phone experience. APIs are provided to create, update, delete, and query the app’s contacts, as well as to sync the app’s contact list with a remote list maintained by the app’s cloud service. For more info, see Custom contact store for Windows Phone 8.
File and URI associations
You can use file and URI associations in Windows Phone 8 to automatically launch your app when another app launches a particular file type or URI scheme. For example, a file association allows your app to launch to handle an email attachment. You can also use the association-launching API to launch another app based on a specific file type or URI scheme. For more info, see Auto-launching apps using file and URI associations for Windows Phone 8.
Search extensibility
When you extend the Search experience in Windows Phone 8, quick cards pass more info to your app. There is also a new quick card for events, the event card. These changes are summarized in the following table.
For more info about these parameters, see Search extensibility for Windows Phone 8.
Windows Phone Store
In-app purchase
In-app purchasing gives developers the ability to create apps or games that sell virtual products for real money. Microsoft servers host the catalog products that are available for in-app purchasing, including price and descriptive metadata. Microsoft also provides a commerce infrastructure, including methods for users to pay in 190 regions around the world.
For each product that users can purchases through in-app purchasing, a developer enters a description in Windows Phone Dev Center, in addition to prices for each region where users can make the in-app purchase. Using the APIs in Windows Phone 8, a developer can list, within an app, the products that are available for users to purchase in that app. Developers don’t need to write special code for handling different types of purchase instruments. All purchase methods that users can use to purchase apps and games are supported for in-app purchasing. The app or game must host and deliver any content associated with the in-app product. For more info, see In-app purchase for Windows Phone 8.
Ready for Business
Windows Phone 8 makes it easy to build and deploy apps to phones enrolled in your enterprise. For info about the process of enrolling phones in your enterprise and deploying apps to them, see Company app distribution for Windows Phone.
Localization and globalization
In Windows Phone 8 you can create apps that read from right to left, and apps that use bidirectional languages. For more info about using new localization and globalization features in Windows Phone 8, see Creating bidirectional apps for Windows Phone 8.
You now have the ability to define a default culture for an app domain. For more info, see the CultureInfo class.
App manifest file
New capabilities have been added to the app manifest file to support new features such as Bluetooth and Near-Field Communication (NFC). You can also specify the hardware required by your app using the requirements section to help ensure that the app is downloaded and installed by users with phones that can successfully run the app. For more info about the new capabilities and hardware requirements in Windows Phone 8, see App capabilities and hardware requirements for Windows Phone 8.
In addition, editing the manifest file is now much easier using the Manifest Editor tool that is built-in in Visual Studio. For more info about how to edit the app manifest file, see How to modify the app manifest file for Windows Phone 8.
App compatibility
Windows Phone 8 introduces some APIs that work differently than the same APIs work in a Windows Phone OS 7.1 app. For details about these differences and how they affect you as you prepare to develop your app, see App platform compatibility for Windows Phone 8.
In many cases where an API behaves differently in Windows Phone 8 than it does in Windows Phone, the API is quirked. That is, for apps that target Windows Phone OS 7.1, the API automatically behaves as it did in Windows Phone OS 7.1. For apps that target Windows Phone 8, the API has a new behavior. For more info, see the "Quirks mode behavior in the .NET Framework" section in App platform compatibility for Windows Phone 8.
Common language runtime
The common language runtime in Windows Phone 8 offers the following new features and differs from Windows Phone in the following areas:
Code generation
Windows Phone 8 uses a new strategy of compiling apps in the cloud for enhanced startup performance. To ensure that developers are able to execute their app as it would run on an app user’s device, the appropriate tools have been provided as part of Windows Phone SDK 8.0.
Inlining support in Windows Phone 8 is improved; manually inlining code is no longer necessary.
Code generation by the JIT compiler has been optimized.
Threading
The .NET Framework is multi-core aware. Apps can create threads, use the ThreadPool class, the Task Parallel Library, and all the synchronization primitives to leverage multiple cores.
Support for multiple cores may cause APIs like Thread..::.Sleep to behave differently.
Security model
- The managed sandbox has been removed. As a result, a security exception, such as a MethodAccessException, that was expected in Windows Phone OS 7.1 may not be thrown in Windows Phone 8.
Garbage collection
The garbage collection heap in Windows Phone 8 has three generations, not two generations as it does in Windows Phone OS 7.1.
In Windows Phone 8, the garbage collector has a large object heap (LOH).
Background garbage collection is not available in Windows Phone 8.
The phone's resource manager invokes a garbage collection when an app approaches the memory cap and will terminate the app if it exceeds the memory cap.
The runtime's auto-tuned garbage collection triggers can be impacted by an app's forced garbage collections.
In Windows Phone 8, the performance of per-thread allocation by the garbage collector is improved.
Portable Class Libraries
The Portable Class Library project in Visual Studio 2012 gives you the ability to write and build managed assemblies that work on multiple .NET Framework platforms. Using a Portable Class Library project, you choose the platforms (such as Windows Phone 8 and .NET for Windows Store apps) to target. The available types and members in your project are automatically restricted to the common types and members across these platforms.
Portable class libraries that target Windows Phone OS 7.1 and Windows Phone 8 can be used on Windows Phone 8. Note that a portable class library that targets Windows Phone OS 7.1 but runs on Windows Phone 8, runs as a Windows Phone 8 app. For more info, see Cross-Platform Development with the .NET Framework.
Interop
Apps can invoke first-party Windows Runtime APIs from managed code.
COM interop and P/Invoke are not supported.
General performance
In Windows Phone 8, the performance of asynchronous and parallel operations that use types in the System.Threading.Tasks namespace has been improved. In addition, the stream classes now include asynchronous methods to take advantage of the asynchronous features added to the C# and Visual Basic languages. For more info, see Asynchronous File I/O in the .NET Framework Version 4.5 documentation.
The performance of virtual calls in Windows Phone 8 has been improved.
The implementation of Fast Application Switching is improved in Windows Phone 8. When a switch from the active application occurs, its managed execution is paused. Once an application is paused, the common language runtime guarantees 0 CPU utilization, and all of the application's timeouts are virtualized.
See Also
Other Resources
App platform compatibility for Windows Phone 8 | https://docs.microsoft.com/en-us/previous-versions/windows/apps/jj206940(v=vs.105) | CC-MAIN-2018-30 | refinedweb | 6,027 | 54.73 |
I found a 'nice and clean' way to check if a variable is assumed to be integer.
The only objection to calling it 'nice and clean' is that it uses the hidden attribute
_assumption, which does not exist as a method. This could be a feature request, and it would not be hard to implement.
In short, this checks if the variable 'a' is assumed to be integer:
sage: a = var('a') sage: assume(a, 'integer') sage: 'integer' in (x._assumption for x in assumptions(a)) True
(Tested in Sage Version 6.3.beta5, released on 2014-07-01, but I'm sure this has been possible for a long time.)
How could one find out about this? By exploring Sage using tab-completion and introspection.
sage: version() # for reference 'Sage Version 6.3.beta5, Release Date: 2014-07-01' sage: a = var('a') sage: assume(a, 'integer') sage: h = assumptions() sage: h [a is integer] sage: ha = assumptions(a) sage: ha [a is integer] sage: d = assumptions(a)[0] sage: d a is integer sage: type(d) <class 'sage.symbolic.assumptions.GenericDeclaration'>
Now use the 'tab' key to check what methods are available for
d:
sage: d. d.assume d.contradicts d.dump d.forget d.rename d.save d.category d.db d.dumps d.has d.reset_name d.version
and keep exploring:
sage: d.has(a) True sage: from sage.symbolic.assumptions import GenericDeclaration as GDecl
Read the documentation for
GDecl, then the source code.
sage: GDecl? sage: GDecl??
and detect the use of the
_assumption attribute in the source code. Now play with it!
sage: d._assumption 'integer' sage: 'integer' in (x._assumption for x in assumptions(a)) True
This is beyond the scope of answering your question, but just in case someone finds it interesting and wants to open a trac ticket or two and/or change the code accordingly.
a method 'assumptions' for the class
sage.symbolic.assumptions.GenericDeclaration.
make the
is_integer method check for the 'integer' assumption as above, for symbolic variables. So far:
sage: a.is_integer() False
However the source code for this method is
def is_integer(self): """ Return True if this expression is known to be an integer. EXAMPLES:: sage: SR(5).is_integer() True """ return self._gobj.info(info_integer)
in particular the docstring claims it should return True if the expression is known to be an integer. | https://ask.sagemath.org/answers/23440/revisions/ | CC-MAIN-2020-50 | refinedweb | 396 | 57.57 |
The event builder itself is a loadable Tcl package rather than a program. This allows experiment designers to:
Provide application dependent user interfaces on top of and around those provided by the event builder.
Tailor the operation of the event builder to meet application specific requirements.
The example below is a Tcl script fragment that shows how to start the event builder. The code assumes that the environment variable DAQROOT has been set to the top installation directory of the NSCLDAQ being used (version 10.2 or later).
Example 41-3. Starting the event builder
lappend auto_path [file join $::env(DAQROOT) TclLibs]
package require EventBuilderpackage require EventBuilder
EVB::Start ?name?EVB::Start ?name?
auto_pathwhen tclsh or wish starts.
nameparameter specifies the event builder name. Note that if you provide a duplicate name,the script will attempt to pop up a Tk dialog prompting you to continue or not.
When this proc has returned, the event builder is listening for connections on that port and the client library will be able to find the event builder.
This proc must be called prior to any other procs in the EVB:: namespace. | http://docs.nscl.msu.edu/daq/newsite/nscldaq-11.0/x8824.html | CC-MAIN-2017-30 | refinedweb | 189 | 64.51 |
A tool for demux ts/mp4/flv by typescript.A tool for demux ts/mp4/flv by typescript.
This tool can be used on platforms such as HTML5 players or Node.js
Data flow diagramData flow diagram
FeatureFeature
Support push streaming-data to demux
Tree-shakable (The version coded with full code does not need to worry about the reference size. When the business only refers to a certain format of decoding, the overall code supports tree-shaking)
Any-combination packaging (These formats can be packaged according to requirements, users do not need to package all the code)
DemosDemos
How to start?How to start?
install
npm i demuxer
Setup
import { TSDemux, FLVDemux, MP4Demux, Events } from 'demuxer'; const demux = new TSDemux(); // const demux = new FLVDemux(); // const demux = new MP4Demux(); // The data is spit out in a streaming manner, // and the first data is emitted as soon as possible. demux.on(Events.DEMUX_DATA, (e) => { console.log(e); // if (e.stream_type === 15) { // console.log(e) // } }); demux.on(Events.DONE, (e) => { // consumed & flushed all piped buffer. }); // buffer -> video bytes ArrayBuffer demux.push(buffer, { // Support push part of the data for parsing // When done is set to true, if the data is decoded and there is no remaining data, the data is considered to have been pushed and Events.DONE will be emitted. // When done is set to false, Events.DONE will not be emit, waiting for subsequent data push done: true });
Debug
var demuxer = new TSDemux({ debug: true });
Demuxer Options
let options = { // Setting options.debug = true; will turn on debug logs on JS console. debug: true }; var demuxer = new TSDemux(options); // var demuxer = new MP4Demux(options); // var demuxer = new FLVDemux(options);
About decoding MP4 raw data (h264/hevc/aac)About decoding MP4 raw data (h264/hevc/aac)
Developer should parse the data of the mp4 header, and then locate the pos of the data information in the mdat according to the information described in the mp4 header.
About how to integrate Demuxer with WorkerAbout how to integrate Demuxer with Worker
Because the third party is likely to be internally built by the worker tool, in order not to conflict and redundancy with the worker tool, the worker is implemented by the user. | https://www.npmjs.com/package/demuxer | CC-MAIN-2022-40 | refinedweb | 369 | 53.61 |
ex. connect to Oracle - Java Beginners
ex. connect to Oracle dear sir,
I want to ask how to connect java...);
e.printStackTrace();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println
JSP Tutorials Resource - Useful Jsp Tutorials Links and Resources
by progressing from very simple
examples to complex examples.
For best progress... working. The early examples might
seem very simple; please have patience... on the exercises, these are designed to
solidify your grasp of the material.
Struts
Struts How Struts is useful in application development? Where to learn Struts?
Thanks
Hi,
Struts is very useful in writing web applications easily and quickly.
Developer can write very extensible and high for beginners struts for beginners example
java material
Java programming tutorial for very beginners
Java programming tutorial for very beginners Hi,
After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners?
Thanks
Hi
Struts - Struts
Struts examples for beginners Struts tutorial and examples for beginners - Struts
Struts Provide material over struts? Hi Friend,
Please visit the following link:
Thanks
Hi.. - Struts
useful in the creation of HTML-based user interfaces.
struts-logic.tld...Hi.. Hi,
I am new in struts please help me what data write in this file ans necessary also...
struts-tiles.tld,struts-beans.tld,struts
SAP MM Study Material
SAP MM Study Material Please let me know where can i get the SAP MM study material an ask queries as well
-Controller (MVC) design
paradigm. Want to learn Struts and want get... of design are deeply rooted. Struts uses the Model-View-Controller design pattern...: you will learn to use Struts very
effectively.John Carnell
jsp online ex Alternative
Struts Alternative
Struts is very robust...-Controller (MVC) design paradigm. Most Struts applications use a browser as the client... as well as support for upload files. The default handler is a very simple Controller
Struts Guide
? -
- Struts Frame work is the implementation of Model-View-Controller
(MVC) design..., Action, ActionForm and struts-config.xml are the part of
Controller... is
the blank struts application which is useful in creating struts application Dear Sir ,
I am very new in Struts and want to learn about validation and custom validation. U have given in a such nice way to understand but little bit confusion,Plz could u provide the zip for address
Developing Struts Application
. This is not JSTL
but Struts Tag Library. We should note the following very carefully...Developing Struts Application
If we are asked to give a very brief
Struts - Struts
Struts hi
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean...("");
session.invalidate();
Thank you very much for answer
Fed Ex service (tracking number)
struts - Java Beginners
struts how to calculate monthly billing in struts, give me example
Spring Framework Tutorials
, Ajax, Struts, JSF and various other frameworks and hence considered to be very useful. Moreover, the Spring MVC components can be utilized for the development... will find a comprehensive range of Spring Framework tutorials for beginners
Struts Frameworks
Struts Frameworks
Struts framework is very useful in the development of web application. It is
based on the popular Model-View-Controller design pattern. The
Model-View-Controller design pattern is also known as MVC design pattern
Plz provide me all the material for Java
Plz provide me all the material for Java Plz provide me all the material for Java
Please go through the following link:
Java Tutorials
java struts - Java Beginners
java struts Hi sir
i need complete digram of struts... how i can configer the struts in my
eclipse... please send me the complete picture diagram
java struts - Java Beginners
java struts i want to do the project in the struts.... how i can configure the project in my eclipse... can u help me in this issues
wt are the futures in jdk 1.5 with clear ex
wt are the futures in jdk 1.5 with clear ex plese send me the correce ex
Know About Outsourcing, More About Outsourcing, Useful Information Outsourcing
and offshoring. For them, both terms mean the same, but this is not very accurate
Thank U - Java Beginners
Thank U Thank U very Much Sir,Its Very Very Useful for Me.
From SUSHANT
singleton class in struts - Java Beginners
singleton class in struts hi,
This balakrishna,
I want to retrive data from database on first hit to home page in struts frame work
Struts Interview Questions
are the disadvantages of Struts?
Answer: Struts is very robust framework and is being... pattern. Struts components can
be categories into Model, View and Controller... of Struts is part of Controller components
which works as front controller to handle
how to compile and run struts application - Struts
how to compile and run struts application how to compile and run struts program(ex :actionform,actionclass) from command line or in editplus 3
J2EE - Java Beginners
consentarate on j2ee(jdbc,servlets,jsp,struts).Then you can start XML.And also HTML(Which is very useful for habituating tag progrming which we can get like
the model
from view and the controller. Struts framework provides the following three... the
information to them.
Struts Controller Component : In Controller, Action class...In this section we will discuss about Struts.
This tutorial will
Unable to understand Struts - Struts
= "success";
/**
* This is the action called from the Struts...(SUCCESS);
}
catch(Exception ex...;
}
catch(Exception ex)
{
out.println(ex.toString... in their country and spend some time there. This
helps to a better understanding
Very simple `Hello world' java program that prints HelloWorld
Hello World Java
Simple Java Program for beginners (The HelloWorld.java)
Java is powerful programming language and it is used... this output
Hello, world!
Understanding the HelloWorld.java code
Let's
JTable - Java Beginners
back. thank you very much sir for your help. i am new to java and your help is very useful for me.
import java.io.*;
import java.sql.*;
import java.awt....();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(p,"Exp
Struts iteraor
Struts iteraor Hi, I am making a program in Struts 1.3.8 in which i have to access data from mysql. I am able to access data but data is not coming..."));
}
catch(Exception" %>
<
Detailed introduction to Struts 2 Architecture
the action very easily.
Expression Language
Struts 2 expression language...
Detailed introduction to Struts 2 Architecture
Struts 2 Framework Architecture
In the previous section we learned
Hello - Struts
user to change the detail by some means outside the program.
for ex.
class
JavaScript open() method
;
This open() method is very useful for the programmers. Here is a case when
this might be very useful. Suppose you are filling some information...
information filled in that form. So here the JavaScript's open() method
may be
Developing Simple Struts Tiles Application
To Create Tiles Application
Tiles is very useful framework for the development of web...
Developing Simple Struts Tiles Application
... will show you how to develop simple Struts Tiles
Application. You will learn
hi... - Struts
also its very urgent Hi Soniya,
I am sending you a link. I hope
Outsourcing Communication Tips,Useful Cultural Tips in Offshore Outsourcing,Communication and Culture Tips
into difficulties due to communication problems. The trend is very prominent in both... include the ability to listen and check their understanding, elicit and manage
Hi - Struts
please help me. its very urgent Hi friend,
Some points to be remember
Struts Video Tutorials
and
in less time. Struts Video tutorials are very extensive and explained... will be
able to learn Struts framework very easily with these tutorials... design pattern.
Application developed in Struts 2 framework is very Format Examples
Struts 2 Format Examples
In this section you will learn how to format Date and numbers in Struts 2
Framework. Our Struts 2 Format Examples are very easy to grasp and you will
learn these concepts Projects
.
Understanding
Spring Struts Hibernate DAO Layer... or the Struts ActionServlet. It is very fast and enables the user to manipulate...
Struts Projects
Easy Struts Projects to learn and get into development
java - Java Beginners
programmer, any pattern is there to learn programming in java, i need struts coding how to do very easily pls anybody tell me, any process is there to learn
Regards
somu Hi friend,
For learning Struts visit to :
http
Useful SEO Articles - 5 Killer Tips for Writing SEO Articles for Home-Based Online Business Ideas
are typed by Internet
users while searching for some material in search engines | http://roseindia.net/tutorialhelp/comment/2674 | CC-MAIN-2014-15 | refinedweb | 1,425 | 57.27 |
senior full stack engineer, building highly scalable Python backends and performant React apps
We all know that building content platforms is hard. You are constantly fighting misinformation, spam, and undesired ads—mostly from bots, the plague of the modern web. Some estimate that two-thirds of links posted on Twitter can come from bots.
So how can you fight them?
You could constantly monitor your website, manually checking for new entries, or you could leave it up to your users, waiting for them to report platform abuse. However, both solutions are slow and tedious.
A type of automated filtering is probably the best, if imperfect, solution. However, if you’re running a smaller site, the best way may be to receive automated notifications about new content!
In this article, I’ll show how to build such a tool (using MuleSoft, Heroku, and this guide) to send notifications to Slack when new content is entered into a content platform.
Some artists say that everything has already been created. Some agree, and some don't. However, if developers are artists, then one thing is certain: In 2020, much of an apps core functionality has probably already been developed. If your core business is a bespoke content platform, why would you invest your time building integration software? A better strategy is to use software that has already been battle-tested and is just a few clicks away from working.
Anypoint by MuleSoft is that platform. It creates connections between services like CRMs, communication tools, and databases. Then it allows you to transfer data between those services when certain events take place. For example:
When your app has a new user, create a new lead in SalesforceWhen a photo is sent in Slack, save it to S3 and add to your website when new content is uploaded to your Heroku app, send its summary to Slack so the moderators can review it as quickly as possible
... and you probably already know which use case we will explore in the rest of the tutorial 😉
For the purpose of this article, we will deploy an open-source project, Pythonic News on Heroku. Pythonic News is a clone of Hacker News written in Python/Django. With slight modifications, I made the app Heroku-deployable without any additional configuration. The detailed process is described below. Run in production at your own risk! (Please don't 😅)
Hacker News gets an enormous amount of traffic every day and content quality is a serious business for the moderators. Fortunately, we already have our strategy to deal with this problem, so let's go ahead and build the content moderation system.
To take full advantage of the Anytime platform, we need to run a JDBC compliant database like Postgres. Fortunately, Heroku allows us to run a Postgres database for free and there is even documentation on plugging it to MuleSoft's Database Connector. The modifications mentioned above include running Postgres instead of Django's default Sqlite, so we are good to go. 👍
Now let’s look at the steps needed to build the whole system.
(Note: You can skip this part and use my deployed fork of pythonic-news.)
Let's start by cloning the original Pythonic News repo:
git clone git@github.com:sebst/pythonic-news.git
The project is complete and working, however, before we deploy it, we need to take three additional steps.
1. Install Gunicorn and add Procfile for Heroku
We’ll use Gunicorn as our web server (because you should never run ./manage.py runserver in production).
pip install gunicorn
Procfile is the configuration file for Heroku. We will guide our Heroku app to apply migrations on the release and use Gunicorn to serve the app.
2. Change the Database to Use Postgres
I prefer to run the same database locally as in production, so I added the support for the Postgres config. The snippet below will:
release: python manage.py migrate web: gunicorn hnclone.wsgi
Locally search for POSTGRES*** environmental variable and if none is found, connect to an open database ‘pythonic_news’.In Heroku, it will read the DATABASE_URL variable, which will automatically show up in our Heroku Config Varsafter setting up a Postgres Add On.
import environ # settings.py env = environ.Env() DB_USER = env("POSTGRES_USER", default="postgres") DB_PASSWORD = env("POSTGRES_PASSWORD", default="") DB_PORT = env("POSTGRES_PORT", default="") DB_NAME = env("POSTGRES_NAME", default="pythonic_news") DB_HOST = env("POSTGRES_HOST", default="") DB_CONFIG_URL = f"postgres://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}" DATABASES = {"default": env.db("DATABASE_URL", default=DB_CONFIG_URL)}
3. Do Some Miscellaneous Changes That Are Definitely NOT Production Ready But Worked for Me 🤷🏻♂️
For me it was DEBUG=True, so the static files work locally. For you it may be something totally different! The project setup is not the essence of this tutorial, so we will skip to the next part.
We’ll assume that you already have a Slack workspace (you probably wouldn’t read this article otherwise), so the next step is to create a Slack app and connect it to a selected channel. To do this, let’s head over to click the "Create App" button.
Then, when the app is created, you will be prompted to select the functions and permissions that your bot needs.
In our case, we will need to enable incoming webhooks and chat:write. In true Linux fashion, always remember to use only the minimal set of permissions that the app needs!
Looks great! Now let’s connect the app to the channel in the menu in the right-hand side panel.
Ready! Now, when MuleSoft sends a message to the chat, we are ready to receive it.
Now on to the fun part! We have our application with a database. We have Slack. Let's connect them!
Login to MuleSoft Anypoint and create a new project.
After choosing "Create new application", we will be prompted to choose an event listener and a receiver.
In the first case, choose a "Database connector" that will listen on new row entries.
For the receiver, choose Slack and "Post new message" (duh!).
Now it’s configuration time!
For database configuration, we will use the tutorial written by Heroku on connecting their data products with MuleSoft. Once it's ready, we should be able to choose a table that we want to listen on and select which column plays the role of an id. A watermark column will mark which rows have already been seen by our connector. In this case, we will select the item_ptr_id for both cases.
🎉 Congratulations! The database is now properly configured! Let's set up the Slack messages.
First, let’s connect to the Slack app that we created. Again, for this, we will use an existing tutorial.
Once the Slack connection is live, MuleSoft will automatically detect what data we can obtain from the selected table and will present it in the right-hand panel. Now you just need to select a channel to post the messages to, write the message you want to post, and drag-and-drop the values from the right to the correct places. And once you're done...
The whole flow is done as well! Now head over to test it (with a short-term MuleSoft deployment) or deploy it so the connection lives after you exit the platform.
Let's take it for a spin and receive some Slack notifications.
Pythonic News UI is really simple — by design. To submit a link, the user clicks the "submit" button and proceeds with filling out the form.
Message posted, and boom 💥
Our app informed me about the new submission. Now, I can go to the admin panel, and mark it as "spam", because it doesn't have anything to do with Python. 😅
(Actually, it wasn't this easy...)
But, hey, we got there eventually!
Naturally, the process wasn’t as smooth as it looks in this write-up. During development, the following issues forced me to stop and rethink some details:
1. You need to upload your own JDBC driver
While Postgres is JDBC-compliant, you need to upload and specify the driver on your own. This has proven to be problematic, because once you enter the official Postgres website, there are over 50 different available drivers to download. I went with version 42.2.1, one recommended by MuleSoft. However, it is not the newest one.
2. Slack token
While creating the Slack app, you may very easily over complicate things by choosing the OAuth authentication flow instead of the token. While OAuth is certainly recommended for more complex projects, the token authentication will work just fine in our case. Simply copy the access token from OAuth & Permissions tab. It starts with xoxb- followed by a random string and needs to be passed to MuleSoft during Slack integration.
3. Watermark
When the whole flow worked correctly for the first time, my Slack was bombarded with tens of messages per second. This was caused by not setting up the Watermark field in Database Connector. It caused MuleSoft to forget which rows had been seen before. Because of that, with every iteration, a message was sent to the channel for each database entry. It was a complete mess! Putting the watermark on a column with a unique ID solved this problem.
Automating one’s business is easier than ever. Tools like Heroku allow us not to worry about infrastructure management, and MuleSoft will simplify complex business integrations to drag-and-drop fun. What a time to be alive!
I hope that this tutorial will help you set up your own integrations and save you a ton of precious time in the outcome. Good luck!
Also published on:
Create your free account to unlock your custom reading experience. | https://hackernoon.com/how-to-use-mulesoft-to-send-slack-notifications-when-data-changes-tz2s34vc | CC-MAIN-2021-17 | refinedweb | 1,616 | 65.12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.