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 |
|---|---|---|---|---|---|
I think I agree with you on most of your negatives, but none of them are
likely to change any time soon. Specific comments:
On Fri, 2002-01-25 at 11:33, Eric M. Hopper wrote:
> Using Berkeley DB extensively is a bad idea. Plain text files much more
> readable. Keep seperate revisions in seperate files or seperate
> directories. Take advantage of the filesystem as a database. Using
> Berkeley DB essentially creates an extra superfluous namespace. Try
> reading reiserfs naming system docuement
> () to understand why this is a bad
> idea.
I agree, and I think we're starting right now to see some added
difficulty in debugging Subversion problems because we're using db.
(It's hard to know for sure without going back in time, doing it without
db, and seeing if these problems became easier to fix.). :)
> Having a single tree version number is bad too. It becomes harder to
> get an intuitive sense of changes to individual files. It's also hard
> to create merged trees this way. Especially if tags just refer to a
> partiular tree version number.
I'm undecided on the single tree version. I think it puts us in a bad
situation when it comes to distributed repositories or repository data
which comes from other sources. On the other hand, it has some very
nice properties; commit atomicity comes for free, for instance.
Anyway, I'm not sure you've learned yet how Subversion does tags and
branches. Subversion just provides cheap directory copies; it doesn't
have a namespace for tags and branches separate from the regular
repository namespace.
> I think having structureless version numbers may be a bad idea. It's
> useful to know, at a glance, which versions belong to which branch, and
> to be able to see the branch history of a file in its version history.
> Taking information out of version number just removes it from clear view
> and makes you have to look somewhere else for same info. Just because
> CVS had structured version numbers as a side effect of it's kludgey
> implementation in terms of RCS doesn't mean they're evil.
I think the Subversion method of doing branches and tags is... bold, but
worth experimenting with. It actually flows out of your arguments about
having a single namespace.
> Controlling subversion behavior based on MIME types may be a bad idea.
I'm a little nervous about that myself, but I think it's one of the
easiest things to change, so I'm not too nervous.
> WebDAV? Why? Seems like adding a useless layer to me.
I don't like it either. The application protocol world has been pulled
in two directions recently: one contingent wants to design the simplest
possible protocols from a birds-eye view, and the other contingent wants
to reuse protocol components--even if they are bulky, flawed, and full
of unneeded features--in order to reduce development time, get some
forms of compatibility between protocols, and in some cases to get
through firewalls. (Although, never bring up that last argument in an
IETF context; the IESG believes, probably correctly, that it's unethical
to deliberately subvert firewall policies by running a new protocol on
the same port as an existing protocol.)
I'm in the first camp, but it's hard to counter the arguments of the
second camp, and in my experience they generally win any time a system
is designed by a heterogeneous committee.
---------------------------------------------------------------------. | http://svn.haxx.se/dev/archive-2002-01/1026.shtml | CC-MAIN-2014-41 | refinedweb | 578 | 62.88 |
"Albert D. Cahalan" <acahalan@cs.uml.edu> wrote:> In spite of that, it should be considered. It allows this:> > $ ls -log /proc/self/fd> total 0> lrwx------ 1 acahalan 64 Sep 21 09:12 0 -> /dev/pts/4> lrwx------ 1 acahalan 64 Sep 21 09:12 1 -> /dev/pts/4> lrwx------ 1 acahalan 64 Sep 21 09:12 2 -> /dev/pts/4> lrwx------ 1 acahalan 64 Sep 21 09:12 3 -> mutex:[720429]> lrwx------ 1 acahalan 64 Sep 21 09:12 4 -> event:[592]> lr-x------ 1 acahalan 64 Sep 21 09:12 5 -> /proc/14527/fdLooks nice, I know, but it may mean file handles are indirect, in that youhave: struct file->struct dentry->struct inode->struct winefile->struct file->...if you can't store all the extra wine attributes on the struct file. It alsomeans that the inode or the dentry has to maintain a list of attached file's,which I don't think it does at the moment.> >> Any information not in kernel structure is Wine specific anyway, so> >> should be separate> > It goes into the kernel structure, so that it won't be Wine-specific.> SGI has already done this so that Samba would interact properly with> regular UNIX software and the NFS server.> > (one might support SGI's API for this)Hmmm... worth investigating. I take it that this was only done for IRIX, notLinux.> Yep, share bits definitely belong in the kernel. How else could> you properly protect against regular (clueless) Linux software?Probably do...> We already have 3 ways to do file locking, so this is only 33% more.66%... Don't forget LockFile/UnlockFile. These work very similarly to fcntl,I think, but demand mandatory locking.> Now THAT would be a disaster. Linux software ought to be able to rely> on having these features available.I agree, but does Linus?> Modules are very bad for this.Probably, but unless the code goes into the kernel proper, patch maintainancecan be a real nightmare. The greater the amount of kernel actually changed bya patch, the worse it is.> Named? That means you use the VFS.Not necessarily. For file handles, you probably should (unless you wantdrive-letter mappings to occur in the kernel - yuk), but the other things areeffectively in separate namespaces.>> Don't use it then... it'll not be mandatory. Wine has also to support OS's>> that can't or won't add Win32 support in the kernel.You misunderstand me... _Using_ this API will not be mandatory, whether or notit exists in the kernel proper.> See a pattern here? System calls are not supposed to be modular.knfsd? But I agree, really. But what is the likelyhood?> We shouldn't have calls that appear and disappear on a whim.True... that smacks of MS policy:-)> Binary compatibility requires that system calls be available on> all Linux systems.Also true. You should be able to compile the module I currently have on allLinux systems. Unfortunately, I can't test this at the moment.David Howells-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgPlease read the FAQ at | https://lkml.org/lkml/2000/9/21/31 | CC-MAIN-2016-18 | refinedweb | 530 | 66.74 |
KNIME and beginners
I gave a presentation at OpenEye's CUP last week. More precisely, I was assigned a talk with the title "Evils of KNIME." I don't chose that sort of name, but the CUP organizers like to be a bit confrontational with presentation titles. I used my speaking slot as a platform for expressing my views on dataflow/visual languages. I don't like them, and think their effectivity is limited compared to a text language, so I explained why. Other people do like them and enjoy them. I've asked them why, and they have some good reasons. My presentation outlined those responses with some observations of my own, including suggestions for ways to improve the text-based toolkits so they are more accessible to "non-programmers."
The next few posts will be based on parts of that talk. Feel free to leave comments.
Upcoming training classes (pre-announcement)
I ended by pointing out that these are technological solutions. Why not spend some time training computational chemists to be more effective at writing software? I provide that sort of training. If you are interested, email me. I'm pinning down the dates for a course in Leipzig in mid-May (likely 18-20 May), and another in Boston in late July. I'll announce them when the dates are determined. if you want to influence those dates or schedule a course at your site, let me know.
Sample test case for KNIME
I haven't used KNIME for about two years. That experience was with KNIME 1.x. People told me that it's gotten better, so I decided it was well time to take a fresh look. Last time I couldn't get it to work on my Mac. I'm happy to report that things have changed, although there are still some difficulties with it regarding updates.
My test case was the first example from the Chemistry Toolkit Rosetta, specifically, to compute the heavy atom counts from an SD file. The pybel solution is:
import pybel for mol in pybel.readfile("sdf", "benzodiazepine.sdf.gz"): print mol.OBMol.NumHvyAtoms()It's not as short as I would like because I had to specify "sdf" twice and because it had to reach down into the underlying OpenBabel molecule object. Still, it's a lot more succint than using any of the base toolkits directly, and a good reference of what a text-based programming language is capable of when designed for ease of use.
What molecular properties can I compute? And how do I do it?
The first step was to find out if KNIME could compute the number of heavy atoms. When I say "KNIME" I mean "the CDK nodes which come with KNIME" since KNIME is a dataflow-based visual programming language with support for a number of extension packages, including chemistry nodes based on the CDK. Schrodinger, Tripos, ChemAxon and likely other companies provide nodes based on their respective toolkits, but I don't have a license to those tools. In any case the Mac version of KNIME doesn't yet support adding new nodes.
The most likely candidate was "Molecular Properties." The help says:
Create new columns holding molecular properties, computed for each structure. The computations are based on the CDK toolkit and include logP, molecular weight, number of aromatic bonds, and many others.What other properties does it compute? I put the node on the workspace and double clicked on it to bring up the dialog box. The result is:
The dialog cannot be opened for the following reason:
No column in spec compatible to "CDKValue".
A Google search for that error message found the same question from 9 September 2009 although concerning a different node. Bernd Wiswedel answered:
We obviously need to improve on the error messages. You need to process the output of the SD reader with the "Molecule to CDK" node, which will parse the structures into an appropriate format for the Lipinski node. Reason is that the Lipinski node is contributed from the CDK plugin, so it needs its desired input format.What this means is the inputs need to be set up correctly before I can see more details. However, it's more complicated then that. If I set up the nodes as shown:
The dialog cannot be opened for the following reason:Turns out I need to put in a valid SD filename in the "SDF Reader" box (the one with the exclaimation point under it), in order to get the right inputs to "Molcule to CDK", in order to see the "Molecular Properties."
No column in spec compatible to "SdfValue" "SmilesValue" "MolValue" "Mol2Value" or "CMLValue".
How accessible is KNIME to first-time users?
Is that really friendly for first-time users? That is, how is a first-time user supposed to: 1) know which options are available if they can't open an unconnected node, 2) know which inputs are required for a node, or for that matter see what outputs are available, 3) know that the "SDF Reader" needs to be converted from "Molecule to CDK" before it can be used by the CDK nodes?
Of course all those can be explained in the documentation, and perhaps they are explained. I admit I haven't read it, but then again the knime.org documentation doesn't show how to use the CDK nodes. And should someone have to read the documentation in order to do something basic like this task? If so, are dataflow systems really any easier than working with a text-based programming language?
Can't compute the number of heavy atoms?
I looked through the list of properties which could be computed:
- Atomic Polarizabilities
- Aromatic Atoms Count
- Aromatic Bonds Count
- Element Count
- Bond Polarizabilities
- Bond Count
- Carbon connectivity index (order 1)
- Carbon connectivity index (order 0)
- Eccentric Connectivity Index
- Fragment Complexity
- Hydrogen Bond Acceptors
- Hydrogen Bond Donors
- Largest Chain
- Largest Pi Chain
- Petitjean Number
- Rotatable Bonds Count
- Topological Polar Surface Area
- Vertex adjacency information magnitude
- Molecular Weight
- Zagreb Index
No "heavy atom count." Next option is to see if there's a way to specify the counts based on a SMARTS pattern. Nope, didn't find anything.
As far as I can tell, there's no way with the default nodes to do much of anything with KNIME. I assume there are additional packages which I can install, but why aren't there more useful CDK nodes as part of the standard installation? An obvious one to me would be a SMARTS count pattern matcher, where I could specify the SMARTS pattern, the option for unique or non-unique matche counts, and the output column name.
Is my problem because I'm on a Mac? Do Linux users get more nodes? Or is there something else I'm missing? How would you find the number of heavy atoms using KNIME? Is there a solution using the default CDK nodes or do I have to use one of the commercial toolkits?
Leave answers and comments here.
Andrew Dalke is an independent consultant focusing on software development for computational chemistry and biology. Need contract programming, help, or training? Contact me
| http://dalkescientific.com/writings/diary/archive/2010/03/16/knime_and_beginners.html | CC-MAIN-2017-26 | refinedweb | 1,199 | 63.29 |
SPARK-2764 (and some followup commits) simplified PySpark's worker process structure by removing an intermediate pool of processes forked by daemon.py. Previously, daemon.py forked a fixed-size pool of processes that shared a socket and handled worker launch requests from Java. After my patch, this intermediate pool was removed and launch requests are handled directly in daemon.py.
Unfortunately, this seems to have increased PySpark task launch latency when running on m3* class instances in EC2. Most of this difference can be attributed to m3 instances' more expensive fork() system calls. I tried the following microbenchmark on m3.xlarge and r3.xlarge instances:
import os for x in range(1000): if os.fork() == 0: exit()
On the r3.xlarge instance:
real 0m0.761s user 0m0.008s sys 0m0.144s
And on m3.xlarge:
real 0m1.699s user 0m0.012s sys 0m1.008s
I think this is due to HVM vs PVM EC2 instances using different virtualization technologies with different fork costs.
It may be the case that this performance difference only appears in certain microbenchmarks and is masked by other performance improvements in PySpark, such as improvements to large group-bys. I'm in the process of re-running spark-perf benchmarks on m3 instances in order to confirm whether this impacts more realistic jobs.
- relates to
SPARK-3333 Large number of partitions causes OOM
- Resolved
- links to
- | https://issues.apache.org/jira/browse/SPARK-3358 | CC-MAIN-2019-43 | refinedweb | 231 | 60.92 |
How I can estimate the number of recursive calls that would be used by the code
to compute binomial(100, 50)?to compute binomial(100, 50)?Code:public static double binomial(int N, int k, double p) { if ((N == 0) || (k < 0)) return 1.0; return (1.0 - p)*binomial(N-1, k) + p*binomial(N-1, k-1); }
I am looking for the formula that gives me the exact number of calls
dont wanna to do it with a counter because the number is very very big and it takes time to calculate
I'm sure there is a formula | http://forums.devshed.com/software-design-43/calculate-recursive-calls-935362.html | CC-MAIN-2015-32 | refinedweb | 101 | 62.68 |
>>Why do you create this "Stuff" sub namespace? What is that called anyway? and why?
>>So what are the benefits of compiling into a namespace?
In my opinion, in practice, namespaces are just housekeeping.
How do you want to group and organize your code?
Usage of namespaces (again, just in my experience) is going to be defined either by company standards or the developer.
>>Why would you add to an existing System namespace?
Again, just housekeeping.
If you write some code that manipulates text, do you want it in your own namespace and class and use it with something like "MyNamespace.MyTextFunctio
or do you feel it's good enough to be part of System.Text?
and then call it with "System.Text.MyTextFunctio | https://www.experts-exchange.com/questions/22960414/Namespace-concept.html | CC-MAIN-2016-50 | refinedweb | 124 | 68.97 |
Since Visual Studio .NET was first released, it has been possible to document your classes directly in code and define the standard documentation sections (such as the summary, remarks, parameter descriptions, etc) which contain the standard tags (such as the member reference, two-column table, list etc). But for us, developers, it was quite inconvenient to fully document our classes and create such long sections as remarks directly in code. The same is true in the case when the documentation is created by a technical writer and the code is created by a developer; it is not quite appropriate for them to work with a single document. The utility we created, DocMounter, is a way to separate the code from the documentation without loss of those conveniences provided by Visual Studio.
DocMounter allows you to easily create MS Visual Studio XML documentation files for your products. These files can be used with your products in Visual Studio (for IntelliSense and in the Object Browser), and you can also use them to get the modern help for your products in one click using such automated help building tools as NDoc and SandCastle.
DocMounter was initially created for our internal needs, namely to create full-featured documentation for one of our components. Step by step the tool improved, and finally it has become an easy-to-use application that can be useful for other developers.
DocMounter allows you to perform the following tasks:
Enter all the standard sections such as summary, remarks, example, see also, etc for classes and their members through a visual interface.
Add tags such as see, code, list, table etc through a visual interface.
Create additional topics using the same syntax as for the classes and their members (XML documentation syntax).
Generate XML documentation files that you can later use to compile a complete documentation with NDoc, SandCastle, or other utility.
Generate HTML files for additional topics (topics not related to a particular class or its members).
Generate a single HTML file from all the additional topics. Later this file may be slightly edited, converted into a DOC, RTF, or PDF format, and used as a manual.
Integrate NDoc, SandCastle, or other utilities to create a compiled HxS help file from XML documentation and additional HTML topics:
Let's build our first help solution with DocMounter.
After starting the application, you will see a start-up dialog like this:
Click the New button in this dialog and then select the library you want to document; a new project will be created.
After the project has been created, you can see the specified assembly's public members in the member tree on the left side of the main form, for instance:
Sequentially select each member of the assembly and enter its descriptions into the sections at the right side of the member tree. Every type of member has its own set of sections, and you can switch among them with the tabs at the top:
You can also use special tags in descriptions. To insert a tag, set the caret to the place you want to insert the tag, click the toolbar button, and specify the tag in the dialog that will appear:
For example if you want to insert a reference to a member, select the See item on the left, select the member to reference to in the tree on the right, and click the OK button.
After you have entered all the necessary descriptions, you can build one of the help types. To build a complete help solution, push the toolbar button. When building is completed, click the toolbar button to view the result.
The output folders are specified in the project properties (the Properties item of the Project main menu item); by default the results are saved to the '10Tec DocMounter Output' folder of the 'My Documents' folder.
After creating a new project, you should specify its properties (such as output paths, title, etc). You can do it with the Properties item of the Project menu. Choose this item, and you will see the dialog which allows you to specify all the project properties:
data-src="/KB/dotnet/docmounterhelp/ProjectProperties.png" class="lazyload" data-sizes="auto" data->
DocSet List [makes sense for building help solution and additional topics only]. In MSHelp 2 every topic can have one or more DocSet attributes. DocSet is an attribute which is used by MSHelp 2 for filtering and searching topics. Here is what Microsoft writes about the DocSet attribute:
If you want to enter a few DocSet attributes, separate them with commas. All the entered DocSet attributes will be added to every topic when building help solution or additional topics.
Help Namespace [valid for building help solution and additional topics only]. Allows you to specify the help namespace that your help will be registered in. The help namespace is used by an MSHelp 2 Document Explorer to navigate topics. For example let's look at the address of a topic from .NET Framework documentation:
The first part of the address, ms-help, tells the explorer that it should use the ms-help protocol to navigate the file; the second part, MS.NETDEVFX.v20.en, is the namespace where the topic is registered.
When you register your help collection, it is registered with the namespace entered into this field. The namespace consists of several parts. Its first part is the name of your company, the second part is the name of the product the documentation describes, the next part is the version of product, and the last one is the locale code.
How is this namespace used by DocMounter? First of all, when you build the help solution, the resulting HxS (compiled help file) is registered with this namespace to enable its viewing in an MSHelp 2 Document Explorer. Also, the help namespace is used when creating reference links to local members when building additional topics.
System Help Namespace [valid for building help solution and additional topics only]. This is the namespace to use when referencing system members. When a topic is built, all the references to system members are replaced with MSHelp 2 links. These links consist of the help namespace and the a-index of the member. For example, the link <see cref="T:System.Object"> will be replaced with <MSHelp:linkSystem.Object</MSHelp:link>, where "MS.NETDEVFX.v20.en" is the namespace specified in this field. It means that the link points to the topic with the frlrfSystemObjectClassTopic a-index within the Microsoft .NET Framework v2.0 help collection.
<see cref="T:System.Object">
<MSHelp:linkSystem.Object</MSHelp:link>
Output. Allows you to specify the output folders for all the types of build. If the XML with Summaries field is empty, the XML document with summary descriptions only is saved to the folders where the assemblies are located.. After you have selected read more about the tags supported by Microsoft in the following article:
Recommended Tags for Documentation Comments (C# Programming Guide)
In member descriptions, you can use the following Microsoft-supported tags: <see>, <code>, <paramref>, and <list>. (Note: you should not use the <para> tag, as DocMounter will automatically add these tags in place of line breaks.) You can either enter these tags manually or use an automated method provided by the DocMounter visual interface. If you want to insert a tag, move the caret to the place where you want to insert the tag and press the Ctrl+T key combination (or push the Insert tag toolbar button, or choose the Insert Tag item of the Insert main menu item). The Insert Tag form will appear:
<see>
<code>
<paramref>
<list>
<para>
On the left side of the form you can see the complete list of tags which are supported by DocMounter. Some of these tags are not supported by Microsoft XML documentation language and are not available to be entered for member description (multi-column table for example). When you select a tag from this list, fields reflecting the tag's parameters appear on the right side of the form. Fill in these fields and then press the OK button. The tag will be inserted into the description.
For example the description text 'This is a reference to the <see cref="T:System.Object" /> member.', which contains a tag, will be compiled into the following text in the output topic:
'This is a reference to the <see cref="T:System.Object" /> member.'
data-
If you want angle brackets to appear in the text of a documentation, use '<' and '>'. For example '<text in angle brackets>' will be compiled to:
'<'
'>'
'<text in angle brackets>'
data-
In addition to member descriptions, DocMounter allows you to create additional topics that are not related to a specific member. The contents of these topics are not included in the complete XML and XML with summaries, but you can create separate HTML documents for these topics, and these topics are also included in the help solution (the compiled HxS file which is built via an add-in).
To create an additional topic, press the Add button, which is located under the topic tree in the main form of DocMounter. Next to the Add button you'll find the Remove button, which allows you to remove the selected topic. Also you can add, remove, or rename a topic with the context menu that appears when you right-click a topic in the member tree. After creating an additional topic, you can edit it as a usual member, enter plain text, and insert tags.
DocMounter allows you to build XML help documents of two types: XML with summaries and complete XML. The first one stores only the summary sections of the help and is smaller than the latter one. What is it intended to be used for? This XML document is intended to be distributed along with the .NET assemblies that you are documenting, and will be used by Visual Studio IntelliSense. When you are typing code in Visual Studio Code Editor, IntelliSense shows you short descriptions for types and their members. It takes these descriptions from the XML documents that are located in the same folders where your assemblies lie. All the other sections of the XML documentation, if they are present, are not used by IntelliSense, and therefore are not needed in this type of XML document.
The second type of XML documentation, the complete XML, is intended to be used by other utilities such as NDoc and SandCastle to generate complete help files such as HxS (MSHelp 2 compiled help format), CHM etc. This XML documentation contains all the sections of the help (summaries, remarks, exceptions etc).
To build the XML help with summaries, choose the XML Summaries item of the Build main menu item, push the Build XML Summary File toolbar button, or press the Ctrl+Shift+S key combination.
To build the complete XML documentation, choose the Complete XML item of the Build main menu item, push the Build Complete XML Description File toolbar button, or press the Ctrl+Shift+C key combination.
Since the XML documentation does not support topics that are not directly related to a member, DocMounter allows you to build separate HTML files for additional topics. These HTML files can be later manually included into a help project.
To build the additional topics, choose the Additional Topics item of the Build main menu item, push the Build Additional Topics toolbar button, or press the Ctrl+Shift+T key combination.
DocMounter itself does not allow you to build HxS (MSHelp 2 compiled help format), CHM, and other help files. It only allows you to build XML documentation, which can be later transformed into these formats with such free utilities as NDoc and SandCastle. But it is possible to integrate one of these utilities as an add-in into DocMounter to give you the ability to build help files automatically. If an add-in (a file with the name TenTec.Utils.HelpBuilder.dll) is located in the same folder with DocMounter, you can build a complete help solution in a single step.
At present DocMounter is distributed with only one add-in based on a modified version of NDoc, which was recompiled for the .NET Framework 2.0. This add-in allows you to build MSHelp2 (HxS) files and view them. It requires the Microsoft Help 2 SDK to be installed on your computer. The SDK is a part of the Visual Studio SDK and can be downloaded from the following locations depending on your version of Visual Studio:
For VS 2003: Visual Studio 2003 Help Integration Kit
For VS 2005: Visual Studio 2005 SDK
To create the compiled HxS file, choose the Help Solution item of the Build main menu item, push the Build Help Solution toolbar button, or press the Ctrl+Shift+H key combination.
With DocMounter you can not only build separate HTML topics, but you can also create an HTML document that contains all the additional topics. This document is not a complete manual - it is a draft which allows you to create a complete manual. You can change the style of the document, add a table of contents, convert it into another format such as DOC, RTF, PDF etc. For instance, to get a ready-to-print manual, you can open this HTML file in MS Word, add your title and table of contents, and save as a Word document – that's all.
To create the manual, choose the Manual item of the Build main menu item, push the Build Manual toolbar button, or press the Ctrl+Shift+M key combination.
DocMounter itself does not allow you to build HxS (MSHelp 2 compiled help format), CHM etc help files. It only allows you to build XML documentation, which can be later transformed into these formats with such free utilities as NDoc and SandCastle. But it is possible to integrate one of the utilities as an add-in. The current version of DocMounter allows you to plug only one add-in at a time (it is enough in 99% of cases because if you build help files for your products, you generally use just one such utility).
An add-in for DocMounter is just a class library with the name TenTec.Utils.HelpBuilder.dll which is located in the same folder with the DocMounter. This library should contain a class that implements the IHelpBuilder and IAdditionalTopicHelper interfaces. These two interfaces are described in the TenTec.Utils.IHelpBuilder.dll library, which you can find in the folder where DocMounter is installed.
Currently an add-in based on NDoc is included in DocMounter.
This article contains only the main parts of the DocMounter manual. The full description of DocMounter can be found in the manual and help included in the installation.
21 Feb 2007. v1.10, build 0000. Article posted.
20 March 2007. v1.10, build 0001.
This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)
private static void WriteParams(XmlTextWriter writer, ParameterInfo[] parameters, MemberInfo declareMember, DataXmlHelpManager data, ref bool memberStarted, bool isDelegate)
{
//check input params
if(declareMember == null)
throw new ArgumentNullException();
if (declareMember.MemberType != System.Reflection.MemberTypes.NestedType)
{
if (
declareMember.MemberType != System.Reflection.MemberTypes.TypeInfo &&
declareMember.MemberType != System.Reflection.MemberTypes.Property &&
declareMember.MemberType != System.Reflection.MemberTypes.Method &&
declareMember.MemberType != System.Reflection.MemberTypes.Constructor)
throw new ArgumentException();
foreach (ParameterInfo myParameter in parameters)
{
//write start method if needed
if (!memberStarted)
{
if (isDelegate)
WriteStartType(writer, declareMember as Type);
else if (declareMember.MemberType == System.Reflection.MemberTypes.Property)
WriteStartProp(writer, declareMember as PropertyInfo);
else if (declareMember.MemberType == System.Reflection.MemberTypes.Constructor)
WriteStartConstructor(writer, declareMember as ConstructorInfo);
else if (declareMember.MemberType == System.Reflection.MemberTypes.Method)
WriteStartMethod(writer, declareMember as MethodInfo);
memberStarted = true;
}
writer.WriteStartElement(ConstsXmlHelpManager.cParameter);
writer.WriteAttributeString(ConstsXmlHelpManager.cName, myParameter.Name);
//get param help string
DataXmlHelpParam myHelpData = new DataXmlHelpParam(myParameter, declareMember);
if (data.GetParamHelpDelegate != null)
data.GetParamHelpDelegate(myHelpData);
if (myHelpData.Summary != null && myHelpData.Summary.Length > 0)
WriteText(writer, myHelpData.Summary);
writer.WriteEndElement();
}
}
}
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/17709/DocMounter-Help-File-Builder | CC-MAIN-2019-39 | refinedweb | 2,693 | 52.09 |
Source Generators are almost certainly the most talked about feature in the C# compiler. It’s understandable: the ability to create new code right in the compilation process and use it immediately is exciting and could be useful in lots of different situations.
What can ReSharper do here? Well, it can do what it does best and take the generated files into account while performing refactorings, provide code editor features, and help you navigate to the generated code.
Partial methods are now allowed to have out parameters, non-void return types, and any type of accessibility, making them more useful with Source Generators. Source Generators can use the defining declaration of the partial method to customize the behavior of the generated code.
Another cool addition is init-only properties. Such properties can only be set during the initialization of an object. So finally you can use object initializers without exposing the property as mutable!
ReSharper is aware of init-only properties and takes them into account when completing your code, performing generative completion, analyzing whether the property changed anywhere, and offering a quick-fix to make it mutable if you change your mind.
The perfect place to apply init is new record types. These are reference types with value semantics that help you achieve immutability, but this time for the whole object. Again, ReSharper is keeping up with the language, from quick-fixes for choosing your preferred declaration style to basic completion.
Positional records have a compiler-generated
Deconstruct() method.
ReSharper supports all deconstruction features in such objects. Notice the popup when
introducing a variable: it offers you the choice between single variable or a
deconstructing declaration. The same choice will be offered when a function accesses a
property of a record object.
Moving on from the big things, local functions are now permitted to have attributes (as well as parameters and type parameters in local functions). This is supported by ReSharper’s quick-fixes, including the neat feature of annotating the method as [NotNull] or [CanBeNull] by pressing ! or ?, respectively.
Another useful C# 9 addition is the ability to write top-level programs. No more fighting with Program classes: you can place your entry point code right after the using directives! There is some help available for working with top-level statements as well. There are two rules about top-level statements: they should precede any type or namespace, and only a single file in the project can contain top-level code. Both rules are easy to break when you’re rearranging and copy-pasting code. ReSharper provides quick-fixes to remedy this by moving your top-level code to the top or to another file.
Given that top-level code is also code, there are refactorings for it as well: Extract local variable and Extract method refactorings.
With target-typed new expressions in C# 9 we can omit the type after the new keyword
when it can be inferred from the usage context. ReSharper provides full support for the
feature including the ability to Find Usages of the constructor and configure preferred
syntax style. The latter allows you to use
new() syntax when a created type
is evident while enforcing an explicit type specification in other cases.
By the way, ReSharper’s new (pun intended) type name hints can help if all the
new() in your code gets out of control.
With return type covariance, you’re no longer bound to returning the same type in overriding members as you do in the base class method. There is no longer any need to implement workarounds to return a more specific type.
Pattern matching continues to evolve in the new language version. Matching expressions
now allow using relational (
<,
>, etc.) and logical
(
not,
or,
and) patterns, cutting out a lot of the
verbosity of the old
switch constructs. ReSharper can assist you with
analyzing the patterns and rewriting them in the desired style.
Finally, when lambda discard parameters were introduced, we felt it would be nice to add a quick-fix for them.
That’s about it for the major language highlights. There are smaller improvements added to the language that are supported in ReSharper 2020.3 as well. This includes target-typed conditional expressions, static lambdas, extension GetEnumerator methods in foreach, function pointer types, and native integer types.
We believe in the power of inlay hints, but we also know that the environment should be kept as clean and uncluttered as possible. We’ve come up with a new "Push-to-Hint" mechanism for inlay hints to keep the best of both worlds.
In Push-to-Hint visibility mode, hints aren't shown by default. They're shown if you press and hold Ctrl (and hidden as soon as you release it) or press Ctrl twice (in which case they remain visible until you press Ctrl twice again).
We’ve provided quite granular settings: you can tell ReSharper which hints should always be enabled, which should be shown on push, and which you don’t really care for. Use the ‘Visibility’ setting for each hint type.
Another thing we’ve worked on are the hints for implicit type casts. Such casts can result in data loss or performance degradation, and ReSharper can now indicate where an implicit cast is happening.
When you Ctrl+Click on a type conversion hint it will take you to the implementation of the implicit conversion.
Inlay hints for XAML, which were already available in the previous version, now also have the usual context menu that allows you to configure how they look.
We continue to add more granular settings to the formatting engine. This is what we’ve added in this release.
A group of settings for arranging property patterns: you can tell ReSharper to place a simple pattern on a single line, and also how you prefer long patterns to be wrapped. There’s also a setting to align the property patterns in columns.
Blank lines can now be added around property or event accessors.
For Visual Basic, there’s the option to add a space after the unary +/- operator.
There are some updates for the .editorconfig support as well. ReSharper now supports the
Roslyn properties:
file_header_templates,
dotnet_sort_system_directives_first, and
dotnet_separate_import_directive_groups.
There’s also a new “Spaces around ‘=’” parameter in export to .editorconfig. It is detected automatically in existing files and can be set manually for new files. It is set to ‘true’ by default.
We’ve added Dynamic Program Analysis (DPA) to ReSharper to help you analyze and create better code by detecting closures and allocations to large and small object heaps in the memory.
The best part is that you don’t have to do anything except your usual routine of coding, running and debugging. DPA goes on in the background and is ready with a report after each launch of your project. Just keep an eye out for the icon in the bottom-right corner.
You may already be familiar with the structural navigation feature: it allows you to select pieces of code according to their structure, a keyword, a block, a method, and so on.
When you’re using the Extend or Shrink Selection actions, they require another step to select a comma, a dot, or a bracket, which is easy to miss. If you were deleting a block, this would result in a code error. ReSharper will do a little cleaning up in this case: if something was selected structurally, ReSharper will try to delete it structurally when you press Backspace or Delete.
If you’re working on a large code base, every solution-wide operation takes a long time
to run. Have you ever found yourself waiting for the whole solution to be reformatted
after you’ve changed a couple of files? Well, now you can run the CleanupCode console
tool without pointing to the solution file: just specify a set of files or folders. The
command line will look like this:
cleanupcode.exe [Path to folder] [Path to file] [Path to another file]
Please note that the tool only formats the code – cleanup isn't available in this mode.
One more thing that was missing from our console tools for some time was support for
plugins. Well, it’s back! For now it’s only available on Windows. To make use of it,
you’ll need to know the ID of the plugin. Go to the
JetBrains Marketplace, open the plugin page, go
to the Versions tab, click on any version and it will show you the plugin ID. After
that, use the
-x=[ID] key with the plugin ID when launching InspectCode or CleanupCode
and the console tool will automatically download and enable the plugin:
cleanupcode.exe -x=[ID] [Path to solution file].
Please note that the plugin has to be compatible with the tool version. Also, plugins are not yet supported if you’re using the .NET Core global tools mechanism to install ReSharper’s command line tools.
Have you ever struggled when searching for text? Maybe for a string in your code, or a comment? Or did a typo in your text prevent you from actually finding anything?
Find Text now performs fuzzy search in addition to exact search, taking possible typos and missing words into account. The results are displayed below the results of the regular substring search, in the Fuzzy section. Hint: it can be very helpful if you are looking for a certain formatted string build in your code.
As is typical for all the WPF-like frameworks, code analysis provides plenty of
common code inspections with appropriate quick-fixes for both C# code-behind and
.axaml files including “Possible ‘System.NullReferenceException’”
and “Class/Property {...} is obsolete: Use {...}”.
In addition to the common WPF inspections, there are a lot of Avalonia-specific
inspections, such as “Path to resource is case-sensitive” or
“ColumnDefinitions tag can be converted to attribute” inspections with
quick-fixes. For the latter, there is a context action on
ColumnDefinitions="*,Auto,*" attribute to convert it back into a
<Grid.ColumnDefinitions> tag.
We’ve added proper support for
“$self",
“$parent”,
“^”, and
“#” syntax in Avalonia bindings, as well as proper validation of indexes in the
$parent[] array.
There is extended support for
CompiledBinding and the
x:CompileBindings extension. ReSharper knows that
DataType is
required here and prompts you to specify it for bindings in your code.
The “Create from usage” quick-fix is available for all sorts of Avalonia properties.
Avalonia XAML support includes understanding of the CSS-like styling system.
Inlay Hints help you better understand the code you are looking at.
Code completion and parameter info are available for all XAML keywords, all sorts of
markup extensions,
x:Name,
Style properties,
Source
properties for
StyleInclude, and lots more.
You can easily navigate to compiled binding data type, bound property, Avalonia control
type, and
x:Name declarations. ReSharper can also go directly from XAML to
decompiled external code including style setter properties and to referenced
xmlns namespaces.
Find Usages helps you find all usages of method bindings,
x:Name
attributes,
Style classes and setters, and all sorts of properties.
Rename and Safe Delete refactorings are now aware of all kinds of usages in Avalonia XAML code and update them accordingly.
You can observe the hierarchy and structure of the Avalonia XAML code.
ReSharper’s integrated decompiler has also received updates to support more C# features. We’ve also improved the synchronization mechanism between IL Viewer and source code.
Specifically for top-level statements, we’ve added a <Top-level Entry Point> node in Assembly Explorer. You can double-click or use the context menu navigation on this node to get to actual top level statements in decompiled code.
Private Source Link is now supported. After you navigate to the external sources that require a connection to a private source server, ReSharper will show a notification and let you enter your credentials; unless, of course, you’ve already specified them in Visual Studio’s settings, in which case they will be applied automatically (for GitHub and BitBucket).
We continue to add more Blazor support. This iteration was about supporting generic type parameters and their type inference from usages, and eliminating performance setbacks on opening solutions. For the full list of fixed issues, please refer to our public bug tracker.
ReSharper C++ 2020.3 provides seamless integration with UnrealHeaderTool to help you catch issues that are usually discovered only at compile time. ReSharper C++ runs UnrealHeaderTool in the background and displays the analysis results in real time right in the editor.
To improve its HLSL support, ReSharper C++ brings control-flow analysis inspections to shader files. Live tracking of changes to build configuration files lets ReSharper always use the most up-to-date project model.
ReSharper C++ 2020.3 implements the C++20 changes to comparison rules. With rich inspections and error messages, you can rely on ReSharper C++ when you need to understand exactly how your code behaves, while the new quick-fixes help you work with comparison operators easily.
In addition, ReSharper C++ 2020.3 brings new inspections to help you adopt the C++20 ranges library, and adds support for the standard mode of C++20 coroutines introduced in Visual Studio 16.8.
dotMemory uses the timeline data to provide automatic inspections right on the Timeline graph.
Currently, there are three inspections available:
Now, you can refine what projects should be built when a continuous testing session is triggered. This lets you speed up continuous testing sessions. The feature works in both Visual Studio and Rider. | https://www.jetbrains.com/resharper/whatsnew/2020-3/ | CC-MAIN-2021-31 | refinedweb | 2,258 | 54.93 |
#include "RTOp_parallel_helpers.h"
Go to the source code of this file.
Definition at line 47 of file RTOp_parallel_helpers.c.
Definition at line 48 of file RTOp_parallel_helpers.c.
This function helps to implement vector method
apply_op(...) for any type of parallel vector.
Preconditions:] There is no overlap of 'g' with 'u'
overlap_first_local_ele_off != 0]
0 <= overlap_local_sub_dim <= local_sub_dim - overlap_first_local_ele_off
To understand what this function computes first consider the what an
apply_op(...) method might look like from a vector class. This method would take a list of non-mutable vectors:
v_1, v_2, ..., v_p
and a list of mutable vectors
z_1, z_2, ..., z_q
and then apply the reduction/transformation operator
op over some subset of the elements in these vectors according to their placement as a set of sub-vectors in some other logical vector.
Let's consider how things are treated for a single vector argument
v_i or
z_i which we will call 'v'. This global vector 'v' is the first vector that we identity. One must understand that there are five distict vectors (or sub-vectors) being refered to here. The first vector (call it 'v') and is one of the parallel vectors that
apply_op() is called on that we have already discussed. The second vector (call it 'g') is the logical sub-vector that the client wants to represent using the elements in 'v'. This logical sub-vector is specified by the input arguments
first_ele_off,
sub_dim and
global_off. If for the time being we ignore
global_off, and then 'g' is defined in terms of 'v' as:
g(k) = v(first_ele_off+k), for k = 0...sub_dim-1. | http://trilinos.sandia.gov/packages/docs/r11.0/packages/rtop/browser/doc/html/RTOp__parallel__helpers_8c.html | CC-MAIN-2013-48 | refinedweb | 264 | 65.93 |
0
Here is code for hexagonal and pentagonal numbers. I need type that stores something bigger than 10 billion. Double works fine to about 8.4 billion. Of course I tried using long long and unsigned long long but it's still not working. Please repair this code because it overflows now matter what I do or explain how to use GMP library. I'm using CodeBlocks 10.5. Best regards.
#include <stdio.h> #include <math.h> double Pentagonal(int n){ double P = 0; P = (3*n*n - n) / 2; P = -P; return P; } double Equation(){ double x1,x2,remainder = 0; //where the cycle starts int n = 166; //variable for the remainder int x = 0; //quadratic equation quotients int a = 2; int b = -1; double c = 0; for(n; n<33000; n++) {c = Pentagonal(n); double expression = b*b - 4*a*c; printf("\n%.0lf",expression); double root = sqrt(expression); x1 = (-b + root)/(2*a); x = (-b + root)/(2*a); remainder = fmod(x1,x); x2 = (-b - root)/(2*a); if(remainder == 0) {printf("%.4lf",x1); printf("\nNumber is %.0lf\n",-c); break;} } return 0; } int main(){ Equation(); return 0; } | https://www.daniweb.com/programming/software-development/threads/352796/number-bigger-than-10-billion | CC-MAIN-2015-40 | refinedweb | 189 | 65.73 |
)
Prasad H(4)
Pramod Singh(3)
Prasad (3)
Rajadurai P(3)
Filip Bulovic(3)
Mike Gold(3)
sayginteh (2)
manish Mehta(2)
Chris Rausch(2)
Shivani (2)
G Gnana Arun Ganesh(2)
Narayana Surapaneni(2)
Paul Lockwood(2)
Sushila S. Bowalekar(2)
Dipal Choksi(2)
Hrishikesh Dhruv(1)
Saurabh Nandu(1)
Praveen Moosad(1)
Gopinath (1)
Hari Shankar(1)
Ian Stallings(1)
Chandrakant Parmar(1)
Nakul Goyal(1)
Ravi Shankar(1)
shrijeet (1)
John O Donnell(1)
Anders Carlsen(1)
Levent Camlibel(1)
Tran Khanh Hien(1)
John Schofield(1)
Srinivasa Sivkumar(1)
Christian Hanssom(1)
Dottys (1)
Daniel Stefanescu(1)
Sankar Ramanathan(1)
Bill Farley(1)
S Thangaraju(1)
Srinivas Kandru(1)
Rajesh VS(1)
Luke Venediger(1)
David Talbot(1)
Jie Su & Ying Qiang(1)
Zhanbo Sun(1)
Anand Narayanswamy(1)
John Hudai Godel(1)
Jigar Desai(1)
Amit Ware(1)
Kamran (1)
Andrew McCarter(1)
TimothyA Vanover(1)
Joel Matthies(1)
nildo (1)
Shantanu Bhattacharya(1)
TH Mok(1)
kamalpatel125 (1)
Doug Bell(1)
Lee SangEun(1)
Daniel Olson(1)
Avinash Pundit(1)
Simon Harris(1)
Michael Momcouglu(1)
john donell(1)
Ivan Zderadicka(1)
Michael Evans(1)
Illawesome (1)
Vivek Sharma(1)
Michael Rednikin(1)
Chandrasekaran Sakkarai(1)
vivekchauhan (1)
Chandra Hundigam(1)
Patrick Wright(1)
Resources
No resource found.
C# Editors
Oct 06, 2000.
You can write your C# code with various editors including your favorite text editor Notepad. See more editors here.
A Simple Calculator Class
Nov 28, 2000.
Code sample shows how to create a simple calculator class and call it from Main C# program..
Calling a COM Component From C# (Late Binding)
Jan 08, 2001.
This code sample shows how to call a COM component in .NET framework using C#.
Developing 3-Tier Applications in C# and .NET
Feb 04, 2001.
The attached sample code explains for beginners, how to Code for a 3-Tier Architecture.
Synchronization in Multi-threading
Feb 13, 2001.
This article with sample code shows synchronization concepts of multithreading ..
Adding Items to a ListBox
Mar 06, 2001.
Sample code shows you how to add items to a list box.
Testing .Net Components Using NUnit
Mar 08, 2001.
Write unit tests before starting development". Writing test allows me to see immediate results of every code change.
Serialization Sample Code
Mar 13, 2001.
A class on serial.
Naming Guidelines in .NET
Apr 20, 2001.
Commenting and following a uniform naming guidelines in your code is one of good programming practices to make code more useful..
Connect to an Oracle Database
May 03, 2001.
This sample code shows you how to connect to an Oracle database using C#.
Operator Overloading Example
May 14, 2001.
The code uses the feature of Operator Overloading in C#. It shows how different operators are overloaded and can be used in a easy manner..
Data Structure Sample Example
Jun 04, 2001.
Source code for Data Structure implemetation of Stack, Queue, Doubly linked list and more..
.NET Brings The Fun Back to Programming
Jul 11, 2001.
Today, we are all comfortable sitting in front of our high powered computers running graphical user interfaces and compiling code in sophisticated development environments.
XML as Middle Tier
Jul 12, 2001.
There is always been a need that there will be an intelligent middle Layer between Database Server and the UI Code. There are many ways but one fantastic approach came in picture with the XML.
Scaling an Image
Jul 13, 2001.
This code will show You on way to scale an image with .Net Beta 2.
Using/Debug Option During Compilation
Jul 15, 2001.
This source code below is an an example of how to use /debug option during compilation.
Compute Feature of DataTable
Aug 01, 2001.
The following code is for implementing least known feature of DataTable Compute() method.
Message Box Builder
Aug 14, 2001.
This program will help you using MessageBox Class. Program generates code from what you choose.# or VB.NET - World War III
Aug 23, 2001.
In this article I'm going to go under the hood and show you what really happens to the in C# and VB.NET.
WhoIs Sample Code
Aug 27, 2001.
Sample example shows you how to implement WhoIs....
Socket Programming in C#
Sep 03, 2001.
This program is useful for a starter who wants to write C# code using .Net Sockets..
Web Control Bulider
Sep 03, 2001.
The attached C# program can be used by users who dont have VS.NET IDE to generate the code for WebControls.
Regular Expressions Usage in C#
Sep 07, 2001.
The source code shows how to use Regular Expressions in C#.
A variety of Chart Engines
Sep 07, 2001.
The original code came from Scott Guthrie’s chart engine example. The differences from original code.
Operator Overloading in C#
Sep 10, 2001.
The Source code below shows how to use Operator Overloading in C#. Operator Overloading is pretty useful concept derived from C++ by C#.
Mouse and Key Events
Sep 11, 2001.
This article explains the usage of key and mouse events. The following code shows you how you can read mouse position on mouse move.
Doppler Radar
Sep 14, 2001.
This is an app that will display the current doppler radar picture for any given zip code..
Constructor, Destructor and ILASM
Sep 20, 2001.
I find C# a very interesting language and it also comes handy to analyze ILASM code.
Accessing Oracle Database
Sep 21, 2001.
This source code shows you how to connect to an oracle database and do operations such as select, insert, update and delete.#...
Debug Troelsen's .NET books (1): IEnumerator
Dec 10, 2001.
This article examines code problem in chapter 4 (for C#)/chapter 5(for VB.Net) of the two .Net books..
How Can You Migrate your Existing Applications?
Dec 20, 2001.
When a new technology emerges, companies and developers begin to wait anxiously for answers to their questions.++.
Basic FTP in C#
Jan 10, 2002.
FTP client developed using Windows Forms. The source code uses a rigid Model-View-Controller design pattern...
Sending Windows Message in C#
Mar 14, 2002.
This sample code shows how to send Window messages between two forms using.
Simple NSLookUp Implementation in C#
Apr 01, 2002.
This is code implementation for simple nslookup. As you can see from the code listing, I've used classes defined in the System.Net namespace.
Multicasting using UDP in C#
Apr 04, 2002.
The attached source code shows you how to use multi casting in a LAN environment..
Drawing B-Spline Curves
Apr 22, 2002.
The attached source code project draws spline curves between two points.
.NET Security in C#
Apr 22, 2002.
This article shows how to make file I/O access be denied if the user running the application did not have administrator privileges.
Application Data Utility Class
Apr 24, 2002.
Attached is a ZIP file containing the source-code and compiled DLL of the "Application Data Utility Class".
MP3 JukeBox
Apr 30, 2002.
This is stable code and more generic than the first release. It has better error handling now to make it more 'idiot proof'.
Interrogating Your Printer Queues with WMI
May 20, 2002.
In response to a newsgroup query here is the code needed to view the printer queues on your system.
CS CODEDOM Parser
Jun 12, 2002.
CS CODEDOM Parser is utility which parses the C# source code and creates the CODEDOM tree of the code(general classes that represent code, part of .NET Framework - namespace System.CodeDom).. MSIL Code to Close Application Programmatically
Jul 18, 2002.
You can use MSIL code to call Win32 APIs and one of the simplest example of it is by closing an application programmatically.
Web Forms Code Model
Jul 23, 2002.
ASP.NET introduces a new programming model for Web Forms to separate the code and visual elements in different files..
Understanding Generic Type in C#
Aug 15, 2002.
Before we start tampering around the code, lets understand why we need a generic type?
RSS Feed Project in .NET
Aug 19, 2002.
The RSS Feed project is aimed as demonstrating writing C# code to consume RSS feeds from the internet and putting the data from these RSS feeds into a database for you to use in your own applications.
About code-coverage. | http://www.c-sharpcorner.com/tags/code-coverage | CC-MAIN-2016-30 | refinedweb | 1,379 | 68.16 |
Usually, Typeerror module object is not callable error occurs when python calls any module in the place of Class constructor or function. This article will help you to fix this issue. So let’s go.
Typeerror module object is not callable (Cause):
In order to explain the root cause of this bug. Let’s take am an example. Now, let’s import any python module NumPy.
import numpy obj=numpy()
As the above image shows. Numpy is a python module, not a python class. Hence We can not create an instance of it. That’s why the python interpreter throws the above error.
Typeerror module object is not callable (Solution):
The Golden rule to fix this error is to call the respective python class or function in the place of the python module. This concept is the same for library python modules like NumPy, pandas, etc and custom develop python module.
1. module object is not callable ( Library Modules)-
Let’s import the standard time module. Here time module contains time() function.
import time obj=time() print(obj)
But in the above code, it directly calls the module. Which is not the right way. That’s why it through the same error.
The correct way is below.
Another way to fix this below. Below we have imported the respective function time() from the complete module. Earlier we were importing the complete module. Which provides the double reference of the same name to the python interpreter. That why it throughs the same error.
from time import time obj=time() print(obj)
2. module object is not callable ( Custom Module)-
In addition, Suppose we create a python module with the name my_utillity.py which has a function my_utillity(). Here if we import the complete package the call the my_utillity() directly. It will show the same error. The best way to fix the module object is not callable is already mentioned above. It will remain unchanged.
Here is my_utillity.py which contains the my_utillity() function.
def my_utility(): return "My utility invoked"
The correct way to call it.
from my_utility import my_utility print(my_utility())
OR
import my_utility print(my_utility.my_utility())
To sum up, I hope now you have understood the root cause of the module object is not callable error with its Fix. Please comment below if you have any related views over it.
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox. | https://www.datasciencelearner.com/typeerror-module-object-is-not-callable-fix/ | CC-MAIN-2021-39 | refinedweb | 413 | 69.07 |
imread rotating image by 90 degree
I was trying to load the image..but after imread it is rotating the image by 90 degrees.
asked 2014-07-31 08:02:43 -0500
updated 2020-06-09 18:13:35 -0500
I was trying to load the image..but after imread it is rotating the image by 90 degrees.
I had the same issues, which turned out to be related to the Preview application on MacOS, which didn't fully save image changes. Simply rotate the image back and forth and make sure you save the image afterwards. By doing so the issue was resolved for me.
Besides the code is formatted quite bad. This is obviously not all the code.
But maybe you are confusing
inputImg with
input (which is previously declared?).
Sorry for wrong formatting..but I am doing nothing new..just read the image and show it..u will see that it is rotated.
//read the image
Mat input = cv::imread("image.jpg", CV_LOAD_IMAGE_COLOR);
//display
imshow("Input Image",input); waitkey(-1);
You will notice the image is inverted
Again, your code contains errors, please check it before submitting.
sorry I am new in coding so not aware of this facts.I will try to improve. can u please try this image
No, it is almost exactly the same as the first image and produces correct results as you can see from my output from previous reply. It has nothing to do with the image. Try adding the
cv:: namespace to opencv functions and classes and remove
using namespace cv.
Does someone has an answer ? I am facing the same issue... When I load an image from disk using cv::imread, the image is rotated...
Asked: 2014-07-31 08:02:43 -0500
Seen: 3,019 times
Last updated: Aug 04 '16?
orignal image :
Is this a question? Please share your code and attempts to reproduce/solve this.
Program :
if u look at output image u will notice that it is rotated. Even if u skip the part of resizing and directly showing the image it will give u rotated image
it might be due to exif data saved in the jpeg (landscape mode and such) | https://answers.opencv.org/question/38481/imread-rotating-image-by-90-degree/ | CC-MAIN-2021-10 | refinedweb | 367 | 68.06 |
I am not a web developer, so when I promised Cerebrata that I would write this article on accessing the Azure Blob Service through the REST API, I didn’t know anything about using REST APIs. I could write a WCF service that offers up a REST API that could be called, but I’d never actually executed a request against a REST API and examined the response. That made this article seem daunting, and while it’s the fifth article in the series about blob storage, it was the last one written.
One question you may ask if why do you want to know how to use the REST API? Well, the Azure product team frequently releases new features (this is the firehose effect). Many times, the new features are accessible through the REST interface, but hasn’t been surfaced through a storage client library or the UI (like the portal) yet. If you always want to use the latest and greatest, learning REST is a required skill. Also, if you want to access blob storage with a programming language that does not have an SDK or storage client library, you can use REST instead.
I find that I am rarely the only one in a room who doesn’t understand something – I’m just the only one brave enough to admit my ignorance. Because of that, I’m going to write this from the standpoint of someone who has no idea how to make a REST call. This may bore those who are all-knowing and just want the syntax for Azure blob storage. If so, feel free to skip to the end and check out the reference links at the bottom of the article.
For those of you who make REST calls but want more details about the fields used, those who want to know what “canonicalized” means, and those of you who, like me, have never actually executed a request to a REST API, this is the place for you. If you want to run amok through the REST API for blob storage, this will give you a good basis to start. I’ll link to the MSDN documentation and show how to translate it into an actual REST call. If I’m successful, then you will no longer need to go home sick to avoid someone who asks if you have time to test their REST API. (No, I’ve never done that, but I had a coworker once who did. Don’t do that – never miss an opportunity to learn something new.)
REST means “representational state transfer”. Wikipedia starts explaining REST this way: .” Phew. It makes me tired just reading that.
What does it mean? To me, REST is an architecture you can use when calling APIs or making APIs available to be called. It is independent of what’s happening on either side, and what other software is being used when sending or receiving the REST calls. You can write an application on a Mac, Windows, Linux, Nokia Lumia 1520 [free product placement because I love mine], iPhone, Samsung Galaxy Note, or web site that and use the same REST API for all of them. Data can be passed in and/or out when the REST API is called. The REST API doesn’t care what it’s called from – what’s important is the information passed in the request and the data provided in the response.
Now that you know more about REST than you ever thought you wanted to, let’s talk about writing code to make a REST call, specifically using the Azure Storage Services REST API. To use this, you actually have to have a storage account in an Azure subscription. I’m going to show an example for listing the containers. Once you get the hang of this, the other calls should be easy to figure out, and in case you have trouble, I’ll give you a link at the end to a project with has tons of sample code.
If you look at the Blob Service REST API, you’ll see all of the operations you can perform with the REST API. The storage client libraries are just wrappers around the REST APIs – they make it easy for you to access storage without writing REST APIs. But we’re going to do this the hard way since that’s the point of this article.
MSDN: List Containers API
Let’s look at the page in MSDN for the ListContainers operation so you understand where some of the fields come from in the request and response when we get to the next section with the code.
Request Method: GET. This is the HTTP method you will specify as a property of the web request. This could also be HEAD, PUT, or DELETE, depending on the API you are calling.
Request URI: We will build this from the blob storage account namespace and the resource string /?comp=list.
URI parameters: There are additional query parameters you can use when calling ListContainers. A couple of these are timeout (in seconds) for the call and prefix which is used for filtering.
Another helpful parameter is maxresults: if more containers are available than this value, the response body will container a NextMarker element that indicates the next container to return on the next request. To use this, you provide the NextMarker value as the marker parameter in the URI when you make the next request. This is like paging through the results.
To use additional parameters, you just append them to the resource string with the value, like this:
/ this to anything you want to; it will be stored in the storage analytics logs when logging is enabled.
Request Body: There is none for ListContainers. This is used on all of the PUT operations when uploading blobs, as well as SetContainerAccessPolicy, which allows you to send in an XML list of data access policies to apply. These are discussed in the article about Shared Access Signatures, which will be published later in this series. (Links to all of the published articles are displayed at the top of this post.)
Response Status Code: Tells of any status codes you need to know. In this example, it tells us that 200 is ok. For a complete list of HTTP status codes, click here.
Response Headers: These include Content Type; x-ms-request-id (the request id you passed in, if you passed one on; x-ms-version (indicates the version of the Blob service used), and the Date (UTC, tells what time the request was made).
Response Body: This is an XML structure providing the data requested. In our case, this will be a list of containers and their properties.
You will see these in the request and response information provided below, and in the code when creating the request and parsing the response.
Steps for creating the REST request
A couple of notes before starting – always use HTTPS rather than HTTP for security. Also, I recommend that you download Fiddler so you can examine the request and response of the REST calls. (It’s free.)
Let’s see how to build the REST request. This returns an HttpWebRequest object. The method signature and setting of some of the variables used are as follows:
For ListContainers, the method is GET. The resource is the query portion of the URI that indicates which API is being called, so the value is /?comp=list. I didn’t pull that out of the air – as noted earlier, it is on the MSDN page that shows the information about the ListContainers API. The resource is concatenated to the endpoint to create the request URI.
In this case, the endpoint is. I’ve hardcoded this value into the class where this code resides, along with the StorageAccount name and key. In a real application, those would reside in some kind of configuration file. The value for request URI ends up being.
For ListContainers, requestBody is null, the headers are null, ifMatch is string.Empty, and md5 is string.Empty. These are included in the method because there are other calls to the Storage Service that use them, so this will work regardless of which API you are calling. An example of where ifMatch is used is when calling PutBlob. In that case, you set ifMatch to an eTag, and it only updates the blob if the eTag you provided matches the current eTag on the blob. The md5 value is passed when creating or updating a blob and you want Azure to make sure the upload was successful by hashing the content and comparing the MD5 hash with the one you’ve passed in.
Instantiate an HttpWebRequest object (in the System.Net namespace), providing the request URI.
Set the request properties for method (GET, PUT, POST, etc.). Set the content length to 0; this is the length of the body, and it can be set later if there is a body.
Add the request headers for x-ms-date and x-ms-version. Add any additional request headers required for the call. ListContainers has no additional headers. An example of an API that will pass in extra headers is SetContainerACL. For blob storage, it will add a header called “x-ms-blob-public-access” and the value for the access level.
If there is a request body, add a request header for Accept-Charset and set the ContentLength.
Create the authorization header (this is the hard part) and add it to the list of request headers. I’ll show you how to create the authorization header later in the article.
Fill in the request body (if there is one).
Return the REST request to the caller.
At this point, you can call GetResponse() on that REST request. This calls the API and gets the response back. You can examine the response StatusCode (200 is okay), then parse the response. In this case, you get an XML list of containers. Here’s the code for calling the GetRESTRequest method to set the request, executing the request, and examining the response for the list of containers.
If you run Fiddler when making the call to GetResponse, these are the things you will see. The name of the storage account I’m using is testsnapshots.
Request:
GET /?comp=list HTTP/1.1
Request Headers:
x-ms-date: Mon, 05 Jan 2015 02:49:59 GMT
x-ms-version: 2014-02-14
Authorization: SharedKey testsnapshots:Es3ptO/u0bzuklCYDGBOPbBarCH8vE+L/dclRLG24M8=
Host: testsnapshots.blob.core.windows.net
Status code and response headers returned after execution:
HTTP/1.1 200 OK
Content-Type: application/xml
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: 51d62149-0001-0001-0b72-c053cb000000
x-ms-version: 2014-02-14
Date: Mon, 05 Jan 2015 02:50:01 GMT
Content-Length: 1110
Response body (XML): In our case, this shows the list of containers and their properties.
?<?xml version=”1.0″ encoding=”utf-8″?>
<EnumerationResults ServiceEndpoint=””>
<Containers>
<Container>
<Name>a-test-sas</Name>
<Properties>
<Last-Modified>Fri, 02 Jan 2015 02:31:03 GMT</Last-Modified>
<Etag>”0x8D1F44B4A1B9A30″</Etag>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
</Properties>
</Container>
<Container>
<Name>a-testblob</Name>
<Properties>
<Last-Modified>Fri, 02 Jan 2015 02:31:20 GMT</Last-Modified>
<Etag>”0x8D1F44B542F0DA7″</Etag>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
</Properties>
</Container>
<Container>
<Name>myimages</Name>
<Properties>
<Last-Modified>Sun, 07 Dec 2014 22:24:01 GMT</Last-Modified>
<Etag>”0x8D1E083A2B38EF4″</Etag>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
</Properties>
</Container>
<Container>
<Name>myimages-01</Name>
<Properties>
<Last-Modified>Sun, 07 Dec 2014 22:53:47 GMT</Last-Modified>
<Etag>”0x8D1E087CB6552D3″</Etag>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
</Properties>
</Container>
</Containers>
<NextMarker />
</EnumerationResults>
So that’s all it takes to make a request to the REST APIs for retrieving a list of containers from blob storage. That doesn’t seem too hard, does it? Oh. What about the authorization header. Oh yeah, the hard part.
Creating the authorization header
Creating the authorization header is the difficult part. I’m going to distill Microsoft’s authentication article down to what we need here. First, we will use a Shared Key authentication. The authorization header format looks like this:
Authorization=”SharedKey <storage account name>:<signature>”
That looks pretty simple, right? Oh wait, what is that Signature field? It is a Hash-based Message Authentication Code (HMAC) created from the request and calculated using the SHA256 algorithm, then encoded using Base64 encoding. Got that? (Hang in there, we haven’t even used the word “canonicalized” yet.)
This is;
You won’t use most of these fields. For blob storage, you will specify VERB, md5, content length, Canonicalized Headers and Canonicalized Resource. You can leave all the others blank (but put in the \n so it knows they are blank).
What the heck are CanonicalizedHeaders and CanonicalizedResource?? Good question. What the heck does canonicalized mean? It’s not even a recognizable word in the Word dictionary. Here’s what wikipedia says: In computer science, canonicalization (sometimes standardization or normalization) is a process for converting data that has more than one possible representation into a “standard”, “normal”, or canonical form. Uh-huh. In normal-speak, this means to take the list of headers (in the case of Canonicalized Headers) and standardize them into the required format. So basically, they decided on a format, and that’s what you have to use – that’s what this means. And in case you actually go read that MSDN page about authenticating the request, I’ll save you the trouble of looking up lexicographically in a dictionary and tell you that it basically means alphabetically.
Let’s start with those two canonicalized fields, because they are required to create the Authorization header.
Canonicalized Headers
To create this, take the headers that start with “x-ms-” and put them in a list and sort them. Then format them into a string of [key: value\n] bits concatenated into one string. For our example, this will return the following:
x-ms-date:Sun, 04 Jan 2015 00:48:38 GMT\nx-ms-version:2009-09-19\n
Here’s the code:
This calls GetHeaderValues which searches through the request headers and returns the value that goes with that header.
Canonicalized Resource
This part of the signature string represents the storage account targeted by the request. Remember that the Request URI is. This, plus the actual account name (testsnapshots in this case). In our example this returns the following:
/testsnapshots/\ncomp:list
If you have query parameters, this will include those as well. Here’s the code, which also handles additional query parameters and query parameters with multiple values.
So now that we have the canonicalized strings, let’s look at how to create the authorization header itself. We will start by creating a string of the message signature in the format of StringToSign previously displayed in this article. This is easier to explain using comments in the code, so here it is, the final routine that returns the Authorization Header:
When running this, the MessageSignature for our example looks like this:
GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:Wed, 07 Jan 2015 02:51:55 GMT\nx-ms-version:2014-02-14\n/testsnapshots/\ncomp:list
The final value for AuthorizationHeader is:
SharedKey testsnapshots:qrdrdEbRfvfLr/79lxozcp0lbEIn2tk5CRkIHBN/TBY=
This is placed in the request headers before posting the response.
How about another example?
How about if we call ListBlobs for container a-test-blob. If you look at the MSDN documentation for this API, you find that the method is GET and the RequestURI is:
It also has a query parameter called include with possible values snapshots, metadata, uncommittedblobs, and copy. You can see in the Message Signature below that by default, this requests the metadata and snapshots. With those values, this doesn’t just return the blobs, but also all of the snapshots of each blob. Snapshots will be discussed in a later article in this series. (Links to all of the published articles are displayed at the top of this post.)
If you run this through the code, these are the results you get:
Canonicalized Headers:
x-ms-date:Wed, 07 Jan 2015 02:57:51 GMTx-ms-version:2014-02-14
Canonicalized Resource:
/testsnapshots/a-testblobcomp:listinclude:metadata,snapshotsrestype:container
MessageSignature:
GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:Wed, 07 Jan 2015 02:57:51 GMT\nx-ms-version:2014-02-14\n/testsnapshots/a-testblob\ncomp:list\ninclude:metadata,snapshots\nrestype:container
AuthorizationHeader:
SharedKey testsnapshots:BYPOycD66nFD8BQ7fVkgkiZ9orsWuTEWpG6E3ybw4s0=
These are from Fiddler:
Request:
GET /a-testblob?restype=container&comp=list&include=snapshots&include=metadata HTTP/1.1
Request Headers:
x-ms-date: Wed, 07 Jan 2015 02:57:51 GMT
x-ms-version: 2014-02-14
Authorization: SharedKey testsnapshots:BYPOycD66nFD8BQ7fVkgkiZ9orsWuTEWpG6E3ybw4s0=
Host: testsnapshots.blob.core.windows.net
Status code and response headers returned after execution:
HTTP/1.1 200 OK
Content-Type: application/xml
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: e116a424-0001-0044-7ad3-292d57000000
x-ms-version: 2014-02-14
Date: Wed, 07 Jan 2015 03:00:36 GMT
Content-Length: 9665
Response body (XML): This shows the list of blobs and their property and metadata. I’ve edited the list and removed all the entries but one for clarity.
<?xml version=”1.0″ encoding=”utf-8″?>
<EnumerationResults ServiceEndpoint=”” ContainerName=”a-testblob”>
<Blobs>
<Blob>
<Name>AZCopyTestImages/BeardedSealOnIceberg_Svalbarg_Norway_EN-US1166573819.jpg</Name>
<Properties>
<Last-Modified>Sun, 07 Dec 2014 21:39:32 GMT</Last-Modified>
<Etag>0x8D1E07D6C60364C</Etag>
<Content-Length>79310</Content-Length>
<Content-Type>image/jpeg</Content-Type>
<Content-Encoding />
<Content-Language />
<Content-MD5>MADqzfCVAL262BgtJ+Gbow==</Content-MD5>
<Cache-Control />
<Content-Disposition />
<BlobType>BlockBlob</BlobType>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
</Properties>
<Metadata />
</Blob>
</Blobs>
<NextMarker />
</EnumerationResults>
Summary
In this article, I explained how to make a request to the blob storage REST API to retrieve a list of containers or a list of blobs in a container. I showed you the code for creating the authorization signature and using it in the REST request, and how to examine the response. I have to thank Neil Mackenzie for his blog article that got me started on my way. And a big shoutout to David Pallmann. He has a project on CodePlex that shows how to perform every Azure Storage operation for blobs, queues, and tables using REST or the storage client library. It’s from 2011, but the REST API code still works. I updated the version and used it as the basis for this article. It really helped me understand the documentation posted on MSDN, which has too many words and not enough code.
Please check out the next article when it’s published; it will be about Blob Properties, Blob Properties properties, and metadata, and will hopefully explain it far better than MSDN does, at least at this time. | https://www.simple-talk.com/cloud/platform-as-a-service/azure-blob-storage-part-5-blob-storage-rest-api/ | CC-MAIN-2017-09 | refinedweb | 3,172 | 53.1 |
Proportional Integral (PI) Control
A variation of Proportional Integral Derivative (PID) control is to use only the proportional and integral terms as PI control. The PI controller is the most popular variation, even more than full PID controllers. The value of the controller output `u(t)` is fed into the system as the manipulated variable input.
$$e(t) = SP-PV$$
$$u(t) = u_{bias} + K_c \, e(t) + \frac{K_c}{\tau_I}\int_0^t e(t)dt$$
The `u_{bias}` term is a constant that is typically set to the value of `u(t)` when the controller is first switched from manual to automatic mode. This gives "bumpless" transfer if the error is zero when the controller is turned on. The two tuning values for a PI controller are the controller gain, `K_c` and the integral time constant `\tau_I`. The value of `K_c` is a multiplier on the proportional error and integral term and a higher value makes the controller more aggressive at responding to errors`.
Discrete PI Controller
Digital controllers are implemented with discrete sampling periods and a discrete form of the PI equation is needed to approximate the integral of the error. This modification replaces the continuous form of the integral with a summation of the error and uses `\Delta t` as the time between sampling instances and `n_t` as the number of sampling instances.
$$u(t) = u_{bias} + K_c \, e(t) + \frac{K_c}{\tau_I}\sum_{i=1}^{n_t} e_i(t)\Delta t$$
Overview of PI Control `u_{bias}`.
Common tuning correlations for PI control are the ITAE (Integral of Time-weighted Absolute Error) method and IMC (Internal Model Control). IMC is an extension of lambda tuning by accounting for time delay. The parameters `K_c`, `\tau_p`, and `\theta_p` are obtained by fitting dynamic input and output data to a first-order plus dead-time (FOPDT) model.
IMC Tuning Correlations
$$}{\left( \theta_p + \tau_c \right)} \quad \quad \tau_I = \tau_p$$ \mathrm{Simple\,tuning\,correlations}$$
ITAE Tuning Correlations
Different tuning correlations are provided for disturbance rejection (also referred to as regulatory control) and set point tracking (also referred to as servo control).
$$K_c = \frac{0.586}{K_p}\left(\frac{\theta_p}{\tau_p}\right)^{-0.916} \quad \tau_I = \frac{\tau_p}{1.03-0.165\left(\theta_p/\tau_p\right)}\quad\mathrm{Set\;point\;tracking}$$
$$K_c = \frac{0.859}{K_p}\left(\frac{\theta_p}{\tau_p}\right)^{-0.977} \quad \tau_I = \frac{\tau_p}{0.674}\left(\frac{\theta_p}{\tau_p}\right)^{0.680}\quad\mathrm{Disturbance\;rejection}$$.
Suppose that a driver of a vehicle set the desired speed set point to a value higher than the maximum speed. to lower the throttle until the negative error cancels out the positive error from the hour of driving. The automobile would not slow down but continue at full throttle for an extended period of time. This undesirable behavior is fixed by implementing anti-reset windup.
Exercise
The purpose of this exercise is to investigate the cause of offset in a P-only controller and oscillations in a PI controller.
Open Loop Response
Consider a first order plus dead time process as
$$\tau_p \frac{dy}{dt} = -y + K_p u \left(t-\theta_p\right)$$
with `K_p = 2`, `\tau_p = 200`, and `\theta_p = 0`. Simulate the behavior for making a step change in manual mode from 0 to 10 (and back). Explain what happens in terms of oscillations or a smooth response.
P-only Control
Simulate the behavior for using
Configure the controller to add an integral term in addition to the proportional control with `K_c = 2`. Simulate the PI controller response with integral reset times `\tau_I=200, 100, 10`. Include a plot of the integral of the error between the set point (SP) and process variable (PV) with anti-reset windup. Explain what happens and why.
Open Loop Response with Dead Time
Add dead time `\theta_p=100` as an input delay. Simulate the behavior for making a step change in manual mode from 0 to 10 (and back). Explain what happens in terms of oscillations.
P-only Control with Dead Time
With the dead time, simulate the response of with Dead Time
Simulate the response of a PI controller with `\tau_I=200`. Include a plot of the integral of the error between the set point (SP) and process variable (PV) with anti-reset windup. Explain what happens and why. Explain the results.
Summary Questions
- Based on the observations in manual mode, is the process stable or unstable?
- Why does P-only control have persistent offset?
- What is the effect of dead time on P-only and PI control?
- If the process is stable, why can the control system make it unstable?
Sample Code
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# specify number of steps
ns = 1200
# define time points
t = np.linspace(0,ns,ns+1)
# mode (manual=0, automatic=1)
mode = 1
class model(object):
# process model
Kp = 2.0
taup = 200.0
thetap = 0.0
class pid(object):
# PID tuning
Kc = 2.0
tauI = 10.0
tauD = 0
sp = []
# Define Set Point
sp = np.zeros(ns+1) # set point
sp[50:600] = 10
sp[600:] = 0
pid.sp = sp
def process(y,t,u,Kp,taup):
# Kp = process gain
# taup = process time constant
dydt = -y/taup + Kp/taup * u
return dydt
def calc_response(t,mode,xm,xc):
# t = time points
# mode (manual=0, automatic=1)
# process model
Kp = xm.Kp
taup = xm.taup
thetap = xm.thetap
# specify number of steps
ns = len(t)-1
# PID tuning
Kc = xc.Kc
tauI = xc.tauI
tauD = xc.tauD
sp = xc.sp # set point
# step input for manual control
if mode==0:
op[100:]=2
# Upper and Lower limits on OP
op_hi = 100.0
op_lo = 0.0
# Simulate time delay
ndelay = int(np.ceil(thetap / delta_t))
#]
if mode==1:
# implement time delay
iop = max(0,i-ndelay)
y = odeint(process,pv[i],[0,delta_t],args=(op[iop],Kp,taup))
pv[i+1] = y[-1]
op[ns] = op[ns-1]
ie[ns] = ie[ns-1]
P[ns] = P[ns-1]
I[ns] = I[ns-1]
D[ns] = D[ns-1]
return (pv,op)
def plot_response(n,mode,t,pv,op,sp):
# plot results
plt.figure(n)
plt.subplot(2,1,1)
if (mode==1):
plt.plot(t,sp,'k-',linewidth=2,label='Set Point (SP)')
plt.plot(t,pv,'b--',linewidth=3,label='Process Variable (PV)')
plt.legend(loc='best')
plt.ylabel('Process Output')
plt.subplot(2,1,2)
plt.plot(t,op,'r:',linewidth=3,label='Controller Output (OP)')
plt.legend(loc='best')
plt.ylabel('Process Input')
plt.xlabel('Time')
# calculate step response
model.Kp = 2.0
model.taup = 200.0
model.thetap = 0.0
mode = 0
(pv,op) = calc_response(t,mode,model,pid)
plot_response(1,mode,t,pv,op,sp)
# PI control
pid.Kc = 2.0
pid.tauI = 10.0
pid.tauD = 0.0
mode = 1
(pv,op) = calc_response(t,mode,model,pid)
plot_response(2,mode,t,pv,op,sp)
plt.show()
Assignment | https://apmonitor.com/pdc/index.php/Main/ProportionalIntegralControl | CC-MAIN-2018-09 | refinedweb | 1,149 | 50.23 |
parseargs
Full-featured command-line argument parsing library.
See all snapshots
parseargs appears in
parseargs: Command-line argument parsing for Haskell programs
This library provides System.Console.Parseargs, a module to assist in argument parsing for Haskell stand-alone command line programs.
The package provides a Haskell command-line argument
"parser". You supply a specification of the arguments to
your command-line program;
parseargs reads the arguments
and checks that they meet your spec. It then fills in a data
structure that captures the relevant data, from which parsed
arguments can be extracted as needed. See the Haddock
documentation for the gory details.
I have used this code with
ghc 6 and later on Linux. It
is a fairly standard Hackage-ready package, to the extent I
know how to construct such.
This library is not what I set out to build. It definitely could also use some work. However, I use it all the time for writing little programs. I thought others might find it useful, and I also have released other code that depends on it, so I put it out there.
Have fun with it, and let me know if there are problems.
Release History
The 0.1.2 release includes a typeclass for argument types for easier use.
The 0.1.3 release includes more uniform and usable error handling.
The various 0.1.3.x point releases include bug fixes and various extra-minor enhancements. See the Git log.
The 0.1.4 release includes the ability to mix optional and required positional arguments.
The 0.1.5 release includes the "soft dash" option, giving the ability to allow positional arguments to begin with a dash if possible.
The 0.1.5.1 release fixes some warnings and stuff.
The 0.1.5.2 release fixes some missing documentation.
The 0.2 release cleans up some namespace pollution by removing
ArgRecordand the
argsaccessor from the public namespace. This allows the use of the name
argsby the user to describe program arguments.
The 0.2.0.1 release cleans up a bunch of documentation nits and cleans up copyright notices and license information.
The 0.2.0.2 release fixes the botched release of 0.2.0.1. Sigh.
The 0.2.0.3 release fixes the missing
Argsconstructor documentation of 0.2.0.2.
The 0.2.0.4 release suppresses a GHC 7.10 warning for
Control.Monad.Safe.
License
This program is licensed under the "3-clause ('new') BSD License". Please see the file COPYING in this distribution for license terms. | https://www.stackage.org/nightly-2017-12-18/package/parseargs-0.2.0.8 | CC-MAIN-2018-05 | refinedweb | 428 | 59.8 |
Here I present a class that can be substituted in place for the the .NET framework's
System.Random class to provide some advantages:
System.Randomfor comparison.
System.Random. Up to 8x faster, depending on which methods are called and which CLR is used (see table below).
System.Random. This class implements all of the methods that
System.Randomdoes plus some additional methods for generating random
uints and booleans. The like named methods are functionally equivalent to those in
System.Random.
System.Randomwhich accepts a seed at construction time only, which then executes a relatively expensive initialization routine. This provides a vast speed improvement if you need to reset the pseudo-random number sequence many times, e.g., if you want to re-generate the same sequence many times. An alternative might be to cache random numbers in an array, but that approach is limited by memory capacity and the fact that you may also want a large number of different sequences cached. Each sequence can be represented by a single seed value (
int). case. I then discovered that a number of further performance improvements could be made to the
Next*() methods. The first version of
FastRandom posted on CodeProject used a multiply-with-carry (MWC) algorithm devised by George Marsaglia. Forum posters pointed out that some seeds generated a sequence of the same number, and whilst investigating the solution, I came across another of Marsaglia's algorithms utilizing an XOR-shift technique that was even faster than MWC. The current version of
FastRandom therefore implements XOR-shift and should also provide good random sequences for all seed values (including 0).
The random number generator (RNG) used generates new numbers using just bitwise XOR and left and right shifts. The method
NextUInt provides the simplest example because it returns the generated 32 bit number (
uint) without any further manipulation:
public uint NextUInt() { uint t= (x^(x<<11)); x=y; y=z; z=w; return (w= (w^(w>>19))^(t^(t>>8))); }
The state of the RNG is described by the four
uint variables
x,
y,
z and
w.
w represents most recently generated number, and a history of the last four generated numbers is maintained with the inclusion of the
x,
y and
z variables. New numbers are generated by applying various shifts and XORs to
x, which represents the number generated four calls ago. Storing and using the history of the last four numbers in this manner results in an RNG with a longer period, here the period is 2^128-1. The period can be shortened or lengthened by adjusting the amount of history variables stored. For more information on this, see the paper referred to above.
All of the other
Next*() methods are variations of this technique, taking the 32 bits generated and manipulating them into
double,
int,
bytes, etc.
The
Reinitialise methods allow the caller to reset
FastRandom with a single integer seed value and thus generate the same set of random numbers over again. This can sometimes be useful, e.g., in simulations where you might want to recreate the same scenario exactly as before. Note that
System.Random provides no such method for re-initializing (re-seeding) the class once it is constructed; the only option is to construct a new instance and pass the seed in to the constructor, which then executes code to build an array of seed data. By allowing re-initialization and avoiding the need to build a seed data array,
FastRandom provides a significant performance improvement where reseeding is required.
Next()and
NextBytes(byte[]).
intto
double, and not from
uintto
double. In tests, casting from
uinttook twice as long as casting from
int. This speed-up applies to
NextDouble(),
Next(int)and
Next(int,int).
virtual. The virtual method table generates some overhead even in released, optimized code where the methods haven't actually been overridden.
System.Random's methods are declared as
virtualand therefore generate this overhead. There may be sound reasons for this within the .NET framework, but if you just want a fast RNG today, then we can omit the
virtualkeyword in our declarations.
NextBytesmethod, we generate 32 bits at a time and fill the byte array in 4 byte chunks.
For prior readers of this article please note that this is an updated version of the table that takes into account improvements made to FastRandom.cs made since the article was first posted and also to the .NET runtime engine between .NET 1.1 and .NET 2.0.
Other notes:
FastRandomand
System.Randomrun faster on the .NET 2.0 CLR than on .NET 1.1. However,
System.Randomdoes benefit more than
FastRandomand so the performance gap between the two classes is narrower in .NET 2.0.
Next(int,int)with a long range between the two integer parameters, on the .Net 1.1 CLR FastRandom's version actually ran slower, however on .NET 2.0 this result is now reversed as can be seen in the table below.
The following performance figures were obtained using released, optimized code executing on an Intel Core 2 Duo E660 overclocked to 3.11Ghz. This is a dual core chip, however these performance figures are for a single core only:
* - An alternative execution path occurs when the range between the lower and upper limits will not fit within an
int. This results in a different performance figure.
Note the last three methods which are extra methods not present on
System.Random.
NextUint() is provided because
uint is the underlying data type behind
FastRandom and so is very fast to generate.
NextInt() returns an
int (
Int32<?CODE>) but unlike
Next() the range is between
0 and
int.MaxValue instead of between
0 and
int.MaxValue-1. This subtle difference allows an optimization to be made (elimination of an 'if' statement).
NextBool() is implemented by generating 32 bits (
uint) and buffering them for future calls, hence the high speed.
System.Random is actually very fast and achieves its speed mostly by only using simple and fast arithmetic operations such as shift and add. However, the whole class is based around a central
Sample() method that returns a
double between 0.0 and 1.0, and thus there is some unnecessary floating point arithmetic used to generate integer values.
FastRandom utilizes a completely different algorithm for generating random numbers that is inherently slightly faster, and in
FastRandom we provide a further boost by avoiding floating point arithmetic wherever possible and implementing some further refinements. Finally,
FastRandom also allows for fast re-seeding which allows repeat random number sequences to be re-generated very quickly.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/fastrandom.aspx | crawl-002 | refinedweb | 1,109 | 55.24 |
Directory Listing.
Merging ripley diagonal storage + CUDA support into trunk. Options file version has been incremented due to new options 'cuda' and 'nvccflags'.
Made more methods pure virtual in AbstractDomain and moved the generic implementation into NullDomain. Made TestDomain derive from NullDomain to inherit the methods....
unit gal added.
nonuniformInterolate and Slope added. Doco later
Adding some linebreaks
Unit tests for binary install with no scons and no source tree. Script for installing and testing a .deb within a chroot.
this will break the downundermodule: major revision of the classes.
small fix
ArithmeticTuple supports empty data object as components now.
Deprecated saveDX and made sure DeprecationWarnings are shown (py2.7 disabled those). Also a fix to $BUILD_DIR being non-absolute.
magnetic inversion added
Tweaked scons files so tests work even when specifying non-absolute build_dir.
missing file
linearPDE.resetRightHandSideCoefficients has been implemented and tested.
Another fix to the PDE assembly logic in ripley..
Changed data source to use ripley's netCDF reader, added tests and changed ERMapper test to have different x and y sizes..
Small bug fixed.
darcy solver removes hydrostatic pressure from problem now
Disable AMG on MPI builds
length scale changed
Merged changes across from the attempt2 branch. This version builds and passes python2 tests. It also passes most python3 tests..
Fixed some unused var errors in non-mpi build.
Switching to external cppunit: -removed tools/CppUnitTest -updated scons script and files -updated tests to changed API -updated readme Bumped scons options file version to 201. Additions: -cppunit* -boomeramg* -vsl_random.
AMG support now block size > 3 (requires clapack or MKL). additional diagnostics for AMG
RandomData added
some clarification on lumping
Pass dictionary of data objects to EscriptDataset as kwargs in DataManager.
Fix to unit tests
matrix balance introduced in paso
3d interpolateTable support. New more generic interface for table interpolation. tests and doco updated
Fix some epydoc errors Fixed issue 564 removed minimize.py since it hasn't worked in who knows how long
a more flexiblae version of safeDiv.
some print statements removed
AMG reengineered, BUG is Smoother fixed.
Fixed some intel compiler warnings. Put linearPDEs back the way it was and present a common interface for dudley and finley (as per Lutz)
Renamed restarts.py to datamanager.py, added a method to explicitly set the domain without adding data. Calling export() without domain/data will now output a warning. Some additional cleanup.
Removing dead files
Merging dudley and scons updates from branches
bug in meanValue fixed.
- weipa's saveVTK will now save multiple files if the data objects to write are not on the same mesh. - the save* methods now also add the appropriate file extension if not already supplied.
bug fixed in RILU and test modified.
GS and Jacobi are now used through the same interface.
Don't clear domain on error. Moved adding Metadata-tags to the C++ level.
some diagnostics for time step backtracing added
Fixed a typo.
Added accessor for the simulation cycle and log which directory was used to restart.
Fixed export when 'work_dir' is set to sth other than the current dir.
test fix
Inject the DataManager class to the escript namespace.
weipa's saveVTK now stores metadata schema & string as expected.
bug in ILU0 fixed.
-New VisIt simulation control interface in weipa (uses VisIt's simv2) -Rewrote restarts.py to be a more generic data manager for restarts and exports -Removed weipa python file since the functionality is now handled by restarts.py
The MPI and sequational GAUSS_SEIDEL have been merged. The couring and main diagonal pointer is now manged by the patternm which means that they are calculated once only even if the preconditioner is deleted.
small bug fixed.
a light restart manager added.
Switched the build_dir keyword param to variant_dir. Should fix issue 525.
tolerance for PCG relaxed.
new darcy flux
AMG levels maximum set 5
C-level lumping switched on
FCT solver rewritten
bar as unit added
new DarcyFlux solver
bug introduced by a smart programmer to the Locator has been fixed?
a new almost completed version of the cookbook
saveESD now doesn't store the absolute path to the files in the ESD file so the whole dataset can be moved easily..
Fix for ambiguous call to sqrt....
Don't panic. Updating copyright stamps..]
More fixes to resolveGroup
ResolveGroup fixed so it actually resolves groups. Children, when you iterate backwards remember its i>=0 not i>0
test is added for selecting standard coarsening.
Dodge problem in NoPDE class.
sorry python Indentation Error, fixed
minor typo
Projector class had getSolverOptions(), but was returning null, so changed to return correct solver options.
getSolverOptionsDiv was returning Pressure options instead of Div equation options
changes to default threshold values
documentation for pycad added. fixes to interpolation
missing offset added in interpolation table.
pre cleanup
Fixed some of my stupids related to MPI compile errors.
Adding getMPIComm
saveDataCSV looks good but does not do MPI yet. Also not unit tested..
reduced PDE solutions added to topography
reengineered version of the mountain class so it becomes easier to use for the convection code
a problem with the sparse matrix unrolling fixed.
Remainder of copyright date fixes
Updating copyright notices.
util: Updated saveESD to allow saving of time series. Combined with an update of the visit plugin this fixes issue 325..
Correcting some doxygen errors
Fixed bug in Locator
Fixed compile warning on Mac
some fixes in wave.py example.
Taipan now prints an error message if new[] throws. Note, the exception is rethrown after the message is printed.
MPI_DOUBLE changed to MPI_INT as lowProc is int
Added maxGlobalDataPoint. Not currently unit tested..
some more work toward numpy.
Week 9: implemented cosine taper for wave function, need to work on direct method without lumping, wave propagation velocity is still not correct
same adjustment of nameing
some improvement on convection which ios now working again
convection works now again.
new version of power law (blame Hans).
units support Celsius, Farenheit and kelvin now
some improvements on units
first version of units in escript
some minor fixes
Added getDataRW to DataC
some modifications to docu for MPI
some modifications to the Darcy flux solver to make it faster and more robust.
some fixes in the transport solver
first version of escript command: no MPI support yet.
obsolet.
soem small fixes.
doxygen doco now correctly reports global project revsion number. link to epydoc is now via a relative URL (avoids the problem of nightly doxygen pointing at out of date release epydoc).
setTaggedValueByName now throws if the tag name does not exist. The documentation says this is what happens - now the code matches the doco. This resolves issue 238
mofification of the weighting factor
for some reason my gcc version requires NL at the end of the source files.
type fixed
Added compile flags to turn autolazy on and off. These are for testing purposes only.
Stop icpc on savanna warning about ignoring namespaces.
Merging version 2269 to trunk
weighting factor introduced.
somehow the fix of the test did not make it into the repository.
a new darcy flux solver.
GMRES supports prconditioning from the right now.
That should be the last of the copyWithMask related errors.
Fixes errors due to feeding scalars and vectors into the same call to maximum.
Throw an exception if AbstractDomain::MPIBarrier is called (This shouldn't happen). Added Barrier to saveVTK. Replaced some misused keywords.
problem in maximum fixed.
new compressible flow solver
Fixed some pathing issues.
Made some changes to the way copyWithMask works.
renaming to make _GMRESm visibale
Development continues on unit test framework
Added pyvisi and c++ unit tests to build of utest.sh
better method to du clipping
Added support for generating non-scons test scripts
Modified scons files to compile c++ unit tests with the same options used to compile the libraries.
First version of the mountains class.
more work on the dary solver
Fixed a little doxygen typo in the hyperlink.)
modifications to the way cosntraints are handeled in the Transport problem
Fixed a bug in lazy evaluation of Tensor Products. Added / to end of boost path
Implemented new utility function saveESD() which takes care of dumping the given data objects with their domain and creates an ESD file containing the required information. This obsoletes the necessity to use esdcreate for single timestep datasets.
Fixed some more typos
Fixed compilation with boost 1.37 (namespace clash).
used unused variable. Added support for limiting the size of lazy expression trees. 500,000 seems a bit high
Unitary minus applied to unsigned returns unsigned error fixed lines 1124 & 1142. Probably not what was intended......
Another unit test fix
Assorted spelling, grammar, whitespace and copy/paste error fixes (Part 2). All epydoc warnings for these files have been fixed. This commit should be a no-op.
Adjust tests for changes to number of buffers required. Prevent cpp unit test from failing.
Fixed a bug related to lazy trace
Assorted spelling, grammar, whitespace and copy/paste error fixes (Part 1). This commit should be a no-op.
Some lazy fixes to the symmetric operation.
some modifications to the iterative solver to make them easier to use. There are also improved versions of the Darcy flux solver and the incompressible solver.
*.
typo fixed
some minor changes to PCG and some extra suspicious characters...
Fix the test for erf() under intelc on windows to something more informative.
Now add the erf() test back for windows under the intelc compiler..
bug fixed.
removed one signed/unsigned value comparison. The remaining one at line 863 is far more difficult to deal)
small fixes.
Fixed two typos that stopped the test suite from running. Also, gcc 4.3.2 issued several warnings not seen before: ignoring the return value of fscanf and using the wrong format with printf..
num_equations -> numEquations
Fixed a compile error under MPI. Cleaned up a comment.
Closing the moreshared branch
a bug in the nc test fixed (hopefully.)
minres test are switched on
first version of testing for transport solver.
Updated doco to describe the behaviour of inf, sup and Lsup for cases where none of the tags in use in the domain have values. It confused me when I was testing.
The NC dump tests work now with MPI. In fact the old test did not exactly what it supposed to
Install runmodel.py into bin Remove obsolete script esysXML.py.
Cleaned up use of gethostname.
levelset in the way laurent did it.
MINRES solver is added to escript. Additional 16 tests are added to run_simplesolve for MINRES and TFQMR solvers
Removed failing test until we fix a bug. Fixed several compiler warnings.
no ifdef _OPENMP required
MPI parallelism for Data().dump and load. Use multiple NetCDF files, one file per MPI process
the MaskFromBoundaryTag function didn't make much sense. The argument function_space is replaced by domain.
robust function to normalize data object added
method returning reference id added to FunctionSpace class
Modified toString() on Data objects. str(x) or print x will now print a summary of the data rather than all the points if the output would take more than 80 lines.
now convection works for other solvers as well, besides PCG.
more algorithms for level set.
some improvements on level set
some first version of a robust level.
tmp_str was unused var on windows.
Resolved some compiler warnings Changed blocktimer to not use strdup, intead malloc and strcpy
Last commit hung. Trying to recover. Also, remove excessive extern C {} I introduced
eliminate unused var argument of catch.
interpolate accepts now float and numarray as argument)
Compiles and runs on Savanna (hostname service0))
reordering when reading Netcfd files | https://svn.geocomp.uq.edu.au/escript/trunk/escriptcore/?pathrev=5273&view=log | CC-MAIN-2019-18 | refinedweb | 1,936 | 68.47 |
Table of Contents:
- I often use my own posts as references and it’s always easier for me to find information in my own writings.
- I wanted to use this post as a reference platform for subsequent posts about dynamic routing and OVN project..
Virtual topology overview
Let’s see what we’re going to be dealing with in this post. This is a simple virtual topology with two VMs sitting in two different subnets. VM1 has a floating IP assigned that is used for external access.
.
Virtual topology setup
Upload Cirros Linux image to OpenStack’s image repository
curl | glance \ image-create --name='IMG-CIRROS' \ --visibility=public \ --container-format=bare \ --disk-format=qcow2
Create 2 virtual subnets - RED and BLUE
neutron net-create NET-BLUE neutron subnet-create --name SUB-BLUE NET-BLUE 10.0.0.0/24 \ --dns-nameserver 8.8.8.8 neutron net-create NET-RED neutron subnet-create --name SUB-RED NET-RED 10.0.1.0/24 \ --dns-nameserver 8.8.8.8
Create external network
neutron net-create EXT-NET --provider:network_type flat \ --provider:physical_network extnet \ --router:external \ --shared neutron subnet-create --name EXT-SUB \ --enable_dhcp=False \ --allocation-pool=start=169.254.0.50,end=169.254.0.99 \ --gateway=169.254.0.1 EXT-NET 169.254.0.0/24
Create a router and attach it to all three networks created above
neutron router-create R1 neutron router-interface-add R1 SUB-RED neutron router-interface-add R1 SUB-BLUE neutron router-gateway-set R1 EXT-NET
Create two host aggregates to spread the VMs across two different hosts
nova aggregate-create AGG-RED AZ-RED nova aggregate-create AGG-BLUE AZ-BLUE nova aggregate-add-host AGG-BLUE compute-2 nova aggregate-add-host AGG-RED compute-3
Boot VMs on two different hypervisors
nova boot --flavor m1.tiny --image 'IMG-CIRROS' \ --nic net-name=NET-BLUE \ --availability-zone AZ-BLUE \ VM1 nova boot --flavor m1.tiny --image 'IMG-CIRROS' \ --nic net-name=NET-RED \ --availability-zone AZ-RED \ VM2
Assign a floating IP (Static NAT) to VM1
nova floating-ip-create EXT-NET nova floating-ip-associate VM1 169.254.0.55
Enable ingress ICMP and SSH access
nova secgroup-add-rule default tcp 22 22 0.0.0.0/0 nova secgroup-add-rule default icmp -1 -1 0.0.0.0/0
Make sure that both VMs are up and running.
+--------------------------------------+------+--------+------------+-------------+----------------------------------+ | ID | Name | Status | Task State | Power State | Networks | +--------------------------------------+------+--------+------------+-------------+----------------------------------+ | 92263ae8-43d1-4cd0-b271-2b11f0efbe7f | VM1 | ACTIVE | - | Running | NET-BLUE=10.0.0.12, 169.254.0.55 | | b4562f24-2461-49fb-875b-fa1bf869dc4a | VM2 | ACTIVE | - | Running | NET-RED=10.0.1.4 | +--------------------------------------+------+--------+------------+-------------+----------------------------------+
non-DVR traffic flow
Using the technique described in my earlier post I’ve collected the dynamically allocated port numbers and created a physical representation of our virtual network.
:
git pull origin master chef-client -z -E lab neutron.rb
Once all changes has been made, we need to either create a new router or update the existing one to enable the DVR functionality:
neutron router-update --admin-state-up False --distributed True R1 neutron router-update --admin-state-up True R1
DVR East-West traffic flow
Now let’s see how the traffic flows have changed with the introduction of DVR.
We’re going to be examining the following traffic flow:
- From VM1 (10.0.0.12/fa:16:3e:83:92:96)
- Via router R1 (10.0.0.1/fa:16:3e:72:7a:50; 10.0.1.1/fa:16:3e:6a:2c:8b)
- To VM2 (10.0.1.4/fa:16:3e:76:31:68)
R1 now has an instance on all compute nodes that have VMs in the BLUE or RED networks. That means that VM1 will send a packet directly to the R1’s BLUE interface via the integration bridge.
$ ovs-appctl fdb/show br-int port VLAN MAC Age 2 1 fa:16:3e:83:92:96 1 4 1 fa:16:3e:72:7a:50 1 5 2 fa:16:3e:6a:2c:8b 1:
$ ovs-appctl ofproto/trace br-tun in_port=1,dl_vlan=1,dl_dst=fa:16:3e:72:7a:50 | grep -E "Rule|action" Rule: table=0 cookie=0xa3536ac94478bd1d priority=1,in_port=1 OpenFlow actions=goto_table:1 Rule: table=1 cookie=0xa3536ac94478bd1d priority=2,dl_vlan=1,dl_dst=fa:16:3e:72:7a:50 OpenFlow actions=drop #3.
$ ovs-appctl ofproto/trace br-tun in_port=1,dl_vlan=2,dl_src=fa:16:3e:6a:2c:8b,dl_dst=fa:16:3e:76:31:68 | grep -E "Rule|action" Rule: table=0 cookie=0xa3536ac94478bd1d priority=1,in_port=1 OpenFlow actions=goto_table:1 Rule: table=1 cookie=0xa3536ac94478bd1d priority=1,dl_vlan=2,dl_src=fa:16:3e:6a:2c:8b OpenFlow actions=set_field:fa:16:3f:d3:10:60->eth_src,goto_table:2 Rule: table=2 cookie=0xa3536ac94478bd1d priority=0,dl_dst=00:00:00:00:00:00/01:00:00:00:00:00 OpenFlow actions=goto_table:20 Rule: table=20 cookie=0xa3536ac94478bd1d priority=2,dl_vlan=2,dl_dst=fa:16:3e:76:31:68 OpenFlow actions=pop_vlan,set_field:0x4d->tun_id,output.
$ ovs-appctl ofproto/trace br-tun in_port=3,tun_id=0x4d,dl_dst=fa:16:3e:76:31:68 | grep -E "Rule|action" Rule: table=0 cookie=0x8a7dedf35101427f priority=1,in_port=3 OpenFlow actions=goto_table:4 Rule: table=4 cookie=0x8a7dedf35101427f priority=1,tun_id=0x4d OpenFlow actions=push_vlan:0x8100,set_field:4097->vlan_vid,goto_table:9 Rule: table=9 cookie=0x8a7dedf35101427f priority=0 OpenFlow actions=goto_table:10 Rule: table=10 cookie=0x8a7dedf35101427f priority=1 OpenFlow actions=learn(table=20,hard_timeout=300,priority=1,cookie=0x8a7dedf35101427 Rule: table=0 cookie=0x9a1e0026794eadc5 priority=1 OpenFlow actions=NORMAL
Integration bridge of compute node #3 will lookup the destination MAC address and send the packet out port 2.
$ ovs-appctl fdb/show br-int port VLAN MAC Age 2 1 fa:16:3e:76:31:68 0 4 2 fa:16:3e:72:7a:50 0 5 1 fa:16:3e:6a:2c:8b 0 1 1 fa:16:3e:29:de:20 0
The reverse packet flow is similar - the packet will get routed on the compute node #3 and sent in a BLUE network to the compute node #2.
External connectivity
External connectivity will be very different for VMs with and without a floating IP. We will examine each case individually.
Case 1 - Overload NAT (VM2 with no FIP)
:
$ ip netns exec qrouter-uuid ip rule 0: from all lookup local 32766: from all lookup main 32767: from all lookup default 167772161: from 10.0.0.1/24 lookup 167772161 167772417: from 10.0.1.1/24 lookup 167772417
In our case table 167772161 matches all packets sourced from the BLUE subnet and if we examine the corresponding routing table we’ll find the missing default route there.
$ ip netns exec qrouter-uuid ip route list table 167772417 default via 10.0.1.12 dev qr-3779302e-62
The next hop of this default route points to the SNAT’s interface in the BLUE network. MAC address is statically programmed by the local L3-agent.
$ ip netns exec qrouter-uuid ip neigh | grep 10.0.1.12 10.0.1.12 dev qr-3779302e-62 lladdr fa:16:3e:29:de:20 PERMANENT
Integration bridge sends the packet out port 1 to the tunnel bridge.
$ ovs-appctl fdb/show br-int | grep fa:16:3e:29:de:20 1 1 fa:16:3e:29:de:20 1
Tunnel bridge finds the corresponding match and sends the VXLAN-encapsulated packet to the Network node.
$ ovs-appctl ofproto/trace br-tun in_port=1,dl_vlan=1,dl_dst=fa:16:3e:29:de:20 | tail -n 1 Datapath actions: set(tunnel(tun_id=0x4d,src=10.0.0.4,dst=10.0.0.0,ttl=64,flags(df|key))),pop_vlan,3
Tunnel bridge of the Network node forwards the frame up to the integration bridge.
$ ovs-appctl ofproto/trace br-tun in_port=3,tun_id=0x4d,dl_dst=fa:16:3e:29:de:20 | grep output OpenFlow actions=learn(table=20,hard_timeout=300,priority=1,cookie=0xb9be3fe62922c800
Integration bridge sends the frame to port 10, which is where SNAT namespace is attached
$ ovs-appctl fdb/show br-int | grep fa:16:3e:29:de:20 10 1 fa:16:3e:29:de:20 0
SNAT is a namespace with an interface in each of the subnets - BLUE, RED and External subnet
$ ip netns exec snat-uuid ip a | grep -E "UP|inet" 16: sg-fefd493b-a5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UNKNOWN link/ether fa:16:3e:99:5c:3a brd ff:ff:ff:ff:ff:ff inet 10.0.0.6/24 brd 10.0.0.255 scope global sg-fefd493b-a5 18: sg-b3d58360-b4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UNKNOWN link/ether fa:16:3e:29:de:20 brd ff:ff:ff:ff:ff:ff inet 10.0.1.12/24 brd 10.0.1.255 scope global sg-b3d58360-b4 19: qg-765b5aca-ce: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN link/ether fa:16:3e:d5:75:0e brd ff:ff:ff:ff:ff:ff inet 169.254.0.57/24 brd 169.254.0.255 scope global qg-765b5aca-ce
SNAT has a single default route pointing to the External network’s gateway.
$ ip netns exec snat-uuid ip route | grep default default via 169.254.0.1 dev qg-765b5aca-ce
Before sending the packet out, iptables will NAT the packet to hide it behind SNAT’s qg external interface IP.
$ ip netns exec snat-uuid iptables -t nat -L | grep SNAT SNAT all -- anywhere anywhere to:169.254.0.57
Case 2 - Static NAT (VM1 with FIP)
The first step in this scenario is the same - VM1 sends a packet to the MAC address of its default gateway. As before, the default route is missing in the main routing table.
$ ip netns exec qrouter-uuid ip route list table main 10.0.0.0/24 dev qr-102c4426-86 proto kernel scope link src 10.0.0.1 10.0.1.0/24 dev qr-3779302e-62 proto kernel scope link src 10.0.1.1 169.254.106.114/31 dev rfp-e4d4897e-7 proto kernel scope link src 169.254.106.114
Looking at the ip rule configuration we can find that table 16 matches all packets from that particular VM (10.0.0.12).
$ ip netns exec qrouter-uuid ip rule 0: from all lookup local 32766: from all lookup main 32767: from all lookup default 57481: from 10.0.0.12 lookup 16 167772161: from 10.0.0.1/24 lookup 167772161 167772417: from 10.0.1.1/24 lookup 167772417
Routing table 16 sends the packet via a point-to-point veth pair link to the FIP namespace.
$ ip netns exec qrouter-uuid ip route list table 16 default via 169.254.106.115 dev rfp-e4d4897e-7
Before sending the packet out, DVR translates the source IP of the packet to the FIP assigned to that VM.
$ ip netns exec qrouter-uuid iptables -t nat -L | grep NAT SNAT all -- 10.0.0.12 anywhere to:169.254.0.55
A FIP namespace is a simple router designed to connect multiple DVRs to external network. This way all routers can share the same “uplink” namespace and don’t have to consume valuable addresses from external subnet.
$ ip netns exec fip-uuid ip a | grep -E "UP|inet" 2: fpr-e4d4897e-7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 inet 169.254.106.115/31 scope global fpr-e4d4897e-7 15: fg-d3bb699d-af: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN inet 169.254.0.58/24 brd 169.254.0.255 scope global fg-d3bb699d-af
Default route inside the FIP namespace points to the External subnet’s gateway IP.
$ ip netns exec fip-uuid ip route | grep default default via 169.254.0.1 dev fg-d3bb699d-af
The MAC address of the gateway is statically configured by the L3 agent.
$ ip netns exec fip-uuid ip neigh | grep 169.254.0.1 169.254.0.1 dev fg-d3bb699d-af lladdr 32:3e:7d:13:ca:78 DELAY
The packet is sent to the br-int with the destination MAC address of the default gateway, which is learned on port 3.
$ ovs-appctl fdb/show br-int | grep 32:3e:7d:13:ca:78 3 3 32:3e:7d:13:ca:78 1
External bridge strips the VLAN ID of the packet coming from the br-int and does the lookup in the dynamic MAC address table.
$ ovs-appctl ofproto/trace br-ex in_port=2,dl_vlan=3 | grep actions= OpenFlow actions=pop_vlan,NORMAL
The frame is forwarded out the physical interface.
$ ovs-appctl fdb/show br-ex | grep 32:3e:7d:13:ca:78 1 0 32:3e:7d:13:ca:78 1:
$ ip netns exec fip-uuid ip route get 169.254.0.55 169.254.0.55 via 169.254.106.114 dev fpr-e4d4897e-7 src 169.254.106.115
Now that the FIP namespace knows the route to the floating IP, it can respond to ARPs on behalf of DVR as long as proxy-ARP is enabled on the external fg interface:
$ ip netns exec fip-uuid cat /proc/sys/net/ipv4/conf/fg-d3bb699d-af/proxy_arp 1
Finally, the DVR NATs the packet back to its internal IP in the BLUE subnet and forwards it straight to VM1.
$ ip netns exec qrouter-uuid iptables -t nat -L | grep DNAT DNAT all -- anywhere 169.254.0.55 to:10.0.0.12
DVR Pros and Cons
Without a doubt DVR has introduced a number of much needed improvements to OpenStack networking:
- East-West traffic now follows the most optimal path thereby reducing the load on the Network node.
- External connectivity to floating IPs now also follows the most optimal path directly to the compute node hosting the VM.
However, there’s a number of issues that either remain unaddressed or result directly from the current DVR architecture:
- DHCP and SNAT are still hosted on the Network node.
- Asymmetric routing means that every DVR needs to have an interface in every configured subnet, even when there are no VMs that belong to those subnets on the current compute node.
- Direct connectivity to FIP means that all compute nodes now need to have direct L2 adjacency to external subnets.
- FIP namespace on compute nodes consumes IP addresses from external subnets which can be a problem if external subnet is in a public IPv4 address range.
- DVR implementation as a network namespace creates additional overhead in packet processing.
Some of the above issues are not critical and can be fixed with a little effort:
- In order to reduce the scope of a External network VLAN span inside the DC, dedicate a subset of hosts that will have a direct L2 adjacency to external networks and only deploy external-facing VMs on those hosts.
- Since FIP namespace only requires an external IP address for debugging purposes, we can create an additional, secondary, subnet in RFC1918 space for FIP connectivity. This is enabled by a feature called subnet “Service types” and is available in the latest Newton release.. | https://networkop.co.uk/blog/2016/10/13/os-dvr/ | CC-MAIN-2020-05 | refinedweb | 2,555 | 52.8 |
!
(66048 AND 65536 = 65536)
This will return true if the flag is set and false if not.
General form:
If (<cumvalue> and <testvalue>) = <testvalue> then true else false
dim foo as boolean = yourval and constant > 0
but either way works ... the reason for comparing to 0 is that you could avoid a comparison by directly casting to a boolean if you really wanted to.
Greg
If a user has a flag value of SCRIPT, ACCOUNTDISABLE, HOMEDIR_REQUIRED = 11
and you need to deside whether he's got a value for ACCOUNTDISABLE = True or not.
I'd do it this way...
Get the UserFlagValue.
Get ValueToCheck.
GetValueToCheck = 2 (in this case, for ACCOUNTDISABLE)
Now please excuse me for not doing datatype casting. (VB.Net)
Function CheckFlagValue(ByVal UserFlagValue, ByVal, GetValueToCheck) As Boolean
Dim i = 16777216 (max flag value)
While i >= 1
If i <= UserFlagValue Then
UserFlagValue = UserFlagValue - i
If i = GetValueToCheck Then
Return True
End If
End If
i = (next flag value in descending order) (You may need to write anothe function to get next value here)
While End
Return False
End Function
return (UserFlagValue AND GetValueTOCheck) = GetValueToCheck
end function | https://www.experts-exchange.com/questions/21423841/How-to-determine-if-a-flag-has-been-set-based-on-cumulative-flag-values.html | CC-MAIN-2017-51 | refinedweb | 188 | 56.59 |
Hi, On May 14, 2009, at 1:14 AM, Reimar D?ffinger wrote: > On Wed, May 13, 2009 at 03:11:57PM -0700, Kenan Gillet wrote: >> + * @param guid contains at least 16 bytes >> + * @return 1 if the guid is a qcelp_13k guid, 0 otherwise >> + */ >> +static int is_qcelp_13k_quid(const uint8_t *guid) { >> + return !memcmp(guid, guid_qcelp_13k, 16) || >> + (!memcmp(guid + 1, guid_qcelp_13k+1, 15) && guid[0] == >> 0x42); > > Some explanation for this would be nice. > Also both > return (guid[0] == 0x41 || guid[0] == 0x42) && !memcmp(guid + 1, > guid_qcelp_13k_part, > sizeof(guid_qcelp_13k_part)); > i like this one the best, also explanation added. > >> +static int qcp_probe(AVProbeData *pd) >> +{ >> + if (AV_RL32(pd->buf ) == MKTAG('R', 'I', 'F', 'F') && >> + AV_RL32(pd->buf+ 8) == MKTAG('Q', 'L', 'C', 'M') && >> + AV_RL32(pd->buf+12) == MKTAG('f', 'm', 't', ' ')) > > Maybe > AV_RL32(pd->buf ) == AV_RL32("RIFF") && > AV_RL64(pd->buf + 8) == AV_RL64("QLCMfmt ") > or memcmp for the second part at least would be nicer. fixed > >> + unsigned char buf[16]; > > You use uint8_t elsewhere. fixed > >> + if (is_qcelp_13k_quid(buf)) { > > quid? fixed >> + url_fskip(pb, 2 + 80 + 2); // codec-version + codec-name + >> average-bps > > I think the average bps can be stored somewhere... stored in AVCodec.bit_rate > >> + c->nb_rates = get_le32(pb); >> + for (i=0; i<8; i++) { >> + c->rates_mapping[i].size = get_byte(pb); >> + c->rates_mapping[i].mode = get_byte(pb); >> + } >> + >> + url_fskip(pb, 20 + 4 + 4); // reserved + "vrat" + chunk-size > > I'm not sure that skipping all those chunk sizes is such a great idea, > it makes very strong assumptions about the format, while RIFF is very > flexible... moved vrat chunk handling in qcp_read_packet, it fixes the playing of fix 13k_fixed_full.qcp and 13k_fixed_half.qcp samples which are missing the mandatory vrat chunk. > >> + int ret = av_new_packet(pkt, buf_size); >> + >> + if (ret < 0) >> + return ret; >> + >> + pkt->pos = url_ftell(pb); >> + >> + ret = get_buffer(pb, pkt->data+1, buf_size-1); > > > Does the decoder really need "mode" when it already has the packet > size? no, the decoder does not really need "mode" but is possible to send an empty packet to the decoder? because qcelp has a SILENCE mode whose packet is empty. > Because then you could use av_get_packet. Actually I am tempted to > say: > just seek back one byte and use av_get_packet. that what the code used to do, but i though it was kind of ugly. > >> + if (ret <= 0 || buf_size != ret + 1) { >> + av_free_packet(pkt); >> + av_log(s, AV_LOG_ERROR, "Packet size is too >> small.\n"); >> + return ret <= 0 ? ret : AVERROR(EIO); >> + } > > Usually FFmpeg also returns partial packets, to allow e.g. to better > recover broken or badly cut files. fixed, i kept the warning though. > >> + c->data_size -= buf_size; >> + pkt->data[0] = mode; >> + av_shrink_packet(pkt, buf_size); > > The packet is already buf_size large, so what is the point of that? removed >> + if (!c->data_size && c->data_has_pad) >> + get_byte(pb); > > That data_size stuff is a bit unfortunate, it means that seeking will > not be possible by using the generic implementation. I am not sure to understand the issue of "data_size stuff." Could you elaborate? What would be needed for the generic implementation to work? a count of data packet is available in the vrat chunk which should be present in valid file. > Also why not e.g. just making sure that our position is two-byte > aligned before reading a tag? > Either > if (url_ftell() & 1) get_byte(); > or > if (c->data_has_pad) { > get_byte(); > c->data_has_pad = 0; > } > directly before tag = ...; fixed >> + case MKTAG('o', 'f', 'f', 's'): >> + url_fskip(pb, chunk_size); >> + break; >> + case MKTAG('t', 'e', 'x', 't'): >> + url_fskip(pb, chunk_size); >> + if (chunk_size & 1) >> + get_byte(pb); // 0 padding >> + break; > > Why not make the default case like that? good idea, it would make the demuxer more flexible. > Also you always need to skip padding for odd sizes, though > you can merge that with the odd data size case if you use either > of my suggestions above. padding is only for text and data chunks as the other chunks have already even sizes. I used your suggestions above anyway. > >> + case MKTAG('l', 'a', 'b', 'l'): >> + get_buffer(pb, c->label, 48); >> + break; > > What's the point of reading that (and wasting bytes in the context for > it)? it is for application use. removed for now, as well as the config. > >> + case 0: >> + if (url_feof(pb)) >> + break; > > Why inside the switch? If it's eof shouldn't you just always return > AVERROR_EOF? no longer needed thanks for the review will post an updated patch Kenan | http://ffmpeg.org/pipermail/ffmpeg-devel/2009-May/075339.html | CC-MAIN-2016-50 | refinedweb | 716 | 75.4 |
shows the input and output
displayed when the roundtrip from user to database to user is
complete.
Every part of the Firefox interface is created using XUL [Hack #68] . We use it to create entire
application interfaces. Whether it is bookmarks or toolbars, menus or
buttons, in Firefox, XUL is ultimately responsible.
Most
XUL
can be created upfront and hardcoded. However, some XUL needs to be
built dynamically; bookmarks are a good example of XUL that
can't be hardcoded. To this end, XUL supports
templates [Hack #70] : dynamic
portions of a XUL document that are populated at runtime, based on
some external XML data.
The XML data that Firefox is most concerned with is
RDF. To recap, RDF is
concerned with making statements about things.
Each statement is comprised of three pieces of information: the thing
we're making the statement about, a
property of the thing, and the
value of that property. In
RDF
parlance, this is called a triple, and the
thing, property, and values are called subject,
predicate, and object,
respectively. For example, Firefox Hacks (the
thing) has an author (the property) of Nigel
McFarlane (the value). In RDF, we would write this statement roughly
as follows (but this is just illustrative):
<rdf>
<Description about="FirefoxHacks">
<author>Nigel McFarlane</author>
</Description>
</rdf>
This is an RDF triple, which an XUL template uses to build XUL
dynamically. When the RDF changes, so does the XUL document.
Enough of concepts; start by creating a mozsql chrome package [Hack #86], including modifying
installed-chrome.txt, and create the new
package's standard contents.rdf
file. We'll use a straightforward directory
structure, not a JAR file. There's no extensions,
overlays, themes, locales, or skins; we just want the
chrome://mozsql URL to be working so that our XUL
code can run in a fully secure environment.
Here is the XUL document we will use to create
and then render the RDF returned by our PHP script. This goes inside
the mozsql chrome package that you need to create
to run XUL content as chrome. Call it
mozsql.xul, and put it in the
content subdirectory of the package:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://mozsql/content/global.css" type="text/css"?>
<page id="MozSQL"
xmlns="">
<script type="application/x-javascript" src="chrome://mozsql/content/
mozsql.js"/>
<description id="lblTitle" value="MozSQL :: A Firefox, PHP and MySQL
Hack"/>
<hbox>
<textbox id="tbQueryString" multiline="true" value="SELECT * from USER"/>
<vbox>
<button id="cmdQuery" label="Query" tooltiptext="Execute SQL Query"
oncommand="doQuery( );"/>
</vbox>
</hbox>
<vbox id="vbResults" datasources="rdf:null" ref="urn:mozsql">
The next bit of code, which immediately follows the preceding set,
deals with the XUL template. Only a part of the document is dynamic;
the remainder (above) can be static:
<template>
<rule>
<conditions>
<content uri="?uri"/>
<member container="?uri" child="?row"/>
<triple subject="?row"
predicate=""
object="?value"/>
</conditions>
<action>
<hbox col="?value" uri="?row" class="hbCell">
<label value="?value" crop="end"/>
</hbox>
</action>
</rule>
</template>
</vbox>
</page>
The conditions tag looks for the RDF statements
that match the values we're interested in. The
action tag is the XUL produced when our RDF
statement matches the condition.
We've also created some pretty CSS style information
for this document. It is decorative, not functional. Call it
global.css and put it next to the
mozsql.xul (it's not a theme or
skin):
@namespace url("");
#MozSQL {
background-color: -moz-Dialog;
color: -moz-DialogText;
font: message-box;
padding: 30px;
}
#lblTitle {
font-size: 150%;
padding-bottom: 20px;
}
#tbQueryString {
width: 500px;
height: 75px;
}
#cmdQuery {
height: 30px;
width: 75px;
}
.hbCell > label {
border-right: 1px solid #999999;
width: 75px;
padding: 3px;
}
vbox hbox[id^="rdf"] > label {
max-width: 15px;
}
vbox > hbox[col="0"] {
margin-top: 20px;
background-color: #E4E4E4;
border-bottom: 1px solid #999999;
font-weight: bold;
}
And finally, here's the included script that adds a
datasource to the template and fills it with data from the server.
Call it mozsql.js and put it in the same folder
as the other files:
function doQuery( ) {
//the template root
var dsElem = document.getElementById( "vbResults" );
// the HTTP GET request
var tbQuery = document.getElementById( "tbQueryString" );
var dsURL = "" +tbQuery.value;
// Quick hack to prevent composites, comment out to aggregate results
dsElem.setAttribute( "datasources", dsURL );
// Create, Init and add a CompositeDatasource to the dsElem
var cd = "@mozilla.org/rdf/datasource;1?name=composite-datasource";
var dsCom = Components.classes[cd].createInstance( );
var dsItem = dsCom.QueryInterface(
Components.interfaces.nsIRDFCompositeDataSource );
dsElem.database.AddDataSource( dsItem );
// Now get the RDF service
var = rs "@mozilla.org/rdf/rdf--service;1";
var rdfSvc = Components.classes[rs].getService( );
var rdfItem = rdfSvc.QueryInterface( Components.interfaces.nslRDFService );
// Run the HTTP GET request and add the server-supplied response data
var ds = rdfItem.GetDataSource( dsURL );
dsItem.AddDataSource( ds );
}
When the button is clicked, the tbQueryString
string is retrieved from the text box and appended to our remote URL
under the HTTP GET variable
query. Next, we get the element that holds the
template root (the <vbox id="vbResults">
element) and add the remote URL to it.
The remainder of the code is the RDF content generated by the server.
We use the following PHP script to create an instance of an RDF
datasource, add it to our <vbox> element,
and then call the RDF service to handle this and call
GetdataSource( dsURL ); to retrieve the remote
document from the PHP script. This script is stored on the server (change
this to suit yourself) in the file
MozSQL/mozsql.php:
<?php
define( 'HOSTNAME', 'localhost' );
define( 'DATABASE', 'mysql' );
// Mozilla expects RDF to be returned as XML
header( 'Content-Type: application/xml' );
if ( !isset( $_GET ["query"] ) )
exit;
$query = addslashes( $_GET ['query'] );
$username = 'username';
$password = 'password';
@ $conn = mysql_pconnect(HOSTNAME, $username, $password);
if ( !$conn ) {
exit;
}
mysql_select_db( DATABASE, $conn );
$results = mysql_query( $query ) or die( mysql_error( ) );
if ( !$results || mysql_num_rows( $results ) < 1 )
exit;
// Write out the RDF preamble
echo "<?xml version=\"1.0\"?>\n".
"<rdf:RDF xmlns:rdf=\"\""
." xmlns:sql=\"\">\n".
"<rdf:Seq rdf:about=\"urn:mozsql\">\n".
"<rdf:li>\n";
$row = mysql_fetch_array( $results, MYSQL_ASSOC );
$row_keys = array_keys( $row );
$row_count = mysql_num_rows( $results );
$col_count = count( $row_keys );
mysql_data_seek( $results, 0 ); // Reset results var
for( $i = 0; $i < $row_count; $i++ ) { // Iterate over each row
$row = mysql_fetch_array( $results );
echo "<rdf:Seq sql:value=\"" .$i ."\">\n";
for( $j = 0; $j < $col_count; $j++ ) { // Iterate over each column in row
echo "<rdf:li rdf:resource=\"urn:row" .$i .":col" .$j ."\"/>\n";
}
echo "</rdf:Seq>\n";
}
echo "</rdf:li>\n</rdf:Seq>\n";
mysql_data_seek( $results, 0 );
// Write out Column headers (keys) first
for( $j = 0; $j < $col_count; $j++ ) {
echo "<rdf:Description rdf:about=\"urn:row0:col" .$j
."\" sql:value=\"" .$row_keys[ $j ] ."\"/>\n";
}
for( $i = 0; $i < $row_count; $i++ ) { // Write remainder items out
$row = mysql_fetch_array( $results );
for( $j = 0; $j < $col_count; $j++ ) {
echo "<rdf:Description rdf:about=\"urn:row"
.$i .":col" .$j ."\" sql:value=\"" .$row[ $j ] ."\"/>\n";
}
}
echo "</rdf:RDF>"; // Close root RDF element
mysql_free_result( $results );
?>
You, of course, will need to set your own
host, database,
username, and
password. Finally, here is an example of
the RDF we expect the PHP script to produce:
<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="
xmlns:
<rdf:Seq rdf:
<rdf:li>
<!-- This is called an 'anonymous resource',
as it has no explicit rdf:uri -->
<rdf:Seq sql:
<!-- This ListItem points to the item with the same URI,
this is called an 'assertion' or 'arc' -->
<rdf:li rdf:
<rdf:li rdf:
</rdf:Seq>
<!-- Next row of data -->
<rdf:Seq sql:
<rdf:li rdf:
<rdf:li rdf:
</rdf:Seq>
</rdf:li>
</rdf:Seq>
<!-- These predicates hold the actual data (rdf object) -->
<rdf:Description rdf:
<rdf:Description rdf:
<rdf:Description rdf:
<rdf:Description rdf:
</rdf:RDF>
This is a rough-and-ready example of what you can achieve by
combining XUL and other web technologies alongside remote RDF. With
the addition of other XUL elements, such as a drop-down list to
select databases and other text boxes for usernames and passwords, it
doesn't take much imagination to see that this
isn't far off from a Mozilla-based MySQL frontend
management utility.
One of the coolest things about
RDF
is a feature called aggregation, where multiple
RDF sources are combined as if they were one. Comment out the bolded
line in the previous JavaScript lists and see what happens; XUL
templates can do operations similar to SQL's
JOIN or UNION. Imagine now,
instead of adding just a single remote URL, we add another, but this
time to a different host, perhaps a Windows server running Microsoft
SQL. Now, without that bold line, the remote data from these two
hosts is aggregated, so we can effectively query and combine data
from both hosts in real time! The cost of proprietary software to
achieve this type of solution can leave the bank manager running for
cover.
Neil Stans | http://codeidol.com/community/internet/connect-sql-to-xul/15507/ | CC-MAIN-2018-39 | refinedweb | 1,460 | 54.93 |
Red Hat Bugzilla – Bug 124329
(ACPI) kernel panic at start of installation process
Last modified: 2007-11-30 17:10:43 EST
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4.1)
Gecko/20031114
Description of problem:
After selecting graphic or text install, the kernel is loaded and
decompressed. As soon as the decompressed kernel is started, it
panics with the message "Attempted to kill init!".
I've tried to limit memory with mem=128M (my system has 512M), I've
tried noprobe, and the problem persists.
The system is a Gigabyte GA-7VRXP with DVD-ROM, CDRW-burner, 80GBhd,
512MB RAM, and an Athlon.
An older system I tried to install on (an old Pentium) also failed
this way.
Fedora Core 1 has successfully been installed on both platforms that
paniced while attempting to install Fedora Core 2.
Version-Release number of selected component (if applicable):
How reproducible:
Always
Steps to Reproduce:
1. Turn on machine
2. Insert FC2 disc 1
3. Select graphic or text install
Actual Results: Kernel panic.
Expected Results: Installation to proceed normally.
Additional info:
EIP is at acpi_ps_parse_aml+0xb2/0x1a4
eax: 00000000 ebx: c147cc00 ecx: c02b38c9 edx: 00000d60
esi: c147cc00 edi: c147bf44 ebp: 00000007 esp: dffd5f60
ds: 007b es: 007b ss: 0068
Process swapper (pid: 1, threadinfo=dffd5000 task=dfd47630)
Stack: 00000000 00000000 c147cc00 dffe0284 00000001 c01aa473 dffe0144
dffe0144
c037e634 00000000 c01aa492 dffe0144 c01a84bd dffe0144 00000000
00000000
c01a852e 00000000 00000000 00000000 c01a85e2 c01ae62d 00000001
000fc0d0
Call Trace:
[<c01aa473>] acpi_ns_one_complete_parse+0x6b/0x7b
[<c01aa492>] acpi_ns_parse_table+0xf/0x29
[<c01a84bd>] acpi_ns_load_table+0x6d/0x8f
[<c01a852e>] acpi_ns_load_table_by_type+0x4f/0xea
[<c01a85e2>] acpi_ns_load_namespace+0x19/0x34
[<c01ae62d>] acpi_load_tables+0xd9/0x139
[<c032ccc5>] acpi_bus_init+0x26/0x11b
[<c032ce1c>] acpi_init+0x62/0xb4
[: 82 78 10 00 75 0e 80 48 09 08 8b 83 ac 01 00 00 c6 40 1c 01
<0>Kernel panic: Attempted to kill init!
Created attachment 100716 [details]
diff file beteen Fedora Core 2 kernel config and Debian 2.6.5 claimed to work
Hello,
I got exactly the same error on an Asus M2400N laptop.
I succeeded booting and installing Fedora Core 2 by passing
acpi=ht parameter to kernel.
Unfortunately, since acpi is disabled, the sound card and pcmcia
does not work.
Here is the relevant parts of /var/log/messages:
May 29 11:20:34 port107-pp kernel: Kernel command line: ro
root=LABEL=/ acpi=ht rhgb quiet
...
May 29 11:20:36 port107-pp kernel: ACPI: Subsystem revision 20040326
May 29 11:20:36 port107-pp kernel: ACPI: Interpreter disabled.
May 29 11:20:36 port107-pp kernel: Linux Plug and Play Support v0.97
(c) Adam Belay
May 29 11:20:37 port107-pp kernel: usbcore: registered new driver usbfs
May 29 11:20:37 port107-pp kernel: usbcore: registered new driver hub
May 29 11:20:37 port107-pp kernel: ACPI: ACPI tables contain no PCI
IRQ routing entries
May 29 11:20:37 port107-pp kernel: PCI: Invalid ACPI-PCI IRQ routing table
May 29 11:20:37 port107-pp kernel: PCI: Probing PCI hardware
May 29 11:20:37 port107-pp kernel: PCI: Probing PCI hardware (bus 00)
May 29 11:20:37 port107-pp kernel: PCI: Ignoring BAR0-3 of IDE
controller 0000:00:1f.1
May 29 11:20:37 port107-pp kernel: Transparent bridge - 0000:00:1e.0
May 29 11:20:37 port107-pp kernel: PCI: Using IRQ router default
[8086/24cc] at 0000:00:1f.0
May 29 11:20:37 port107-pp kernel: PCI: IRQ 0 for device 0000:00:1f.1
doesn't match PIRQ mask - try pci=usepirqmask
May 29 11:20:37 port107-pp kernel: PCI: IRQ 0 for device 0000:00:1f.5
doesn't match PIRQ mask - try pci=usepirqmask
May 29 11:20:37 port107-pp kernel: PCI: IRQ 0 for device 0000:00:1f.6
doesn't match PIRQ mask - try pci=usepirqmask
May 29 11:20:37 port107-pp kernel: PCI: IRQ 0 for device 0000:01:03.0
doesn't match PIRQ mask - try pci=usepirqmask
May 29 11:20:37 port107-pp kernel: PCI: IRQ 0 for device 0000:01:03.1
doesn't match PIRQ mask - try pci=usepirqmask
[snip]
May 29 11:20:38 port107-pp kernel: PCI: IRQ 0 for device 0000:00:1f.6
doesn't match PIRQ mask - try pci=usepirqmask
May 29 11:20:38 port107-pp kernel: PCI: No IRQ known for interrupt pin
B of device 0000:00:1f.6. Please try using pci=biosi
rq.
...
I did try various combinations of kernel parameters with no success
(no sound) such as:
nolapic
nolapic pci=noacpi
nolapic pci=biosirq
nolapic pci=usepirqmask
All of them gave me the kernel panic.
I can use my Fedora only with acpi=ht ( or acpi=off) ...
Please note that my colleague succeeded with a mandrake 10.0 (kernel
2.6.3) community by using nolapic pci=usepirqmask. He has sound !!!
And there are reports on Google of successful Debian install with
Kernel 2.6.5 on this laptop such as:
Finally I should say that I succeeded to have sound with RedHat 9 on
this laptop by customizing/compiling a 2.4.22 kernel. But the harddisk
was extremely slow (hdparm gaves 3Mb/s), that's why I tried Fedora
core 2... So far I am disappointed.
There should be something missing or incorrect in the kernel's
config files for Fedora Core 2.. But what ?
I am quite willing to help
Created attachment 100717 [details]
the config file of Debian with 2.6.5 claimed to work
Here is the config file of the debian distro claimed to work by
I have the same issue as Msquared.
I also get this with the FC2 recovery CD.
I am running dual XP and FC1.
My system :
Intel Celeron 2.6ghz
Maxtor 91366U4 (12Gb) IDE
ST360015A (60Gb) IDE
NVIDIA FX5200
Workaround: adding the parameter "acpi=off" to the kernel while
installing allowed me to successfully install Fedora Core 2. I also
had to add "acpi=off" to the kernel when booting in order to
successfully boot Fedora Core 2. Thanks to Patrick for the hints.
I tried :
acpi=off
acpi=ht
pci=noacpi
still the same Kernel panic.
However,
my actual info is different to yours:
Process swapper (pid: 1, threadinfo=f7d90000 task=f7d49630)
Stack: 0000002b 00000000 c015a352 c02d4c80 00000000 0000002b c1997f84
c02d4c80
c17fd9e0 c014f6d4 0000002b c016e2dc fffffff4 c199aa18 0000002c
c199a980
c1997f84 c199b580 c1997fb0 00000000 c016e31d c199b580 c199b580
c1997f91
Call Trace:
[<c015a352>] simple_prepare_write+0x31/0x94
[<c014f6d4>] init_symlink+0x4e/0x10e
[<c016e2dc>] init_symlink+0x0/0xd
[<c016e31d>] sysfs_symlink+0x34/0x49
[<c016e49a>] sysfs_create_link+0xed/0x117
[<c01dbbc7>] bus_match+0x3f051>] pci_create_newid_file+0x15/0x1a
[<c0199315>] pci_register_driver+0x4b/0x67
[<c032f0fb>] agp_intel_init+0x20/0x27
[: 0f 0b 2a 00 78 90 29 c0 2b 0d cc 90 37 c0 c1 f9 05 c1 e1 0c
<0>Kernel panic: Attempted to kill init!
Hello again,
I solved it from infos in bug # 121760.
I applied the patch by luming (comment #18) to linux/drivers/acpi/dsopcode.c ( 3
lines to comment out), and recompiled the kernel & modules...
Now my laptop boots with 2.6.5-1.358custom
without any acpi=xx parameter AND acpi is enabled OK.
No more kernel panic (execpt of course from FC2 CD1 or image on usb disk).
The directory /proc/acpi is populated and my sound card Intel 82801DB
WORKS :-))
Just have to modify kernel-ntfs and ipw2100 rpms to install in
/lib/modules/2.6.5-1.358custom instead of /lib/modules/2.6.5-1.358
This may not help Steven since he do not have the same error code .
Thanks and cheers ;-)
Created attachment 100737 [details]
Successful /var/log/messages
What I was expecting for a long time. Cheers to FC2 ;-)
Thank-you Patrick for proving this is a duplicate of bug 121760.
Steven has a different (non-ACPI) failure and should open a different bug.
closing this bug as a duplicate of bug 121760...
*** This bug has been marked as a duplicate of 121760 ***
Changed to 'CLOSED' state since 'RESOLVED' has been deprecated. | https://bugzilla.redhat.com/show_bug.cgi?id=124329 | CC-MAIN-2017-13 | refinedweb | 1,343 | 62.98 |
Performs character I/O for a block device using a uio structure.
#include <sys/types.h> #include <sys/errno.h> #include <sys/buf.h> #include <sys/uio.h>
int uphysio (uiop, rw, buf_cnt, devno, strat, mincnt, minparms) struct uio *uiop; int rw; uint buf_cnt; dev_t devno; int (*strat)( ); int (*mincnt)( ); void *minparms;
The uphysio kernel service performs character I/O for a block device. The uphysio service attempts to send to the specified strategy routine the number of buf headers specified by the buf_cnt parameter. These buf structures are constructed with data from the uio structure specified by the uiop parameter.
The uphysio service initially transfers data area descriptions from each iovec element found in the uio structure into individual buf headers. These headers are later sent to the strategy routine. The uphysio kernel service tries to process as many data areas as the number of buf headers permits. It then invokes the strategy routine with the list of buf headers.
The routine specified by the mincnt parameter is called before the buf header, built from an iovec element, is added to the list of buf headers to be sent to the strategy routine. The mincnt parameter is passed a pointer to the buf header along with the minparms pointer. This arrangement allows the mincnt parameter to tailor the length of the data transfer described by the buf header as required by the device performing the I/O. The mincnt parameter can also optionally modify certain device-dependent fields in the buf header.
When the mincnt parameter returns with no error, an attempt is made to pin the data buffer described by the buf header. If the pin operation fails due to insufficient memory, the data area described by the buf header is reduced by half. The buf header is again passed to the mincnt parameter for modification before trying to pin the reduced data area.
This process of downsizing the transfer specified by the buf header is repeated until one of the three following conditions occurs:
When insufficient memory indicates a failed pin operation, the number of buf headers used for the remainder of the operation is reduced to 1. This is because trying to pin multiple data areas simultaneously under these conditions is not desirable.
If the user has not already obtained cross-memory descriptors, further processing is required. (The uio_segflg field in the uio structure indicates whether the user has already initialized the cross-memory descriptors. The usr/include/sys/uio.h file contains information on possible values for this flag.)
When the data area described by the buf header has been successfully pinned, the uphysio service verifies user access authority for the data area. It also obtains a cross-memory descriptor to allow the device driver interrupt handler limited access to the data area.
After the uphysio kernel service obtains a cross-memory descriptor to allow the device driver interrupt handler limited access to the data area, the buf header is then put on a list of buf headers to be sent to the strategy routine specified by the strat parameter.
The strategy routine specified by the strat parameter is called with the list of buf headers when:
The buf headers in the list are chained together using the av_back and av_forw fields before they are sent to the strategy routine.
When all available buf headers have been sent to the strategy routine, the uphysio service waits for one or more of the buf headers to be marked complete. The IODONE handler is used to wake up the uphysio service when it is waiting for completed buf headers from the strategy routine.
When the uphysio service is notified of a completed buf header, the associated data buffer is unpinned and the cross-memory descriptor is freed. (However, the cross-memory descriptor is freed only if the user had not already obtained it.) An error is detected on the data transfer under the following conditions:
When an error is detected by the uphysio service, no new buf headers are sent to the strategy routine.
The uphysio service waits for any buf headers already sent to the strategy routine to be completed and then returns an error code to the caller. If no errors are detected, the buf header and any other completed buf headers are again used to send more data transfer requests to the strategy routine as they become available. This process continues until all data described in the uio structure has been transferred or until an error has been detected.
The uphysio service returns to the caller when:
The uphysio service also returns an error code to the caller if an error is detected.
When it detects an error, the uphysio kernel service reports the error that was detected closest to the start of the data area described by the uio structure. No additional buf headers are sent to the strategy routine. The uphysio kernel service waits for all buf headers sent to the strategy routine to be marked complete.
However, additional buf headers may have been sent to the strategy routine between these two events:
When errors occur, various fields in the returned uio structure may or may not reflect the error. The uio_iov and uio_iovcnt fields are not updated and contain their original values.
The uio_resid and uio_offset fields in the returned uio structure indicate the number of bytes transferred by the strategy routine according to the sum of all (the b_bcount field minus the b_resid fields) fields in the buf headers processed by the strategy routine. These headers include the buf header indicating the error nearest the start of the data area described by the original uio structure. Any data counts in buf headers completed after the detection of the error are not reflected in the returned uio structure.
The uphysio kernel service can be called from the process environment only.
The uphysio kernel service is part of Base Operating System (BOS) Runtime.
The ddstrategy device driver entry point.
The geterror kernel service, iodone kernel service.
The mincnt routine.
The buf structure, uio structure. | http://ps-2.kev009.com/tl/techlib/manuals/adoclib/libs/ktechrf1/uphysiok.htm | CC-MAIN-2022-27 | refinedweb | 1,012 | 51.38 |
Introduction to Python Web Development
Python Web Development can be defined as a series of processes followed for the creation of a web based application. Python is one of the well-known object oriented programming language used for the application development of a web based application or a website. Coding in python is pretty straightforward, that makes it easy to learn and practice even for an inexperienced person. A few notable features of python web development are pre-defined functions and methods for almost all frequently used operations, manipulation of data is flexible using the data related functions like list, collection and dictionaries, the built-in library is complete to fulfil the integration functions, etc.
Python Programming Language
Python is used everywhere. To be more accurate, there is hardly any programmer who does not know the importance of python web developement. Google uses it in maintaining its own database. Hard coders use it in combination with Linux since its extremely compatible with Linux and you can even cross-create a program written half in bash and half in python. Besides creating databases, it is used for creating high-end games, for creating CGI Effects in Movies and Animations.
If you think that is it, it’s not. It’s even used for creating Gnome applications, for automated tasks in UNIX and Linux. The reason for Python web development being so explicitly used is because it is extremely User-friendly. It’s also easy for a beginner to understand a code written in python because it has a specific format in which it needs to be written.
Unlike Ruby or Perl, python needs to be coded in a proper way. If you have any experience in ruby or Perl, then you know it can be a mess since it’s an extremely forgiving language. But it’s not the same in case of Python. Python needs to be indented in a proper way. That is the reason all Perl web applications are being replaced by python nowadays.
Most likely, by the end of this decade, Perl will be completely replaced by python. Here is an example I have written to calculate compound interest in both Python and Perl. Mess yourself up and check which one do you find easier.
Calculating Compound Interest in Python
So, before I proceed, Compound interest is that type of interest that accrues over a period of time on the initial amount and the accumulated interest of a principal deposited. In Compound interest, interest grows faster than Simple Interest. The following is the basic formula for calculating Compound Interest:
Compound Interest = Principal (1+ Interest/100)^Period
In the following code:
P = principal
R = Rate of Interest
T = Time duration
>>>print ': Compound Interest :'
def Compound_Interest():
amount = input('Enter the principal amount')
amount = float(amount)
rate = input('Enter rate percentage')
x = input('Press \'1\' for duration of time in days \n\'2\' for time in months and \n\'3\' for time in years\n')
if(x == 1):
time = input('Enter number of days')
time = time /(12*30)
elif(x == 2):
time = input('Enter number of months')
time = time / 12
else:
time = input(' Enter number of years')
total_amount = (amount * (1 + (float(rate)/100))**time)
print('\nTotal Amount is %f' %total_amount)
compound_interest = total_amount - amount
print('\nCompound Interest = %f' %compound_interest)
print('\nTotal amount = %f' %total_amount)
Perl Programming Codes
Perl is for high performance, high-level decoding and dynamic programming language. Let us look at the codes below.
#!/usr/bin/perl
$principal =$ARGV[0];
$percent=$ARGV[1];
$rate=$ARGV[1]/100;
$time=$ARGV[2];
$futurevalue=$principal*(1+$rate)**$time;
print “The principal amount is $principal\n”;
print “The annual interest rate is $percent percent\n”;
print “The time duration of the investment is $time\n\n”;
print “The future value of the investment is $futurevalue\n\n”;
So, it may seem Perl code is smaller than python, but python is much easier to understand. And there are other ways in which it can be written in a much more compact way. Thus Python exceeds Perl in every other way.
Now you may be thinking, maybe I have gone off-topic just to describe the importance of python. Nope, I didn’t. Previously Perl was the most used language, even on the web. But today, it has been replaced by Python and I just wanted to convey my message about the same.
And now, it’s about time that we see how python has squeezed the web in the past One Decade.
Scripting Language – Python Web Development
Now coming on to this part, let’s see how python made its position to the top. Python was recommended as the easiest and the most popular scripting language by Developers in 2009 and 2011. There were multiple other competitions out of which the toughest were given by JavaScript and C.
JavaScript has a good grounding in basic programming concepts and its simplicity. Learning JavaScript can make you understand the most basic concepts of any programming language and how it needs to work. It’s also like Perl and Ruby is a forgiving language and has easier to use Syntax.
Besides JavaScript, we have C which was also cited as a good competitor for Python, the reason being it as a rock-solid foundation in programming. It is old and not obsolete. It is still used in a lot of places. So, in short, if you learn C as your beginning language, then learning any other language will be a piece of cake. But that’s the easiest part.
The hardest part is using C as a beginner language. If you are a noob, 90% of the C stuff will go over and above your head. And, by the time you understand the basics in C, the other person will already have learned python, ruby, and Perl. Yeah! I am not exaggerating. It is the truth. And this is how Python came up to the top.
Features of Python Programming
So now we know, how python made its place to the top position in developing web applications. Let’s take a deeper look at that. Following are some of the most important features that make python more flexible and sustainable for the long term in real day life:
1. Swapping Variables
> a, b = 1, 2
>>> a, b = b, a
>>>a, b
(2, 1)
2. Slicing and Negative Indexing
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[-4: -2]
[7, 8]
3. Naming Slices
>>> a = [0, 1, 2, 3, 4, 5]
>>> LASTTHREE = slice(-3, None)
>>> LASTTHREE
slice(-3, None, None)
>>> a[LASTTHREE] [3, 4, 5]
4. Zip and Iterators
>>>)]
5. Generator Expressions
>>> g = (x ** 2 for x in xrange(10))
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> sum(x ** 3 for x in xrange(10))
2025
>>> sum(x ** 3 for x in xrange(10) if x % 3 == 1)
408
6. Queue with Maximum Lengths
>>> last_three = collections.deque(maxlen=3)
>>> for i in xrange(10):
... last_three.append(i)
... print ', '.join(str(x) for x in last_three)
...
0
0, 1
0, 1, 2
1, 2, 3
2, 3, 4
3, 4, 5
4, 5, 6
5, 6, 7
6, 7, 8
7, 8, 9
Now, these are some of the most basic but important knows to stuff which you would be using most of the timing to make your programs efficient and compact. Besides, if you are trying to make python work with the web, then here are some important point you might consider gathering information on:
1. Setting up CGI (Common Gateway Interface) on your own Server.
2. Learning the difference between mod_python and mod_php.
3. Learning Libraries which help integrate Python and HTML and creating templates on that basis.
4. Learning Django Framework or TurboGears.
Conclusion
So, above are my experiences shared with you guys in detail. And trust me when I say Django is the best and widely used. If you know Django, then I don’t think there would be a need to learn TurboGears, the reason being Django covers every aspect of TurboGears and might probably even replace Turbo in a few years.
Recommended Articles
Here are some articles that will help you to get more detail about the Python Squeezes the Web so just go through the link. | https://www.educba.com/python-web-development/?source=leftnav | CC-MAIN-2021-04 | refinedweb | 1,384 | 61.36 |
Implementation status: partially implemented
Synopsis
#include <unistd.h>
pid_t fork(void);
Description
The
fork() function creates a new process. The new process (child process) is an exact copy of the calling process (parent process) except some exceptions.
Arguments:
None.
The differences between child and parent process are as follows:
- The child process has a unique process ID.
- The child process ID also does not match any active process. Each open directory stream in the child process shares directory stream positioning with the corresponding directory stream of the parent.
- The child process has its own copy of the parent's message catalogue descriptors.
- The child process values of
tms_utime,
tms_stime,
tms_cutime, and
tms_cstimeis set to
0.
- The time left until an alarm clock signal is reset to zero, and the alarm, if any, is cancelled.
- All
semadjvalues are cleared.
- File locks set by the parent process are not inherited by the child process.
- The set of signals pending for the child process is initialized to the empty set.
- Interval timers are reset in the child process.
- Any semaphores that are open in the parent process are also opened in the child process.
- The child process does not inherit any address space memory locks established by the parent process via calls to
mlockall()or
mlock().
- Memory mappings created in the parent are retained in the child process.
MAP_PRIVATEmappings inherited from the parent are also
MAP_PRIVATEmappings in the child, and any modifications to the data in these mappings made by the parent prior to calling
fork()are visible to the child. Any modifications to the data in
MAP_PRIVATEmappings made by the parent after
fork()returns is visible only to the parent. Modifications to the data in
MAP_PRIVATEmappings made by the child are visible only to the child.
- For the
SCHED_FIFOand
SCHED_RRscheduling policies, the child process inherits the policy and priority settings of the parent process during a
fork()function.
- Per-process timers created by the parent are not inherited by the child process.
- The child process has its own copy of the message queue descriptors of the parent. Each of the message descriptors of the child refers to the same open message queue description as the corresponding message descriptor of the parent.
- No asynchronous input or asynchronous output operations are inherited by the child process. Any use of asynchronous control blocks created by the parent produces undefined behaviour.
-functions is called.
- If the
Traceoption and the
Trace Inheritoption are both supported:
If the calling process was being traced in a trace stream that had its inheritance policy set to
POSIX_TRACE_INHERITED, the child process is traced into that trace stream, and the child process inherits the parent's mapping of trace event names to trace event type identifiers. If the trace stream in which the calling process was being traced had its inheritance policy set to
POSIX_TRACE_CLOSE_FOR_CHILD, the child process is not traced into that trace stream. The inheritance policy is set by a call to the
posix_trace_attr_setinherited()function.
- If the
Traceoption is supported, but the
Trace Inheritoption is not supported the child process is not traced into any of the trace streams of its parent process.
- If the
Traceoption is supported, the child process of a trace controller process does not control the trace streams controlled by its parent process.
- The initial value of the CPU-time clock of the child process is set to zero.
- The initial value of the CPU-time clock of the single thread of the child process is set to zero.
After
fork(), both the parent and the child processes are capable of executing independently before either one terminates.
Return value
Upon successful completion,
fork() returns
0 to the child process and returns the process ID of the child process to the parent process. Both processes continue to execute from the
fork() function.
Otherwise,
-1 is returned to the parent process, no child process is created, and
errno is set to indicate the error.
Errors
[
EAGAIN] The system lacked the necessary resources to create another process, or the system-imposed limit on the total number of processes under execution system-wide or by a single user {
CHILD_MAX} would be exceeded.
[
ENOMEM] Insufficient storage space is available.
Implementation tasks
- Implement error handling. | https://phoenix-rtos.com/documentation/libphoenix/posix/fork | CC-MAIN-2020-29 | refinedweb | 703 | 62.48 |
zipapp — Manage executable Python zip archives¶
New in version 3.5.
Source code: Lib/zipapp.py
This module provides tools to manage the creation of zip files containing Python code, which can be executed directly by the Python interpreter. The module provides both a Command-Line Interface and a Python API.
Basic Example¶
The following example shows how the Command-Line Interface
can be used to create an executable archive from a directory containing
Python code. When run, the archive will execute the
main function from
the module
myapp in the archive.
$ python -m zipapp myapp -m "myapp:main" $ python myapp.pyz <output from myapp>
Command-Line Interface¶
When called as a program from the command line, the following form is used:
$ python -m zipapp source [options]
If source is a directory, this will create an archive from the contents of source. If source is a file, it should be an archive, and it will be copied to the target archive (or the contents of its shebang line will be displayed if the –info option is specified).
The following options are understood:
-o
<output>
,
--output
=<output>¶
Write the output to a file named output. If this option is not specified, the output filename will be the same as the input source, with the extension
.pyzadded. If an explicit filename is given, it is used as is (so a
.pyzextension should be included if required).
An output filename must be specified if the source is an archive (and in that case, output must not be the same as source).
-p
<interpreter>
,
--python
=<interpreter>¶
Add a
#!line to the archive specifying interpreter as the command to run. Also, on POSIX, make the archive executable. The default is to write no
#!line, and not make the file executable.
-m
<mainfn>
,
--main
=<mainfn>¶
Write a
__main__.pyfile to the archive that executes mainfn. The mainfn argument should have the form “pkg.mod:fn”, where “pkg.mod” is a package/module in the archive, and “fn” is a callable in the given module. The
__main__.pyfile will execute that callable.
--maincannot be specified when copying an archive.
-c
,
--compress
¶
Compress files with the deflate method, reducing the size of the output file. By default, files are stored uncompressed in the archive.
--compresshas no effect when copying an archive.
New in version 3.7.
--info
¶
Display the interpreter embedded in the archive, for diagnostic purposes. In this case, any other options are ignored and SOURCE must be an archive, not a directory.
Python API¶
The module defines two convenience functions:
zipapp.
create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False)¶
Create an application archive from source. The source can be any of the following:
The name of a directory, or a path-like object referring to a directory, in which case a new application archive will be created from the content of that directory.
The name of an existing application archive file, or a path-like object referring to such a file, in which case the file is copied to the target (modifying it to reflect the value given for the interpreter argument). The file name should include the
.pyzextension,, or a path-like object,extension added.
The interpreter argument specifies the name of the Python interpreter with which the archive will be executed. It is written as a “shebang” line at the start of the archive. On POSfile.file, as otherwise the resulting archive would not be executable.
The optional filter argument specifies a callback function that is passed a Path object representing the path to the file being added (relative to the source directory). It should return
Trueif the file is to be added.
The optional compressed argument determines whether files are compressed. If set to
True, files in the archive are compressed with the deflate method; otherwise, files are stored uncompressed. This argument has no effect when copying an existing archive.
If a file object is specified for source or target, it is the caller’s responsibility to close it after calling create_archive.
When copying an existing archive, file objects supplied only need
readand
readline, or
writemethods. When creating an archive from a directory, if the target is a file object it will be passed to the
zipfile.ZipFileclass, and must supply the methods needed by that class.
New in version 3.7: Added the filter and compressed arguments.
Examples¶
Pack up a directory into an archive, and run it.
$ python -m zipapp myapp $ python myapp.pyz <output from myapp>
The same can be done using the
create_archive() function:
>>> import zipapp >>> zipapp.create_archive('myapp', 'myapp.pyz')
To make the application directly executable on POSIX, specify an interpreter to use.
$ python -m zipapp myapp -p "/usr/bin/env python" $ ./myapp.pyz <output from myapp>
To replace the shebang line on an existing archive, create a modified archive
using the
create_archive() function:
>>> import zipapp >>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')
To update the file in place, do the replacement in memory using a
BytesIO
object, and then overwrite the source afterwards. Note that there is a risk
when overwriting a file in place that an error will result in the loss of
the original file. This code does not protect against such errors, but
production code should do so. Also, this method will only work if the archive
fits in memory:
>>> import zipapp >>> import io >>> temp = io.BytesIO() >>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2') >>> with open('myapp.pyz', 'wb') as f: >>> f.write(temp.getvalue())
Specifying the Interpreter¶
Note that if you specify an interpreter and then distribute your application
archive, you need to ensure that the interpreter used is portable. The Python
launcher for Windows supports most common forms of POSIX
#! line, but there
are other issues to consider:
If you use “/usr/bin/env python” (or other forms of the “python” command, such as “/usr/bin/python”), you need to consider that your users may have either Python 2 or Python 3 as their default, and write your code to work under both versions.
If you use an explicit version, for example “/usr/bin/env python3” your application will not work for users who do not have that version. (This may be what you want if you have not made your code Python 2 compatible).
There is no way to say “python X.Y or later”, so be careful of using an exact version like “/usr/bin/env python3.4” as you will need to change your shebang line for users of Python 3.5, for example.
Typically, you should use an “/usr/bin/env python2” or “/usr/bin/env python3”, depending on whether your code is written for Python 2 or 3.
Creating Standalone Applications with zipapp¶
Using the
zipapp module, it is possible to create self-contained Python
programs, which can be distributed to end users who only need to have a
suitable version of Python installed on their system. The key to doing this
is to bundle all of the application’s dependencies into the archive, along
with the application code.
The steps to create a standalone archive are as follows:
Create your application in a directory as normal, so you have a
myappdirectory containing a
__main__.pyfile, and any supporting application code.
Install all of your application’s dependencies into the
myappdirectory, using pip:
$ python -m pip install -r requirements.txt --target myapp
(this assumes you have your project requirements in a
requirements.txtfile - if not, you can just list the dependencies manually on the pip command line).
Optionally, delete the
.dist-infodirectories created by pip in the
myappdirectory. These hold metadata for pip to manage the packages, and as you won’t be making any further use of pip they aren’t required - although it won’t do any harm if you leave them.
Package the application using:
$ python -m zipapp -p "interpreter" myapp
This will produce a standalone executable, which can be run on any machine with the appropriate interpreter available. See Specifying the Interpreter for details. It can be shipped to users as a single file.
On Unix, the
myapp.pyz file is executable as it stands. You can rename the
file to remove the
.pyz extension if you prefer a “plain” command name. On
Windows, the
myapp.pyz[w] file is executable by virtue of the fact that
the Python interpreter registers the
.pyz and
.pyzw file extensions
when installed.
Making a Windows executable¶
On Windows, registration of the
.pyz extension is optional, and
furthermore, there are certain places that don’t recognise registered
extensions “transparently” (the simplest example is that
subprocess.run(['myapp']) won’t find your application - you need to
explicitly specify the extension).
On Windows, therefore, it is often preferable to create an executable from the
zipapp. This is relatively easy, although it does require a C compiler. The
basic approach relies on the fact that zipfiles can have arbitrary data
prepended, and Windows exe files can have arbitrary data appended. So by
creating a suitable launcher and tacking the
.pyz file onto the end of it,
you end up with a single-file executable that runs your application.
A suitable launcher can be as simple as the following:
#define Py_LIMITED_API 1 #include "Python.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #ifdef WINDOWS int WINAPI wWinMain( HINSTANCE hInstance, /* handle to current instance */ HINSTANCE hPrevInstance, /* handle to previous instance */ LPWSTR lpCmdLine, /* pointer to command line */ int nCmdShow /* show state of window */ ) #else int wmain() #endif { wchar_t **myargv = _alloca((__argc + 1) * sizeof(wchar_t*)); myargv[0] = __wargv[0]; memcpy(myargv + 1, __wargv, __argc * sizeof(wchar_t *)); return Py_Main(__argc+1, myargv); }
If you define the
WINDOWS preprocessor symbol, this will generate a
GUI executable, and without it, a console executable.
To compile the executable, you can either just use the standard MSVC command line tools, or you can take advantage of the fact that distutils knows how to compile Python source:
>>> from distutils.ccompiler import new_compiler >>> import distutils.sysconfig >>> import sys >>> import os >>> from pathlib import Path >>> def compile(src): >>> src = Path(src) >>> cc = new_compiler() >>> exe = src.stem >>> cc.add_include_dir(distutils.sysconfig.get_python_inc()) >>> cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs')) >>> # First the CLI executable >>> objs = cc.compile([str(src)]) >>> cc.link_executable(objs, exe) >>> # Now the GUI executable >>> cc.define_macro('WINDOWS') >>> objs = cc.compile([str(src)]) >>> cc.link_executable(objs, exe + 'w') >>> if __name__ == "__main__": >>> compile("zastub.c")
The resulting launcher uses the “Limited ABI”, so it will run unchanged with
any version of Python 3.x. All it needs is for Python (
python3.dll) to be
on the user’s
PATH.
For a fully standalone distribution, you can distribute the launcher with your application appended, bundled with the Python “embedded” distribution. This will run on any PC with the appropriate architecture (32 bit or 64 bit).
Caveats¶
There are some limitations to the process of bundling your application into a single file. In most, if not all, cases they can be addressed without needing major changes to your application.
If your application depends on a package that includes a C extension, that package cannot be run from a zip file (this is an OS limitation, as executable code must be present in the filesystem for the OS loader to load it). In this case, you can exclude that dependency from the zipfile, and either require your users to have it installed, or ship it alongside your zipfile and add code to your
__main__.pyto include the directory containing the unzipped module in
sys.path. In this case, you will need to make sure to ship appropriate binaries for your target architecture(s) (and potentially pick the correct version to add to
sys.pathat runtime, based on the user’s machine).
If you are shipping a Windows executable as described above, you either need to ensure that your users have
python3.dllon their PATH (which is not the default behaviour of the installer) or you should bundle your application with the embedded distribution.
The suggested launcher above uses the Python embedding API. This means that in your application,
sys.executablewill be your application, and not a conventional Python interpreter. Your code and its dependencies need to be prepared for this possibility. For example, if your application uses the
multiprocessingmodule, it will need to call
multiprocessing.set_executable()to let the module know where to find the standard Python interpreter.
The Python Zip Application Archive Format¶
Python has been able to execute zip files which contain a
__main__.py file
since version 2.6. In order to be executed by Python, an application archive
simply has to be a standard zip file containing a
__main__.py file which
will be run as the entry point for the application. As usual for any Python
script, the parent of the script (in this case the zip file) will be placed on
sys.path and thus further modules can be imported from the zip file.
The zip file format allows arbitrary data to be prepended to a zip file. The
zip application format uses this ability to prepend a standard POSIX “shebang”
line to the file (
#!/path/to/interpreter).
Formally, the Python zip application format is therefore:
An optional shebang line, containing the characters
b'#!'followed by an interpreter name, and then a newline (
b'\n') character. The interpreter name can be anything acceptable to the OS “shebang” processing, or the Python launcher on Windows. The interpreter should be encoded in UTF-8 on Windows, and in
sys.getfilesystemencoding()on POSIX.
Standard zipfile data, as generated by the
zipfilemodule. The zipfile content must include a file called
__main__.py(which must be in the “root” of the zipfile - i.e., it cannot be in a subdirectory). The zipfile data can be compressed or uncompressed.
If an application archive has a shebang line, it may have the executable bit set on POSIX systems, to allow it to be executed directly.
There is no requirement that the tools in this module are used to create application archives - the module is a convenience, but archives in the above format created by any means are acceptable to Python. | https://docs.python.org/3/library/zipapp.html | CC-MAIN-2020-34 | refinedweb | 2,349 | 56.66 |
PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Author: Anton Trygub
Tester: Danny Mittal
Editorialist: Nishank Suresh
DIFFICULTY:
Medium-Hard
PREREQUISITES:
Understanding of permutations, a good eye for constructions
PROBLEM:
You have two permutations P and Q of size N. Find a permutation R of size N such that
- The number of inversions of the permutation \left(P_{R_1}, P_{R_2}, \dots, P_{R_N}\right) equals A
- The number of inversions of the permutation \left(Q_{R_1}, Q_{R_2}, \dots, Q_{R_N}\right) equals B
or say that none exist.
EXPLANATION:
First, it can be observed that independent of the choice of R, the set of pairs of indices splits into two equivalence classes:
- One class where each pair contributes either one inversion to both P\circ R and Q\circ R, or does not contribute to either
- The other class where each pair contributes one inversion to P\circ R and none to Q\circ R, or vice versa
This follows from the fact that R flips the contribution to inversions of P of a pair of indices (i, j) if and only if the contribution to Q of this pair is also flipped (which is really just a fancy way of saying that both P and Q are acted on by the same permutation).
Now, suppose we have x pairs of type 1 (i.e contributes the same to both) and y pairs of type 2.
Just this information is enough to tell us whether an answer exists or not.
Claim: Given A and B, a required permutation R exists if and only if the following conditions are satisfied:
- A+B has the same parity as y
- y\leq A+B\leq 2x+y
- -y\leq A-B\leq y
The remainder of the editorial will prove this by constructing such a permutation R.
A slight transformation
Let us perform the transformation (A, B) \to (A+B, A-B) - this will make some costs a bit easier to work with.
In particular:
- A pair of indices of type 1 now contributes either 0 or 2 to A+B, and 0 to A-B.
- A pair of indices of type 2 now contributes 1 to A+B, and either -1 or 1 to A-B.
Notice that this immediately gives us the bounds from the claim above:
- A+B lies between y and 2x+y, and always has the same parity as y.
- A-B lies between -y and y.
Thus the conditions in the above claim are certainly necessary. It remains to be seen that they are sufficient.
It can also be seen that choosing R such that P ends up being the identity permutation minimizes both A+B and A-B.
Why?
Every type 1 pair is sorted in P, and thus contributes 0 to A+B since it must also be sorted in Q. So, A+B equals exactly the number of type 2 pairs, i.e, y. This is the minimum attainable value.
Every type 2 pair contributes -1 to A-B, and type 1 pairs contribute 0 so A-B equals exactly -y. Again, this is the minimum possible.
A similar analysis tells us that when Q is the identity permutation, A+B is minimum but A-B is maximum.
Now, let P be the identity permutation (and Q transformed appropriately). Consider the following process:
for i from 1 to N: while the element to the immediate left of i in Q is greater than i: swap i with the element to its left
Every time this operation performs a swap, A-B increases by exactly 2 because we only swap type 2 pairs.
Why?
This follows from the fact that P was initially sorted and the way our process works.
When we are moving i to the front of Q, note that we never touch indices 1, 2, \dots, i-1, because Q_j = j for those indices.
The nature of our swapping also guarantees that P_i, P_{i+1}, \dots, P_N is sorted, and hence any swap we make turns an inversion into a non-inversion in Q, while turning a non-inversion into an inversion in P - which means we swap a type 2 pair.
Of course, this also means that we don’t swap any type 1 pairs at all - in other words, A+B remains unchanged throughout this process.
So, as long as -y\leq A-B\leq y and A-B has the same parity as y, we will reach a state where A+B = y and A-B is our target value.
Now we do something similar: we perform a sequence of swaps which increases A+B by 2 each time and leaves A-B unchanged.
The idea is as follows:
Iterate i from 1 to N. Let cur_P = P_i, cur_Q = Q_i, cur_{id} = i.
For each j from i-1 to N, if P_j < cur_P and Q_j < cur_Q, swap the pairs (cur_P, cur_Q) with (P_j, Q_j), and set cur_{id} = j (in terms of R, this equates to performing the swap (R_{cur_{id}}, R_j)).
In other words, we just swap the pair (P_i, Q_i) down as much as possible.
Notice that any pair swapped in this process is a type 1 pair which initially contributed 0 to A+B. So, swapping it increases A+B by 2 and does not change -B$.
However, this time we also need to worry about indices between the two we swapped - because if we have i < k < j, swapping i and j also swaps the contribution of the pairs (i, k) and (k, j).
It turns out that the overall contribution of all such flips is 0.
Proof
Suppose we swap i and j, and have j < k < i.
Our process chose j such that it was the closest to i with P_j < P_i and Q_j < Q_i.
Thus, either P_k > P_i or Q_k > Q_i.
- If both P_k > P_i and Q_k > Q_i, we also have P_k > P_j and Q_k > Q_j. Swapping (i, j) doesn’t change the relative comparisons so the number of inversions of both permutations is unchanged.
- If P_k > P_i but Q_k < Q_i, we have P_k > P_j. If Q_k < Q_j, just as above swapping i and j doesn’t change the relative order of elements in both P and Q, so the number of inversions doesn’t change.
What if Q_j < Q_k < Q_i?
In this case, we have Q_j < Q_k and P_j < P_k, but notice such that if such a pair did exist, it would have been swapped at an earlier step of our process.
(Formally, the invariant maintained is that when starting the process at index i, there is no ‘swappable’ pair before i)
This is a contradiction, so such a pair cannot exist.
Thus, the number of inversions of both P and Q does not change, except from the pair (i, j).
Note that the problem is solved now - we modify Q to obtain the correct value of A-B, then modify both permutations to obtain the correct value of A+B.
No special data structure is required to implement this: the constraints are low enough that a straightforward \mathcal{O}(N^2) implementation is fast enough.
TIME COMPLEXITY:
\mathcal{O}(N^2)
CODE:
Setter (C++)
#include <bits/stdc++.h> using namespace std; bool check(int X, int Y, int A, int B) { if ((B+A+Y)%2) return false; int X1 = (B+A-Y)/2; int Y1 = A - X1; if (X1<0||X1>X) return false; if (Y1<0||Y1>Y) return false; return true; } void solve() { int n, A, B; cin>>n>>A>>B; vector<pair<pair<int, int>, int>> p(n); for (int i = 0; i<n; i++) { cin>>p[i].first.first; p[i].second = i; p[i].first.first--; } for (int i = 0; i<n; i++) { cin>>p[i].first.second; p[i].first.second--; } int X = 0; int Y = 0; for (int i = 0; i<n; i++) for (int j = i+1; j<n; j++) { if ((p[i].first.first<p[j].first.first)==(p[i].first.second<p[j].first.second)) X++; else Y++; } if (!check(X, Y, A, B)) {cout<<-1<<endl; return;} vector<int> same(n), diff(n), P_invs(n), Q_invs(n); for (int i = 0; i<n; i++) { for (int j = 0; j<n; j++) if (i!=j) { if ((p[i].first.first<p[j].first.first)==(p[i].first.second<p[j].first.second)) same[i]++; else diff[i]++; if (p[i].first.first>p[j].first.first) P_invs[i]++; if (p[i].first.second>p[j].first.second) Q_invs[i]++; } } for (int iter = 0; iter<n; iter++) { int cur = iter; while (true) { if (check(X-same[cur], Y-diff[cur], A-P_invs[cur], B-Q_invs[cur])) { X-=same[cur]; Y-=diff[cur]; A-=P_invs[cur]; B-=Q_invs[cur]; for (int i = iter; i<n; i++) if (i!=cur) { if ((p[i].first.first<p[cur].first.first)==(p[i].first.second<p[cur].first.second)) same[i]--; else diff[i]--; if (p[i].first.first>p[cur].first.first) P_invs[i]--; if (p[i].first.second>p[cur].first.second) Q_invs[i]--; } swap(p[iter], p[cur]); swap(same[iter], same[cur]); swap(diff[iter], diff[cur]); swap(P_invs[iter], P_invs[cur]); swap(Q_invs[iter], Q_invs[cur]); break; } else cur++; } } for (int i = 0; i<n; i++) cout<<p[i].second+1<<' '; cout<<endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); int t; cin>>t; while (t--) solve(); }
Tester (Kotlin)
import java.io.BufferedInputStream fun main(omkar: Array<String>) { val jin = FastScanner() val out = StringBuilder() repeat(readLine()!!.toInt()) { val n = jin.nextInt() val a = jin.nextInt() val b = jin.nextInt() val p = listOf(0) + List(n) { jin.nextInt() } val q = listOf(0) + List(n) { jin.nextInt() } val answer = Array(n + 1) { it } answer.sortBy { p[it] } var inversionSum = 0 var inversionDiff = 0 for (j in 1..n) { for (k in j + 1..n) { if (q[answer[j]] > q[answer[k]]) { inversionDiff++ inversionSum++ } } } xLoop@for (x in 1..n) { for (j in n downTo x + 1) { if (inversionDiff == b - a) { break@xLoop } if (q[answer[j]] == x) { inversionDiff -= 2 val u = answer[j] val v = answer[j - 1] answer[j] = v answer[j - 1] = u } } } if (inversionDiff != b - a) { out.appendln(-1) return@repeat } jLoop@for (j in 1..n) { var j = j for (k in j - 1 downTo 1) { if (inversionSum == a + b) { break@jLoop } if (p[answer[k]] < p[answer[j]] && q[answer[k]] < q[answer[j]]) { inversionSum += 2 val x = answer[j] val y = answer[k] answer[j] = y answer[k] = x j = k } } } if (inversionSum != a + b) { out.appendln(-1) return@repeat } out.appendln(answer.toList().subList(1, n + 1).joinToString(" ")) } print(out) } nextInt(): Int { var neg = false if (c == NC) c = char while (c < '0' || c > '9') { if (c == '-') neg = true c = char } var res = 0 while (c >= '0' && c <= '9') { res = (res shl 3) + (res shl 1) + (c - '0') c = char } return if (neg) -res else res } } | https://discuss.codechef.com/t/permutinvs-editorial/95811 | CC-MAIN-2021-49 | refinedweb | 1,842 | 70.23 |
This action might not be possible to undo. Are you sure you want to continue?
Contents of Chapter 4
• Chapter 4 The Greedy method
– – – – – – – – – – 4.1 The general method 4.2 Knapsack problem 4.3 Tree vertex splitting 4.4 Job sequencing with deadlines 4.5 Minimum cost spanning trees 4.6 Optimal storage on tapes 4.7 Optimal merge patterns 4.8 Single-source shortest paths 4.9 References and readings 4.10 Additional exercises
4.1 General Method
• Greedy method control abstraction for subset paradigm (Program 4.1)
SolType Greedy(Type a[], int n) // a[1:n] contains the n inputs. { SolType solution = EMPTY; // Initialize the solution for (int i = 1; i <= n; i++) { Type x = Select(a); if Feasible(solution, x) solution = Union(solution, x); } return solution; } – Terminologies: feasible solution, objective function, optimal
solution – Subset paradigm vs. ordering paradigm • Subset paradigm: selection of optimal subset (Sec. 4.2 – 4.5) • Ordering paradigm: finding optimal ordering (Sec. 4.6-4.8)
4.2 Knapsack Problem
• Problem definition
– Given n objects and a knapsack where object i has a weight wi and the knapsack has a capacity m – If a fraction xi of object i placed into knapsack, a profit pixi is earned – The objective is to obtain a filling of knapsack maximizing the total profit
• Problem formulation (Formula 4.1-4.3)
maximize
subject to ∑ wi xi ≤ m
1≤i ≤n
1≤i ≤n
∑p x
i
i
( 4.1) (4.2) ( 4.3)
and 0 ≤ xi ≤ 1, 1 ≤ i ≤ n
• A feasible solution is any set satisfying (4.2) and (4.3) • An optimal solution is a feasible solution for which (4.1) is maximized
1 In case the sum of all the weights is ≤ m. (p1. • Lemma 4.w2. 1 ≤ i ≤ n is an optimal solution. 2/3.10) ( x1 .w3)=(18.p2. 3. 4.15).5 • Lemma 4. x 3 ) 1. 1) 20 (0. • Knapsack problem fits the subset paradigm . x2 .2 Knapsack Problem • Example 4. m=20. 1/4) 16. 1/2) 20 24.24.5 (1. 1.p3)=(25. 0) 20 (0.2 31 31.1 – n=3. ∑w x ∑ p x i i i i (1/2.4. (w1.2 All optimal solutions will fill the knapsack exactly. 2. 1/3. 2/15. then xi = 1.25 28.15.
2 Knapsack Problem • Greedy strategy using total profit as optimization function – Solution 2 in Example 4.1 – Optimal .4.1 – Suboptimal • Greedy strategy using weight (capacity used) as optimization function – Solution 3 in Example 4.1 – Suboptimal • Greedy strategy using ratio of profit to weight (pi/wi) as optimization function – Solution 4 in Example 4.
U -= w[i].2 Knapsack Problem • Algorithm for greedy strategies (Program 4. // Initialize x. i++) x[i] = 0. i<=n. i++) { if (w[i] > U) break.4.2) – Assuming the objects already sorted into nonincreasing order of pi/wi void GreedyKnapsack(float m.0. i<=n. } . m is the knapsack // size and x[1:n] is the solution vector. float U = m. for (i=1. int n) // p[1:n] and w[1:n] contain the profits and weights // respectively of the n objects ordered such that // p[i]/w[i] >= p[i+1]/w[i+1]. } if (i <= n) x[i] = U/w[i]. x[i] = 1.0. { for (int i=1.
1 If p1/w1 ≥ p2/w2 ≥ … ≥ pn/wn. it is shown how to make the xi in the optimal solution equal to that in the greedy solution without any loss in total value.2 Knapsack Problem – Time complexity • Sorting: O(n log n) using fast sorting algorithm like merge sort • GreedyKnapsack: O(n) • So. .4. • Proving technique Compare the greedy solution with any optimal solution. If the two solutions differ. then find the first xi at which they differ. Repeated use of this transformation shows that the greedy solution is optimal. then GreedyKnapsack generates an optimal solution to the given instance of the knapsack problem. total time is O(n log n) • Theorem 4. Next.
2) 2. 3) 3.1. (1. 3 or 3. (2) 8.2 – n=4. (p1.d3.d2. 3) 5. (4) processing sequence value 2.d4)=(2. (1. (2. 4) 4.1) Feasible Solution 1. (d1. 1 127 2.4. (1) 7. 4) 6. 1 115 4.p4)=(100.p3.10.15.27).2. 3 25 4. 3 42 1 100 2 10 3 15 4 27 . (1. (3) 9.4 Job Sequencing with Deadlines • Example 4.p2. 1 110 1. (3.
3 Let J be a set of k jobs and permutation of jobs in J such that Then J is a feasible solution iff the jobs in J can be processed in the order without violating any deadline. 1 2 k σ . σ = i .4} with total profit 127 – It is optimal • How to determine the feasibility of J ? – Trying out all the permutations • Computational explosion since there are n! permutations – Possible by checking only one permutation • By Theorem 4. ≤ d ik . and added to J J={1.4. but discarded because not feasible J={1.3 a • Theorem 4...4} • Final solution is J={1. i .4 Job Sequencing with Deadlines • Greedy strategy using total profit as optimization function – Applying to Example 4. i d i1 ≤ d i 2 ≤ .2 • Begin with J=φ • Job 1 considered....4} • Job 2 considered. but discarded because not feasible J={1.4} • Job 3 considered.. and added to J J={1} • Job 4 considered.
} } . i++) { if (all jobs in J ∪{i} can be completed by their deadlines) J = J ∪{i}. int n) – Assuming the jobs are ordered such that p[1]≥ p[2]≥ … // J is a set of jobs that can be ≥ p[n] // completed by their deadlines. { J = {1}.5) GreedyJob(int a[]. set J. for (int i=2. i<=n.4 The greedy method described above always obtains an optimal solution to the job sequencing problem.4 Job Sequencing with Deadlines • Theorem 4. • High level description of job sequencing algorithm (Program 4.4.
are the jobs in J and d[J[1]] ≤ d[J[2]] ≤ …. 1≤ r≤ k+1 .5 ? – How to represent J to avoid sorting the jobs in J each time ? • 1-D array J[1:k] such that J[r].4 Job Sequencing with Deadlines • How to implement Program 4. ≤ d[J[k]] • To test whether J ∪ {i} is feasible.4. 1≤ r≤ k. just insert i into J preserving the deadline ordering and then verify that d[J[r]]≤ r.
. for (int i=2. // Also. i<=n. d[0] = J[0] = 0. // Include job 1.. Find position for // i and check feasibility of insertion. (Program 4. The jobs // are ordered such that p[1]>=p[2]>= . if ((d[J[r]] <= d[i]) && (d[i] > r)) { // Insert i into J[]. int n) // d[i]>=1. for (int q=k. { //Consider jobs in nonincreasing // order of p[i].. J[i] // is the ith job in the optimal solution. J[r+1] = i. k++. 1<=i<=k. at termination d[J[i]]<=d[J[i+1]]. >=p[n]. i++) { int r = k. 1<=i<=n are the deadlines.4. int k=1. n>=1. // Initialize. 1<=i<k. q--) J[q+1] = J[q].4 Job Sequencing with Deadlines • C++ description of job sequencing algorithm int JS(int d[]. J[1] = 1. while ((d[J[r]] > d[i]) && (d[J[r]] != r)) r--. } } } return (k). q>=(r+1).6) int j[].
5 Spanning trees • Applications – Obtaining an independent set of circuit equations for an electric network – etc . E) be at undirected connected graph. • Example 4.1 Let G=(V.5 Minimum-cost Spanning Trees • Definition 4. A subgraph t=(V.4. E’) of G is a spanning tree of G iff t is a tree.
5 Minimum-cost Spanning Trees • Example of MCST (Figure 4.4.6) – Finding a spanning tree of G with minimum cost 1 10 6 25 24 5 7 28 2 14 16 3 18 12 4 6 25 5 10 1 2 14 7 16 3 12 22 (b) 4 22 (a) .
4.6 (Figure 4.5.1 Prim’s Algorithm • Example 4.7) 1 1 10 10 2 6 5 7 4 3 6 25 5 4 7 1 2 3 6 25 5 1 2 7 5 10 16 3 12 22 4 6 25 5 22 4 14 7 2 16 3 12 10 7 2 3 (a ) 1 10 6 25 5 7 2 3 12 6 25 10 (b 1) 22 4 (c) (d 22 4 (e) (f) .
near(7))=24 So.5. near(2))=28 near(3)=1 (or 5 or 6).near(j)) is minimum among all choices for near(j) • The next edge is defined by the vertex j such that near(j)≠ 0 (j not already in the tree) and cost(j. near(3))=∞ // no edge to the tree near(4)=5.7 (b) near(1)=0 // already in the tree near(2)=1. Figure 4. the next vertex is 4 . cost(4. cost(3. cost(2. near(4))=22 near(5)=0 // already in the tree near(6)=0 // already in the tree near(7)=5.near(j)) is minimum – eg. cost(7.4.1 Prim’s Algorithm • Implementation of Prim’s algorithm – How to determine the next edge to be added? • Associating with each vertex j not yet included in the tree a value near(j) • near(j): a vertex in the tree such that cost(j.
int n. 15 t[1][1] = k. L.4. 13 let (k. 28 if ((near[k]!=0) && 29 (cost[k][near[k]]>cost[k][j])) 30 near[k] = j. 16 for (int i=1.5. 25 mincost = mincost + cost[j][near[j]]. 17 if (cost[i][L] < cost[i][k]) near[i] = L. j. i <= n-1.1 Prim’s Algorithm • Prim’s MCST algorithm (Program 4. 20 for (i=2. 19 near[k] = near[L] = 0. 18 else near[i] = k. 24 t[i][1] = j.8) 1 float Prim(int E[][SIZE]. t[1][2] = L. i<=n. 22 let j be an index such that near[j]!=0 and 23 cost[j][near[j]] is minimum. i++) // Initialize near. k.L) be an edge of minimum cost in E. int t[][2]) 11 { 12 int near[SIZE]. 14 float mincost = cost[k][L]. 31 } 32 return(mincost). 27 for (k=1. t[i][2] = near[j]. i++) { // Find n-2 additional 21 // edges for t. 26 near[j]=0. k<=n. k++) // Update near[]. float cost[][SIZE]. 33 } .
5.4.1 Prim’s Algorithm • Time complexity – – – – Line 13: O(|E|) Line 14: Θ (1) for loop of line 16: Θ (n) Total of for loop of line 20: O(n2) • n iterations • Each iteration – Lines 22 & 23: O(n) – for loop of line 27: O(n) – So. Prim’s algorithm: O(n2) • More efficient implementation using red-black tree – Using red-black tree • Lines 22 and 23 take O(log n) • Line 27: O(|E|) – So total time: O((n+|E|) log n) .
2 Kruskal’s Algorithm • Example 4.5.8) 1 1 10 2 6 5 7 4 3 6 5 7 1 2 3 10 6 5 7 2 3 12 4 4 (a ) 1 10 6 5 14 7 4 2 3 12 10 6 5 (b 1) 14 7 2 10 16 3 12 4 6 5 (c) 1 14 7 22 4 2 16 3 12 (d (e) (f) .7 (Figure 4.4.
9) • How to implement ? t = EMPTY.5. w) from E. } – Two functions should be considered • Determining an edge with minimum cost (line 3) • Deleting this edge (line 4) – Using minheap • Construction of minheap: O(|E|) • Next edge processing: O(log |E|) – Using Union/Find set operations to maintain the intermediate forest .2 Kruskal’s Algorithm • Pseudo code of Kruskal’s algorithm (Program 4. w). w) dose not create a cycle in t add (v. w) from E of lowest cost. while ((t has fewer than n-1 edges) && (E!=EMPTY)) { choose an edge (v. delete (v. else discard (v.. if (v.4. w) to t.
} . if (j != k) { i++. else return(mincost). int t[][2]) { int parent[SIZE]. int n.4.v) from the heap and reheapify using Adjust.5. while ((i < n-1) && (heap not empty)) { delete a minimum cost edge (u. t[i][1] = u. float mincost = 0. i++) parent[i] = -1. mincost += cost[u][v]. int k = Find(v). k).2 Kruskal’s Algorithm • Kruskal’s algorithm (Program 4. } } if ( i != n-1) cout << “No spanning tree” << endl.0. int j = Find(u). construct a heap out of the edge costs using Heapify.10) float Kruskal(int E[][SIZE]. i = 0. Union(j. i<=n. float cost[][SIZE]. y[i][2] = v. // Each vertex is in a different set. for (int i=1.
x2. 20. requiring the fewest comparisons or record moves) to pairwise merge them into one sorted file – It fits ordering paradigm • Example 4.x3) with lengths (30. merging the result with x1 (60 moves) total 90 moves – The solution 2 is better ..e. find an optimal way (i. merging the result with x3 (60 moves) total 110 moves – Solution 2: merging x2 and x3 (30 moves). 10) – Solution 1: merging x1 and x2 (50 record moves).9 – Three sorted files (x1.4.7 Optimal Merge Patterns • Problem – Given n sorted files.
11) 95 z4 z2 35 z1 15 5 x4 10 x3 20 x1 30 x5 60 z3 30 x2 – Total number of record moves = weighted external path length ∑d q i =1 n i i – The optimal 2-way merge pattern = binary merge tree with minimum weighted external path length .10.30.30) (Figure 4.7 Optimal Merge Patterns • A greedy method (for 2-way merge problem) – At each step.4..g. five files with lengths (20. merge the two smallest files – e.5.
// smallest lengths. // Get a new tree node. } return (Least(list)). } . { for (int i=1.13) struct treenode { struct treenode *lchild. // Tree left in l is the merge tree. Insert(list. }. int weight. Type *Tree(int n) // list is a global list of n single node // binary trees as described above. *rchild. // Merge two trees with pt -> rchild = Least(list). i<n.7 Optimal Merge Patterns • Algorithm (Program 4.4. pt -> weight = (pt->lchild)->weight + (pt->rchild)->weight. pt -> lchild = Least(list). *pt). typedef struct treenode Type. i++) { Type *pt = new Type.
4.10 (Figure 4.7 Optimal Merge Patterns • Example 4.12) .
7 Optimal Merge Patterns • Time – If list is kept in nondecreasing order: O(n2) – If list is represented as a minheap: O(n log n) .4.
.4.7 Optimal Merge Patterns • Huffman codes – Obtaining an optimal set of codes for messages M1. .. 4 messages (Figure 4.g. M2. Mn+1 – e.14) 0 1 0 0 M1 • • • • M1=000 M2=001 M3=01 M4=1 1 M3 1 M2 M4 .
10.4.5.….8.q2.12.q7)=(4.7 Optimal Merge Patterns • Huffman codes (Continued) – When qi is the relative frequency for Mi • The expected decode time (also the expected message length) qd 1≤i ≤n + 1 ∑ i i • The minimum decode time (also minimum message length) is possible by choosing the code words resulting in a binary tree with minimum weighted external path length (that is.7. the same algorithm as 2-way merge problem is applicable) – Example using Exercise 4 • (q1.20) .
15) .8 Single-source Shortest Paths • Example 4.11 (Figure 4.4.
in Figure 4. and ending at w . going through only those vertices that are in S.. in nondecreasing order of path lengths • e.15 – 14: 10 – 145: 25 – … • We need to determine 1) the next vertex to which a shortest path must be generated and 2) a shortest path to this vertex – Notations • S = set of vertices (including v0 ) to which the shortest paths have already been generated • dist(w) = length of shortest path starting from v0.4.g.8 Single-source Shortest Paths • Design of greedy algorithm – Building the shortest paths one by one.
• The destination of the next path generated must be that of vertex u which has the minimum distance. • Having selected a vertex u as in observation 2 and generated the shortest v0 to u path. and goes through only those vertices that are in S. dist(u). then the path begins at v0. ends at u. vertex u becomes a member of S.8 Single-source Shortest Paths • Design of greedy algorithm (Continued) – Three observations • If the next shortest path is to vertex u. among all vertices not in S.4. .
num < n. int n) { int u. float cost[][SIZE]. i++) { // Initialize S. // Put u in S.4.8 Single-source Shortest Paths • Greedy algorithm (Program 4.0. S[u] = true. } S[v]=true. choose u from among those vertices not in S such that dist[u] is minimum. for (int i=1. i<= n. num++) { // Determine n-1 paths from v. float dist[]. for (int w=1.14): Dijkstra’s algorithm – Time: O(n2) ShortestPaths(int v. dist[v]=0. dist[i] = cost[v][i]. w<=n. // Put v in S. S[i] = false. if (( S[w]=false) && (dist[w] > dist[u] + cost[u][w])) dist[w] = dist[u] + cost[u][w]. } } . for (int num = 2. w++) //Update distances. bool S[SIZE].
8 Single-source Shortest Paths • Example 4.4.16) .12 (Figures 4.
4.17) .12 (Figures 4.8 Single-source Shortest Paths • Example 4. | https://www.scribd.com/doc/44899789/Chap-4 | CC-MAIN-2017-34 | refinedweb | 2,927 | 78.45 |
Related link:
I’ll admit it … I’m one of those poor saps who inevitably, when given the chance, roots for the underdog. I can’t help it. For several years, I rooted for the Seattle Mariners, that perennial underdog that has, in its thirty odd years of existence, never made it to the World Series. Its perhaps for this reason (though there many others) that I’ve been a long time fan of Open Office. The open source office suite has come from rather dismal beginnings (the early Star Office incarnations were truly dreadful) into being a solid, capable, and performant alternative to Microsoft Office not only in the Linux space but even on MS Office’s home turf of Windows.
Open Office Developer Writing Content
In the wake of Open Office 2.0, there have been a number of interesting developments that are aimed at improving not only the product itself but also the developer and user communities. One in which I have a direct hand most recently is the establishment by the Open Office development team of a contest for the best technical article about some facet of Open Office. To specifically quote Louis Suarez-Potts of the Open Office Team:.
I am a member of the judging board, and I’m specifically going to be looking for decent articles with an XML bent to recommend, so please, feel free to submit as often as possible.
Open Office Labels
Russell Ossendryver, the US director of Worldlabel.com, also recently wrote to me to announce one of those odd little niches in business which can, when identified, make their identifier a very wealthy man. In this case, Russell.
I personally think this is a fairly major thing - most labels are generated for use from within office programs and batch processing mode processing. The templates, in addition to working well within the Open Office environment, can also be opened and examined by unzipping the template document, which means that with a little bit of additional processing you could actually utilize these with XSL-FO to generate labels from other XML sources.
Mitt Romney is Fast Becoming My Hero
When Massachusetts state CIO Peter Quinn resigned recently due to intense lobbying pressure (and some reported intimidation tactics) may have seemed like a major blow to the adoption of the Open Document Format, but it seems that Massachusetts Governor Mitt Romney may in fact have the last laugh. On the 30th of January, he appointed a new CIO, Louis Gutierezz, and during the appointment also released a press release indicating that he was still very much in favor of the ODF format and planned on seeing it made official by year’s end, as is indicated in the second sentence of the press release:
Gutierrez will be responsible for overseeing the final stages of implementation of the state’s new Open Document format proposal, to go into effect in January 2007.
This is frankly incredible, and showcases the fact that Romney, who’s rumored to be considering a run for President, is both very much aware of the technical debate and at the same time has absolutely no intention of being bullied by Microsoft on this front. It’s a gutsy stance for any politician to take, and bodes well for the future of open standards in the state … and by extension, may prove to be the catalyst for other states to consider moving their infrastructure to open standards.
(More info on this can be found at Andy Updegrove’s Standards Blog).
Open Office for Intel Mac OSX and Portable Open Office
Open Office recently announced that the first build of Open Office 2.01 for the Intel version of Mac OSX, adding to the applications capable of running on that intriguing hybrid. In similar news, OpenOffice.org teamed with PortableApps.com to create a portable version of OpenOffice, one capable of running off of a USB thumbdrive, a portable hard drive, an iPOD or MP3 player, and so forth. This raises a number of issues, not least of which being that we are rapidly reaching the second fork of ubiquitious computing (the first being files in the Internet data cloud), where one’s data can remain with you even without a computer. If bluetooth or ultra high bandwidth wireless USB ever becomes a reality, this gives rise to the notion that you could walk up to a computer anywhere and start working with the files located on your belt buckle or earrings, without having to worry about having the right tools.
SVG Import Filter
At the end of last month OpenOffice.org released what I’ve felt has long been a sorely needed feature - an SVG Import Filter. While Open Office doesn’t use SVG internally (although it does maintain critical information in an SVG namespace within drawings) the lack of SVG import support has meant that its not possible to load in SVG files as graphics for word documents - something that’s been very frustrating to me and many others. Utilizing the Apache Batik SVG engine, the import filter has undergone a number of improvements since its last update in August, including considerably better handling of gradients (something that’s always been a problem in OpenOffice), better handling of elliptical curves and transformable use and image elements. It does require that you have the Java JRE 1.5 on your system.
Batch Conversion of Legacy Docs
Bob DuCharme, in a superb article for XML.com writes about “Moving to OpenOffice: Batch Converting Legacy Documents.“. In it he covers the Open Office macro language and illustrates how you can create a simple batch routine for taking all of those pesky proprietary MS Word documents and converting them into Open Office format, including invoking this from a command line call. I’ve used Open Office before in this role as a batch document converter not just to ODF (or to the older SXW format) but to DocBook and other related formats. This trick should be a critical part of any document management system that needs to convert legacy Word documents into XML formats, without the licensing costs of going to the MS Office 2003 and utilizing the Office Open (hah!) XML format.
So, to wrap this up, once again I ask all of you budding technical writers to try your chops in writing for the OpenOffice contestOpenOffice contest. It comes with a decent prize ($750 for the winning entry per month), and helps to build the information base for the best open source office suite on the planet.
Kurt Cagle is an author and web architect specializing in XML, Web 2 and AJAX technology, and is currently available for consulting (please check out his resume for more information).
Do you have any news or case studies about OpenOffice that you’d like to let people know about? | http://www.oreillynet.com/xml/blog/2006/02/open_office_party_2.html | crawl-002 | refinedweb | 1,146 | 52.94 |
Memory leakage in Max?
Hi,
I’ve recently been putting together a patch for a permanent installation. Previous projects I’ve done like this have always involved using Windows’ scheduler (don’t ask me why it’s on Windows, something about budget constraints apparently) to restart the machine and the patch periodically to reduce the likelihood of the machine crashing. Apparently, so the client tells me, hardware constraints are such that this cannot happen. Does anybody with any experience in this know how likely it is that Windows (I think Vista) or indeed Max 5 will last before memory leakage or something else awful causes the computer to keel over? It’s especially annoying as the installation is in Warsaw and we’re in the UK, so rebooting every now and then isn’t really a practical option.
Thanks
Hi.
One explaination might be that you’re filling up Max’s symbol table. Every symbol you create is stored in memory and never erased until you quit Max. This is not a memory leak, is part of Max’s design and has specific purposes, but can become a serious issue for long-running patches.
If this is what causes your crashes, the only solution is reducing the number of symbols you create, using numbers whenever possible and being careful with [sprintf], [combine] and things like that.
hth
aa
Thanks for the reply. When you say ‘create’, does that apply to just being used? I have various messages that are printed to the Max window to give some feedback about the patch’s behaviour so it can be monitored long term. Some of these are routed to various locations. Will banging these messages be classed as ‘creating’ them do you know?
Each new symbol will bloat the table by a very small amount. When symbols are reused there is no additional memory overhead, so unless you are doing something like auto-generating symbols (from date / time combinations for example) then you shouldn’t worry about this.
I’d suggest that you could try running your patch whilst monitoring memory usage, and see if there is an increase over time at all. Beyond that the best way to find out is probably to run a dummy run for as long as possible in the most similar conditions you can create, although that may not be practical in your case…
Alex
leakage rules.
and a serious answer, too.
i have seen memory leakage some year ago quite often when using maxmsp in
classic mac os.
the memory usage, which you could see in the console was continiously rising
and when the glass was full the computer froze.
i never found out what caused this, i think it was in 4.05 and went away with 4.09,
and it was not rleated to poly~.
eventually it might have been something with the m-audio delta hardware i was
using back in the days.
-110
"Every symbol you create is stored in memory and never erased until you quit Max"
the same is true for namespaces .. but they cant be the problem i guess. ;)
If you can reproduce please send an example to support and we’ll look into it. It’s also worth mentioning that Max uses a memory pool to be more efficient, and this memory pool can give you the impression that Max is leaking but if in fact the memory can be reused. The Max window for instance uses memory in the pool, so if you clear it from time to time, you’ll see that it reuses this memory. If you need to monitor things over a long period of time, I would recommend you store things into an external text file.
HTH
Forums > MaxMSP | https://cycling74.com/forums/topic/memory-leakage-in-max/ | CC-MAIN-2017-09 | refinedweb | 626 | 69.82 |
Python dev and test discussions. Not just pytest, but it's a common topic.
[Jacob Floyd, Test Podcast] I'm trying to fix a test. It's in a unittest class, but pytest is the official runner, so I'm using pytest features. Pulling the test out of the unittest class didn't make a difference.
The test is supposed to test signal handling. ie when the app gets SIGHUP and SIGINT, reload() should be called, as should sys.exit (or SystemExit should be raised).
If I run the one test all by itself, everything passes. But, when I run it in the suite, something else seems to get the SIGHUP/SIGINT causing pytest to exit. However wrote this before tried to use threading, but that just swallowed exceptions so no one knew that this test was broken. Instead some time after the test "passed" pytest would exit saying it got a KeyboardInterrupt.
So, is there a good way to run a pytest test with subprocess or multiprocessing to make sure the signal is only going to the process under test?
[Pax, Test Podcast] I’m creating tests involving an email marketing service (e.g. mailchimp). I’m trying to decide whether to pass the campaign’s
recipients explicitly / as a separate parameter to a method that creates/schedules campaigns---making it safer to not schedule a campaign to the actual list during a test.
On the other hand, it doesn’t seem right to pass the recipients as a separate parameter from the “email type” since an email/campaign always go to the same list / recipients. (Unless of course the method is used in tests.)
Based on my collective knowledge about clean code (mostly books), passing a separate
recipients parameter just for the sake of tests is not a good design decision; and that it’s the responsibility of the person making tests (which is currently me…but could be a different person in the future) to clean up (delete campaigns) or mock appropriately (perhaps stub the
recipients prop) to make sure no email generated from tests are sent to actual users — but I also think there’s so much I don’t know so I would like to hear what others think.
[Kristoffer Bakkejord, Test Podcast] I am looking for something that lets me parametrize tests that sets a class property - something like this (not working example)
```@pytest.mark.parametrize("source_name", ["source_1.txt", "source_2.txt"])
class TestSource:
def params_init(self, source_name):
self.source = source_name
def test_source(self): assert self.source in ["source_1.txt", "source_2.txt"]```
Has anyone come across something like this?
This would allow me to refer to the class instance when running my tests (
self.source in the above example).
Maybe this is what I'm looking for: (thinking face emoji)
@pytest.fixture(params=["source_1.txt", "source_2.txt"], scope="class", autouse=True) def source_file_name(request): return request.param
[Kristoffer Bakkejord, Test Podcast] @Salmon Mode Indeed, if the test was as simple as in the above example, that would work. But I'm having a test class with several methods. I would like to run the entire test class, with different test inputs.
If I parametrize the test class, I will have to pass all argnames (of pytest.mark.parametrize) to all methods of the test class. I don't want that, as it would result in many methods getting variables they''re not using.
It's a set of tests which are interconnected (second test depends on first and so on), so using a class to tie these together seemed like a good idea. It's a bit difficult to explain here. Not so sure if I want to go that route anymore. Maybe I should look into pytest-subtest or pytest-check instead (thinking face emoji)
[Kristoffer Bakkejord, Test Podcast] It's not for testing python code. It's testing a workflow running through a workflow system (Zeebe). The test class was intended to test a workflow, and several runs through parametrizing it. Then each test function in the test class would be a step in the workflow. (Sorry if the explanation isn't entirely clear.)
But I don't think I need the reporting of each step in the workflow - a pass/fail for the entire workflow may be sufficient (then I can do asserts or subtests/checks during the test run).
[Kristoffer Bakkejord, Test Podcast] Firstly, I agree that code should be designed in a manner where each can be broken into units that can be individually tested.
In your example... it depends. Is it possible to mock function B's execution? If yes, then we can do just that. If no - then function B must be called.
Just to be clear, and follow up on your example - I am mocking function B. I have unit tests/integration tests for the work that B performs.
But what I need to test is that A can run with different inputs, and that D is run in some cases and C in other.
I think my approach of running a test within the "main test" (the test class) has been the wrong approach. My conclusion is that test classes should be used for grouping tests, and doesn't allow too much control logic (e.g. if class property foo == bar, don't run test method B or C).
I think my approach will move over to testing the workflow definition/DAG in a single pytest function, one for each variant. And mock the execution of the steps (which I have been doing with test class+test methods, but bending pytest the wrong ways).
But - it's not always possible to mock B, and maybe B must be run to determine the outcome needed before C/D. It's not always possible to use the philosophy of unit testing, when testing systems you don't have too much control over (black box testing).
[Chris NeJame, Test Podcast] The system chosen (in this case, Zeebe) was a design decision, just as much as how functions, classes, and modules would be structured. If the functions, classes, and modules were designed in such a way (not to imply intent), that testing the individual components of it would be made more difficult, or even impossible, then I would suggest changing the design.
When you have to test the DAG, it exponentially increases the number of tests you'd have to do, and I'm guessing you're trying to reduce the very large amount of duplicate code that you might have to write because of the sheer number of tests. Testing the DAG itself is not ideal, because of how many tests there would likely be, but this is why some places use model-based testing to start exploring issues that may only present themselves at that level of complexity, in addition to their normal tests.
[Kristoffer Bakkejord, Test Podcast] To be clear Zeebe isn't "untestable", but it requires a different approach than say unit tests, and figuring that out isn't necessarily easy. Just because it's not, doesn't mean it's a bad design decision.
Here's one test implementation for Zeebe BPMNs (i.e. DAGs): (this doesn't cover our use case, which is why I'm looking into an approach in pytest).
[Chris NeJame, Test Podcast] In my opinion, any design-related decision that makes testing things in an atomic way less achievable, is a bad design decision, as this inherently introduces large amounts of technical debt (i.e. time was borrowed from the future for a perceived speedup in the short term, and this will likely cost more time in the long term than what was perceived to be saved in the short term).
In this case, in order to pay down the technical debt completely, you would have to go bankrupt and rebuild everything (unless you can piecemeal separate out individual components to be handled by separate, atomically testable components)..
Consciously sacrificing testability, for the sake of short term speed ups, is by no means uncommon, because testing is often seen as secondary and not as important as writing the "actual" code. But I have never heard of a case where doing so didn't bite the person in the ass, and every system I've worked on that focused only on operating at the DAG level (which is surprisingly not 0) was a buggy, unmaintainable mess once it was down the road enough to be considered (by some, but not me) to be MVP.
[Kristoffer Bakkejord, Test Podcast] > any design-related decision that makes testing things in an atomic way less achievable, is a bad design decision
Agreed..
It doesn't seem we're on the same page here. I do find Zeebe to be quite testable. With very little knowledge of pytest plugins and not too much time, I managed to create a basic framework that allowed me to test Zeebe BPMNs. Wanting to iterate on this, I met some challenges with how pytest works. But that don't mean either pytest or Zeebe is a bad design decision – just that my assumptions about it was wrong (and I can learn from this).
Consciously sacrificing testability
I don't think I am doing that,...
that focused only on operating at the DAG level
Not sure I'm following you here. You may have had a bad experience with DAG systems, but I don't think you should have assumptions about every use case and implementation considerations others may have.
Anyways - I appreciate the discussion. You come with many good points. I was looking for some input on how to use pytest with test classes, and I've come to a conclusion that this isn't the right path.
[Chris NeJame, Test Podcast] The problems with such a system likely aren't obvious now, and may not be for a time, but, like I said, taking up technical debt is about short term gains, with long term consequences. The problems will become more apparent as you build out the application. As more complexity is introduced, it will exponentially grow out of control.
The systems I worked with all had in common an inability to test individual steps in isolation. This meant that the automated tests had to operate at the end-to-end level, which made them very expensive and time consuming to run, and would break regularly, especially when third party dependencies were having issues. They would also prevent developers from finding out the full picture in regards to what was broken, because if an earlier common step was broken, everything that depended on it could not be tested.
The end result, was a lot of wasted work, and very slow developer feedback loops, which wasted a lot of time.
I wish you the best of luck though. I'm sure this will be quite an informative/educational experience in many ways :)
def ensure_some_default_settings() -> bool: ... return # ... True or False
if ensure_some_default_settings:
did you mean `if ensure\_some\_default\_settings\(\):`
my_project.connections.redis_client,i.e. you need to patch it from the POV of the file you are using. if there are cross reference like that (with multiple layer of referencing) it become harder. since patch only replace the "reference", and reference which is different in multiple files, won't be replaced.
capsys.readouterr()but no success ^^
assert expected in captured.outwould work?
[a4z, Test Podcast] I wonder if I could get some startup help here, please!
I decided to share my helper scripts with colleagues, and the best option might be to distribute them as pip.
So I create some pip, say, mytool
Of course I know that mytool scripts work ( =@ ), but just to be sure, I would like to add some tests.
So I have this pip project layout
- mytool - tests LICENSE setup.py ... (rest of pip files)
now what to do that file in tests can import mytool
and optimal, that even VS Code knows about mytool when editing the test file
(You might notice on my question, python is not my dayjob)
[Erich Zimmerman, Test Podcast] General question -- in past testing, I have made use of delayed timing on assertions. For example, I may send an event to a system, but the assertion based on the event isn't immediate.
```some_object = MyClass()
related_object = NextClass(some_object)
some_object.take_action('action')
assert related_object.updated_property == 'action'```
In Nunit and others, there is support for basically a polling assertion, where you check the predicate until a timeout is reached.
Pytest and the Python assertions don't support this directly (well, as far as I can tell), but I don't even find any conversations online about doing something like this.
So, I'm wondering if this approach doesn't "fit" in the Pytest approach to testing?
I wrote a simple function on my own, called
wait_for_assert that takes a predicate function, resulting in an AssertException if the predicate is still failing after some time, so I'm good with that on the "works for me" paradigm. But I'm just curious if Pytest thinking would point me down a different road. | https://gitter.im/TestAndCode/Lobby?at=5ff8813c787d8f79c8ec9e21 | CC-MAIN-2022-27 | refinedweb | 2,189 | 69.11 |
in reply to Limit on array size?
The possible size of an array is only limited by how much memory you have. You may be running out of memory here. Instead of creating a huge scalar and a huge array, you might try just creating the array as you read the file:
while (<ASA>) {
push @ASAList, split;
}
[download]
This may help enough to get the entire array into memory, but if not, you'll have to use some scheme for keeping the data on the hard disk and only reading what you need. Sounds like a good job for a tied array, maybe something in the Tie namespace on CPAN will help.
--. | http://www.perlmonks.org/index.pl?node_id=305086 | CC-MAIN-2016-18 | refinedweb | 112 | 74.32 |
Activity Feeds with Rails
Activity feeds are all over the place. For example, Github’s main page lists all of the activity in your social coding network: one of your friends created or cloned a repo, a new issue was opened, your repo was forked or starred, etc.
Twitter displays the latest tweets, retweets, and replies.
That’s a convenient and easy way for users to learn about recent updates. How about trying to replicate the same functionality with Rails? Turns out, there is a convenient gem that makes the development process very easy!
In this article, I am going to talk about public_activity, a gem created by Piotrek Okoński to easily track activity for models (and more, actually). I will show you how to easily create an activity feed and employ various features of
public_activity to extend the app further.
Before proceeding, I wanted to make a small note. Some months ago, I wrote an article Versioning with PaperTrail that covered
paper_trail, a gem used to implement version control of an application’s models. In some ways,
paper_trail is similar to
public_activity and could be used to implement a solution similar to the one presented in this article. However,
paper_trail is aimed at crafting versioning systems, whereas
public_activity was created specifically to implement activity feeds.
The working demo is available at sitepoint-public-activity.herokuapp.com.
The source code is available on GitHub.
Preparing the App
Suppose we want to create an app that will allow users to share (cool) stories. Users should be able to sign in, but guests will be allowed to post stories, as well. There will also be a “Like” button for each story. The most important piece of functionality, however, will be an activity feed, so users are able to see what has happened recently. Example activities in the feed are a story was added, deleted, or liked.
Time for the ground work. Let’s call our app Storyteller:
$ rails new Storyteller -T
For this demo I am using Rails 4.2.0, but the same solution (with only a few tweaks) can be implemented with Rails 3.
Drop in some gems that we are going to use:
Gemfile
[...] gem 'bootstrap-sass', '~> 3.3.1' gem 'autoprefixer-rails' gem 'public_activity' gem 'omniauth-facebook' [...]
and run
$ bundle install
bootstrap-sass and
autoprefixer-rails are completely optional – the first one is used for styling and the second one automatically adds browser vendor prefixes to CSS rules.
public_activity is the star today, as it will help us set up the activity feed.
omniauth-facebook will be used to set up authentication.
If you’re following along, hook up Bootstrap’s styles:
application.scss
@import "bootstrap-sprockets"; @import "bootstrap"; @import 'bootstrap/theme';
Now, we have to prepare a couple of models. The first one will be called
Story and contain the following attributes (I am skipping the default
id,
created_at and
updated_at):
title(
string) – title of the story
body(
text) – body of the story
user_id(
integer) – foreign key to reference the author of the story
The second one will be called
User and have these attributes:
name(
string) – name (probably, with a surname) of the user
uid(
string) – user’s unique identifier provided by the social network
avatar_url(
string) – user avatar’s URL
Create and apply the required migrations:
$ rails g model User name:string uid:string:index avatar_url:string $ rails g model Story title:string body:text user:references $ rake db:migrate
Tweak the model files like this:
user.rb
class User < ActiveRecord::Base has_many :stories end
story.rb
class Story < ActiveRecord::Base belongs_to :user validates :title, presence: true validates :body, presence: true end
Set up routes:
[...] resources :stories delete '/logout', to: 'sessions#destroy', as: :logout get '/auth/:provider/callback', to: 'sessions#create' root to: 'stories#index' [...]
The
/auth/:provider/callback is the callback route used by Facebook as a part of the OAuth2 sign in process. The
:provider piece means that you may use any other Omniauth authentication strategy (or multiple strategies at once).
Focus on the layout now:
views/layouts/application.html.erb
[...] <div class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <%= link_to 'Storyteller', root_path, class: 'navbar-brand' %> </div> <ul class="nav navbar-nav pull-right"> <% if current_user %> <li><span><%= image_tag current_user.avatar_url, alt: current_user.name %></span></li> <li><%= link_to 'Log Out', logout_path, method: :delete %></li> <% else %> <li><%= link_to 'Log In', '/auth/facebook' %></li> <% end %> </ul> </div> </div> <div class="container"> <div class="page-header"> <h1><%= yield :page_header %></h1> </div> <% flash.each do |key, value| %> <div class="alert alert-<%= key %>"> <%= value %> </div> <% end %> <%= yield %> </div> [...]
Nothing special here apart from the
yield :page_header piece of code that relies on a
page_header helper method. Create it now:
application_helper.rb
module ApplicationHelper def page_header(header) content_for(:page_header) {header.to_s} end end
Great, the next step is creating the controller to put this all together:
stories_controller.rb
class StoriesController < ApplicationController before_action :find_story, only: [:destroy, :show, :edit, :update] def index @stories = Story.order('created_at DESC') end def new @story = Story.new end def create @story = Story.new(story_params) if @story.save flash[:success] = 'Your story was added!' redirect_to root_path else render 'new' end end def edit end def update if @story.update_attributes(story_params) flash[:success] = 'The story was edited!' redirect_to root_path else render 'edit' end end def destroy if @story.destroy flash[:success] = 'The story was deleted!' else flash[:error] = 'Cannot delete this story...' end redirect_to root_path end def show end private def story_params params.require(:story).permit(:title, :body) end def find_story @story = Story.find(params[:id]) end end
This is a very basic controller, but it gets more interesting in a bit.
Now, the views:
views/stories/index.html.erb
<% page_header "Our cool stories" %> <p><%= link_to 'Tell one!', new_story_path, class: 'btn btn-primary btn-large' %></p> <% @stories.each do |story| %> <div class="well well-lg"> <h2><%= link_to story.title, story_path(story) %></h2> <p><%= truncate(story.body, length: 350) %></p> <div class="btn-group"> <%= link_to 'Edit', edit_story_path(story), class: 'btn btn-info' %> <%= link_to 'Delete', story_path(story), data: {confirm: 'Are you sure?'}, method: :delete, class: 'btn btn-danger' %> </div> </div> <% end %>
As you can see, we are calling the
page_header helper method that was defined a moment ago. Here’s what is displayed for each story:
views/stories/show.html.erb
<% page_header @story.title %> <p><%= @story.title %></p> <div class="btn-group"> <%= link_to 'Edit', edit_story_path(@story), class: 'btn btn-info' %> <%= link_to 'Delete', story_path(@story), data: {confirm: 'Are you sure?'}, method: :delete, class: 'btn btn-danger' %> </div>
The
new and
edit views are even simpler:
views/stories/new.html.erb
<% page_header "New cool story" %> <%= render 'form' %>
views/stories/edit.html.erb
<% page_header "Edit cool story" %> <%= render 'form' %>
A partial for the form to create a story:
views/stories/_form.html.erb
<%= form_for @story do |f| %> <%= render 'shared/errors', object: @story %> <div class="form-group"> <%= f.label :title %> <%= f.text_field :title, class: 'form-control', required: true %> </div> <div class="form-group"> <%= f.label :body %> <%= f.text_area :body, class: 'form-control', required: true, cols: 3 %> </div> <%= f.submit 'Post', class: 'btn btn-primary' %> <% end %>
The
shared/_errors partial is referenced here, so we have to create it too:
views %>
And some basic styles:
application.scss
[...] .well { h2 { margin-top: 0; } } [...]
That was the easy part. Before proceeding let’s also set up authentication via Facebook.
Authentication via Facebook
Create a new file omniauth.rb inside the config/initializers directory with the following content:
config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], scope: 'public_profile' end
To obtain the Facebook key and secret, visit the developers.facebook.com page and create a new application (with a type “Website”). On the Dashboard page of the newly created app, find the “App ID” and “App Secret” (a password will have to be provided to display this one) – this is what you need. Note: The key pair should not be available publicly – I am using environmental variables to store it.
While on Facebook Developers page, navigate to the Settings page and click the “Add Platform” button, then select “Website”. Next, fill in the following fields:
- Site URL (if you are testing the app on local machine, enter “”)
- App Domains (if you are on local machine, leave this blank)
- Contact Email
Click “Save Changes”.
Lastly, navigate to “Status & Review” and toggle the “Do you want to make this app and all its live features available to the general public?” to “Yes”. Your app is now live and users may log in using it.
The
scope parameter specifies what actions to allow our application to perform. For this case, we only need to fetch basic information about the user that is logging in.
The next step is creating the controller that will handle log in and log out requests:
sessions_controller.rb
class SessionsController < ApplicationController def create user = User.from_omniauth(request.env['omniauth.auth']) session[:user_id] = user.id flash[:success] = "Welcome, #{user.name}" redirect_to root_url end def destroy session[:user_id] = nil flash[:success] = "Goodbye!" redirect_to root_url end end
request.env['omniauth.auth'] contains all the information about the user. The
User.from_omniauth class method needs to be created:
models/user.rb
class << self def from_omniauth(auth) user = User.find_or_initialize_by(uid: auth['uid']) user.name = auth['info']['name'] user.avatar_url = auth['info']['image'] user.save! user end end
We are storing the necessary information and returning the
user object as a result. The
find_or_initialize_by method will either create a new user or update an existing one if the
uid is already present in the database. This is done to prevent the same user being created multiple times.
And, lastly, the
current_user method that will return the currently logged in user or
nil:
controllers/application_controller.rb
[...] private def current_user @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id] end helper_method :current_user [...]
helper_method ensures that this method can be called from the views as well.
When you are done, boot up the server. Try to authenticate and add a couple of stories to check that everything is working. We are ready to move to the interesting part.
Integrating public_activity
public_activity‘s idea is quite simple: use callbacks to automatically store information about the changes that happen in the specified table. That information is then used to display all the recent activity. You might be wondering if it is possible to record activity without actually touching the table. Well, it is, and we will talk about it more in a bit.
For now, let’s do the basic setup. Run these commands:
$ rails g public_activity:migration $ rake db:migrate
This will generate and apply
public_activity‘s migration. A new table called
activities is created.
To enable tracking for the
Story model:
models/story.rb
[...] include PublicActivity::Model tracked [...]
Pretty simple, isn’t it? Now, whenever you perform actions such as
save,
update_attributes,
destroy, and others,
public_activity‘s callback will be fired to record that event.
This gem also supports MongoMapper and Mongoid adapters – refer to the Database setup section in the docs to learn more.
Displaying the Activity Feed
Let’s display the events. You may either create a separate page to display the activity feed or render it
on each page of your site. I’m going to stick with the latter option.
Tweak the controller:
stories_controller.rb
[...] before_action :load_activities, only: [:index, :show, :new, :edit] private def load_activities @activities = PublicActivity::Activity.order('created_at DESC').limit(20) end [...]
As you can see, the
Activity model is inside the
PublicActivity namespace to prevent naming collisions. We are ordering activities by creation date (the newest the first) and taking the first twenty of them. Read more here.
Our layout needs to be changed a bit so that the activity feed is being placed on the right side of the website:
views/layouts/application.html.erb
[...] <div class="col-sm-9"> <%= yield %> </div> <%= render 'shared/activities' %> [...]
views/shared/_activities.html.erb
<div class="col-sm-3"> <ul class="list-group"> <%= @activities.inspect %> </ul> </div>
For those who don’t know, Bootstrap uses a 12-column grid layout, so by specifying
col-sm-9 we are using 9 columns (75 % of the available space) for the main content.
col-sm-3, in turn, leaves 3 columns for the activity feed.
sm here means that columns will be displayed one beneath another (horizontal grid) on smaller displays. More information is available here.
Reload the page to check what the
@activities array contains and how it displays. To render an array of activities there is a special helper method
render_activities:
views/shared/_activities.html.erb
<div class="col-sm-3"> <%= render_activities @activities %> </div>
public_activity expects that there is a public_activity folder inside the views that, in turn, has a story folder (or any other folder with a singular name of the model that is related to the specific activity). Inside the story directory, there should be the following partials: _create.html.erb, _update.html.erb, _destroy.html.erb. Each partial, as you’ve probably guessed, is rendered for the corresponding action. Inside those partials there is a local variable
activity (aliased as
a) available.
Go ahead and create those files:
views/public_activity/story/_create.html.erb
<li class="list-group-item"> <%= a.trackable.title %> was added. </li>
views/public_activity/story/_update.html.erb
<li class="list-group-item"> <%= a.trackable.title %> was edited. </li>
views/public_activity/story/_destroyed.html.erb
<li class="list-group-item"> <%= a.trackable.title %> was deleted. </li>
The
trackable is a polymorphic association which has all the necessary information about the model that was modified.
There is a problem, however. If you create and then delete a story, you’ll see an error
undefined method 'title' for nil:NilClass. This is because the we are trying to fetch the title of the record that was deleted. It is easy enough to fix:
views/public_activity/story/_create.html.erb
<li class="list-group-item"> <% if a.trackable %> <%= a.trackable.title %> was created. <% else %> An article that is currently deleted was added. <% end %> </li>
views/public_activity/story/_update.html.erb
<li class="list-group-item"> <% if a.trackable %> <%= a.trackable.title %> was edited. <% else %> An article that is currently deleted was edited. <% end %> </li>
views/public_activity/story/_destroyed.html.erb
<li class="list-group-item"> An article was deleted. </li>
Pretty nice, but not very informative. When did the action take place? Can we navigate directly to the article that was modified? Who modified it? Well, the first two issues can be fixed easily:
views/public_activity/story/_create.html.erb
<li class="list-group-item"> <span class="glyphicon glyphicon-plus"></span> <small class="text-muted"><%= a.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> <% if a.trackable %> <%= link_to a.trackable.title, story_path(a.trackable) %> was added. <% else %> An article that is currently deleted was added. <% end %> </li>
views/public_activity/story/_update.html.erb
<li class="list-group-item"> <span class="glyphicon glyphicon-edit"></span> <small class="text-muted"><%= a.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> <% if a.trackable %> <%= link_to a.trackable.title, story_path(a.trackable) %> was edited. <% else %> An article that is currently deleted was edited. <% end %> </li>
views/public_activity/story/_destroyed.html.erb
<li class="list-group-item"> <span class="glyphicon glyphicon-remove"></span> <small class="text-muted"><%= a.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> An article was deleted. </li>
I’ve also added some Bootstrap Glyphicons so that everything looks a bit prettier.
Displaying information about the user responsible for the change involves a bit more work.
Storing Information About the User
There is a special field called
owner in the
activities table that is intended to store information about the user responsible for the action. The problem, however, is that the
current_user method is not available inside the model so we have to use a pretty hacky solution.
Tweak the controller:
application_controller.rb
[...] include PublicActivity::StoreController def current_user @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id] end helper_method :current_user hide_action :current_user [...]
Note that I’ve removed the
private keyword because otherwise we won’t be able to call
current_user from inside the model. Adding
hide_action :current_user makes sure that this method is not considered a controller action.
Now the model:
models/story.rb
[...] tracked owner: Proc.new { |controller, model| controller.current_user ? controller.current_user : nil } [...]
The procedure takes two arguments:
controller and
model. In this case, we only need
controller to call the
current_user method;
model stores the object that was modified.
With this in place, log in, add/change some stories and check the
activities table. The
owner field should be populated with user’s id.
The last step is modifying the partials:
views/public_activity/story/_create.html.erb
<li class="list-group-item"> <span class="glyphicon glyphicon-plus"></span> <small class="text-muted"><%= a.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> <strong><%= activity.owner ? activity.owner.name : 'Guest' %></strong> <% if a.trackable %> added the story <%= link_to a.trackable.title, story_path(a.trackable) %>. <% else %> added the story that is currently deleted. <% end %> </li>
views/public_activity/story/_update.html.erb
<li class="list-group-item"> <span class="glyphicon glyphicon-edit"></span> <small class="text-muted"><%= a.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> <strong><%= activity.owner ? activity.owner.name : 'Guest' %></strong> <% if a.trackable %> edited the story <%= link_to a.trackable.title, story_path(a.trackable) %>. <% else %> edited the story that is currently deleted. <% end %> </li>
views/public_activity/story/_destroyed.html.erb
<li class="list-group-item"> <span class="glyphicon glyphicon-remove"></span> <small class="text-muted"><%= a.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> <strong><%= activity.owner ? activity.owner.name : 'Guest' %></strong> deleted a story. </li>
Now, for the newly performed actions you will see your name displayed; for the previous ones there should be a “Guest” string provided instead.
Everything is working fine, but our partials contain a lot of duplication – actually, the code is nearly identical. So let’s spend some time refactoring it.
Using I18n Fallbacks to Refactor Activity Partials
I want to completely get rid of those activity partials and work only with the shared/_activities.html.erb file. You should know, however, that there are some other possible solutions.
The basic structure of the partial will be as follows:
views/shared/_activities.html.erb
<div class="col-sm-3"> <ul class="list-group"> <% @activities.each do |activity| %> <li class="list-group-item"> <!-- render activities here --> </li> <% end %> </ul> </div>
It appears that only two things in the activity partials are different: the icon and the text saying what happened to the trackable object.
The issue with the icon can be easily fixed using regular expressions and some Sass magic:
views/shared/_activities.html.erb
<div class="col-sm-3"> <ul class="list-group"> <% @activities.each do |activity| %> <li class="list-group-item"> <span class="glyphicon glyphicon-<%= activity.key.match(/\.(.*)/)[1] %>"></span> </li> <% end %> </ul> </div>
The
key fields contains the string in the form of
so for example in our case it might be
story.create,
story.update or
story.destroy. Of course, Bootstrap applies no styles to classes like
glyphicon-create but it can be easily changed:
application.scss
.glyphicon-update { @extend .glyphicon-edit; } .glyphicon-create { @extend .glyphicon-plus; } .glyphicon-destroy { @extend .glyphicon-remove; }
We are employing Sass’
@extend directive to apply the styles to our new classes.
The issue with the text can be solved with the help of fallbacks. As we’ve already seen,
public_activity by default will search for the partials inside the public_activity/
display: :i18n option, I18n translations will be used instead.
The structure for those translation look like:
activity: model_name: create: '...' destroy: '...' update: '...' other_action: '...'
This way, we are also solving the possible internationalization problem that might arise in the future.
The partial contains the following code:
views/shared/_activities.html.erb
<div class="col-sm-3"> <ul class="list-group"> <% @activities.each do |activity| %> <li class="list-group-item"> <span class="glyphicon glyphicon-<%= activity.key.match(/\.(.*)/)[1] %>"></span> <strong><%= activity.owner ? activity.owner.name : 'Guest' %></strong> <%= render_activity activity, display: :i18n %> <% if activity.trackable %> "<%= link_to activity.trackable.title, story_path(activity.trackable) %>" <% else %> with unknown title. <% end %> </li> <% end %> </ul> </div>
Here the
render_activity helper method is used – its alias
render_activities we saw previously.
Now the translations file:
config/locales/en.yml
en: activity: story: create: 'has told his story' destroy: 'has removed the story' update: 'has edited the story'
The previously created public_activity folder may be removed completely.
This will only work, however, for a single trackable model. For multiple models you will have to create the corresponding partials. It is possible to create a separate layout (which actually is yet another partial) for your activities. Here is a demo app created by the author of
public_activity that uses a layout to render activities.
Create Custom Activities
Until now, we only worked with the basic CRUD operations that caused activities to be saved automatically. But what if we wanted to track some custom events? Or if there is a need to trigger an activity without touching the model?
Not to worry, this can be done quite easily. Suppose we want to add the “Like” button and count likes for each post. Moreover, a special activity should be recorded, too.
First of all, we need to add a new column to the
stories table:
$ rails g migration add_likes_to_stories likes:integer $ rake db:migrate
Now the new route:
config/routes.rb
[...] resources :stories do member do post :like end end [...]
Add the “Like” button to the view:
views/stories/show.html.erb
<% page_header @story.title %> <p> <span class="label label-default"><%= pluralize(@story.likes, 'like') %></span> <%= link_to content_tag(:span, '', class: 'glyphicon glyphicon-thumbs-up') + ' Like it', like_story_path(@story), class: 'btn btn-default btn-sm', method: :post %> </p> [...]
And the controller action:
stories_controller.rb
before_action :find_story, only: [:destroy, :show, :edit, :update, :like] [...] def like @story.increment!(:likes) @story.create_activity :like flash[:success] = 'Thanks for sharing your opinion!' redirect_to story_path(@story) end [...]
@story.increment!(:likes) just adds
1 to the likes and saves the result to the database.
@story.create_activity :like actually creates a new activity by providing the
like key (we’ve talked about keys before when refactoring partials). This will require us to modify the translations file:
config/locales/en.yml:
en: activity: story: like: 'has liked the story' [...]
If you are dealing with partials instead, then you’ll have to create the views/public_activity/story/_like.html.erb partial.
The
create_activity method is called to trigger a custom activity – it does not require a model change.
We are not done yet, however. There is one problem that will allow me to show one more feature of
public_activity – disabling model tracking. You see, the
@story.increment!(:likes) code fires an update which causes
public_activity to record an update event. So,
@story.create_activity :like will result in recording two activities for one action. This is obviously not what we want. The first operation should be done without any tracking at all.
public_activity allows disabling tracking globally or for a specific model. For global disabling, use
PublicActivity.enabled = false
To disable tracking on model’s level use
Story.public_activity_off
We are going to employ the latter solution, as the first one is obviously overkill:
stories_controller.rb
def like Story.public_activity_off @story.increment!(:likes) Story.public_activity_on @story.create_activity :like flash[:success] = 'Thanks for sharing your opinion!' redirect_to story_path(@story) end
This can be simplified further:
stories_controller.rb
def like without_tracking do @story.increment!(:likes) end @story.create_activity :like flash[:success] = 'Thanks for sharing your opinion!' redirect_to story_path(@story) end private def without_tracking Story.public_activity_off yield if block_given? Story.public_activity_on end
Now the increment operation will not cause the
update activity to be triggered. Great!
Saving Custom Information
Suppose we want to store some additional information about the activity. How could we do this?
public_activity presents two ways to achieve the desired result. First of all, there is the serialized
parameters field present in the
activities table that we can access right away:
@story.create_activity :like, parameters: {why: 'because'}
Later, we can access this information, like so:
activity.parameters['why']
This is not always convenient, however. If you need some data to be saved for each activity, this approach requires calling
create_activity for each action.
For other scenarios, there are custom fields available. Let’s, for example, store the title of the story so that we can fetch it even if the story is later deleted.
The setup is very simple. Create a new migration:
xxx_add_title_to_activities.rb
class AddTitleToActivities < ActiveRecord::Migration def change change_table :activities do |t| t.string :title end end end
and apply it:
$ rake db:migrate
And now tweak the model like this:
models/story.rb
[...] tracked owner: Proc.new { |controller, model| controller.current_user ? controller.current_user : nil }, title: Proc.new { |controller, model| model.title } [...]
Let me remind you, that
model stores the object that was changed.
And now we can display this title in case the model is destroyed:
shared/_activities.html.erb
<div class="col-sm-3"> <ul class="list-group"> <% @activities.each do |activity| %> <li class="list-group-item"> <span class="glyphicon glyphicon-<%= activity.key.match(/\.(.*)/)[1] %>"></span> <small class="text-muted"><%= activity.created_at.strftime('%H:%M:%S %-d %B %Y') %></small><br/> <strong><%= activity.owner ? activity.owner.name : 'Guest' %></strong> <%= render_activity(activity, display: :i18n) %> <% if activity.trackable %> "<%= link_to activity.trackable.title, story_path(activity.trackable) %>" <% elsif activity.title %> <span class="text-muted">"<%= activity.title %>"</span> <% else %> with unknown title. <% end %> </li> <% end %> </ul> </div>
Conclusion
I’ve shown you nearly all the features provided by
public_activity – hopefully you will use it one of your future projects!
Have you ever implemented the similar activity feed? Which tools did you use? Share your experience! As always your feedback or article requests are very much welcome.
Happy hacking!
Good stuff! As someone who has built and worked with activity streams for years, I will say this is a good start. One thing I would suggest looking at is the Activity Streams protocol specification -. This provides a standard data format for activity stream data that can then be used with any standardized activity streams tool.
Once you start to move beyond simple streams - e.g. to add different types of activity, enable commenting, and especially allow following and building of feeds, it's my belief that you shouldn't try to build it yourself. It starts to get very complex to enable that level of functionality and maintain any kind of performance. I actually built a company around solving this problem - it's called Collabinate (). We provide an API that allows you to build streams for any object in an application, manages the relationship of followers to streams, lets you pull back feeds in real time, enables likes and comments, utilizes the Activity Streams protocol, and does it at huge scale if necessary (billions of objects). We should talk some time if you're interested in learning more about it.
Thanks again for the article!
Thank you!
Your service seems like a nice solution - I may be interested in writing an article about it. Could you contact me via e-mail ( - e-mail and some other contact options are listed here) if that suits you?
Good stuff..
Anyway, I checked your github apps for this tutorial, seems there is folder public_activity for the view.
A bit confused about that.
Thanks
Sorry, didn't quite understand. I have no such folder: because I am sticking with I18n for this demo.
Yeah, sorry my bad, I did not read it carefully. So I found out you deleted that because of using the I18n.. Cool stuff. Thank you very much.
Btw, is is possible to make it to more than 1 model ? like 2-3 models?
Thanks
By the way, I have couple of questions
First one, if you have 2 users type (user and admin) how do you set the owner?
Second, how do you filter them on the render activity or the view?
and lastly, this is applicable to many models?
Thanks
Nope, with more than 1 model you will have to use partial views like described here:
You will want to tweak this
and this code
accordingly. Just more checkings come into play - you also check if the person is logged in as admin.
By the
ownerfield, if I understood the question correctly. It has the polymorphic association () and you can use it for find only activities for admin or user for example.
Of course, multiple models may be used. Just remember to use partials, not I18n fallbacks.
Okaaay
I have tried to play around this. Seems pretty good.
Thank you very much for your time
cheers
I am big fans of you
Oh, thank you for kind words! Don't hesitate to contact me if anything else will seem unclear.
AWESOME article! Really gave me a great grasp on the activity_feed. Is there a way to 1) limit liking to one time per post so that if you click on "Like it" a second time it unlikes it, like Facebook 2) show names of likers next to like button so you know who is liking it without having to scroll down the activity feed? Might be a nice expansion to your wonderful tutorial because I can't find these answers anywhere!
Thank you!
1&2. Of course that is possible, but this is not related to activity feeds so I did not consider add such info to the currect article. However I think that is a nice suggestion for a new topic so I'll probably work on this in some time, maybe expanding a bit further. It is really great to receive so many feedback! | https://www.sitepoint.com/activity-feeds-rails/ | CC-MAIN-2017-51 | refinedweb | 4,938 | 51.34 |
In this tutorial you will see how to create a Web Service with WebMatrix and a Windows 7 Phone App that will consume your Web Service. Microsoft WebMatrix is a free tool that allows you to create, customize and publish web sites on the Internet.
This may sound like a daunting task but with WebMatrix and the Windows Phone Developer Tools, this task can be easier. WebMatrix makes it easy to create websites and web services. Before you start, you must download and install WebMatrix and the Windows Phone Developer Tools.
If you are having problems installing WebMatrix, step by step instructions can be seen in Getting Started with WebMatrix. Steps for downloading and installing the Windows Phone Developer Tools can be seen later on in this article.. The "new" button on the menu ribbon allows us to create new folders and files for our website.
Since we are creating a web service we will need to create a class that will supply data. Similar to ASP.NET, the App_Code folder contains classes. Since we chose to create an Empty Site, our site does not contain an App_Code folder. Certain templates come with this folder but the Empty site template does not. Create a new folder and name it App_Code.
Any file in our App_Code folder can be accessed by FileName.FunctionName(Parameters). This means that we can create functions in our class and can call them in other files.
One of the ways to use a Web Service is to pull data from a database. Our Web Service will retrieve information from our database. Before we can write this code, we must first create our database. One of the nice things about WebMatrix is the fact that we can create and insert data into our database, all within WebMatrix.
Creating a WebMatrix is easy. Click the "Database" workspace on the lower left of WebMatrix. Here you can manage your databases or create new ones.
Once in the Database Workspace, you can create a new database by clicking the "new database" button on the menu ribbon or by clicking the "add database to your site" link in the middle of the page.
WebMatrix will create a new database for you with the same name of your website. This database can be seen in the files explorer on the left.
Now that we have our database set up, we can create a new table. On the menu ribbon, select "new table." If the icon is not able to be selected, make sure the database is selected on the left.
If you have any prior experience with databases, you may know the best practices for structuring your tables. For this tutorial, we will be using a simple Product table with three columns: id, name, and price.
Click the "new table" icon. Here we can enter our table's columns. The first column we need to make is the id column. Since it's not really necessary to have an id in such a basic table, you do not have to include this but it is best practice to include ids.
After you've added the id column, add a Name column and a Price column. Name should be an nvarchar and Price should be an int. When you've added all of your table columns, you database table should look similar to this.
Save your table and give it a meaningful name. Your table will appear on the left under your database.
Now we can add data to our database. You can either double click on the table on the file explorer, or if your table is still open, you can click the "data" icon on the menu ribbon. Either method will take you to your empty table.
Here you can enter information into your table. Once you're done, your table should look similar to this.
Now that we have our database with our product table and data we can get started writing our web service code. Click the "files" tab on the lower left to get back to your files workspace.
A web service is a communication between two different devices. One device sends a request to the other device and receives a response. The device then uses the received response to do something. This request is done in the form of an url. This url consists of the web services' address and parameters to request certain information from the service. Services can be based on XML or Json responses. For this tutorial we will be dealing with Json responses since WebMatrix has a nifty built in Json encode and decode helper.
Our Web Service will consist of two different .cshtml files. One file, which will go into our App_Code file, will contain our class and function that retrieves data from our database. Our other file will be the file that will receive the web request and will return the information. This file will call our function from the other file. This may sound kind of confusing but it will become more clear as we go along.
Firstly, we need to create our class and function. Make sure your App_Code folder is selected and create a new .cshtml file.
With your new file open, remove all of the <html> tags. These are not needed in our file. Add to your now empty file:
@functions {
}
This is the way to signify that this code contains functions with Razor code. Code between these {} brackets will be treated as a class or function. Now let's add our class. Our web service is going to get information about a product from our database. This means that we should create a Product object. Since our database is super simple, our product will only have 2 attributes: name and price. We can create a very simple, succinct Product class in our file. Within the @functions {} brackets, add:
public class Product {
public string Name {get; set; }
public int Price {get; set; }
}
Now that we have our Product object, let's create our function that the requests product information from our database. This function will open our database, query our database, and place the information from our database into our product object. We then return our product object.
Add to between @functions{}:
public static Product GetProducts(string price) {
var db = Database.Open("WebService");
var selectQueryString = "SELECT Name, Price FROM Products WHERE Price >= " + @price;
var data = db.Query(selectQueryString);
Product product = new Product();
foreach (var row in data) {
product.Name = @row.Name;
product.Price = @row.Price;
}
return product;
}
We must loop through the rows in our sql response in order to place our values into our product object. If we don't then we are simply returning an empty Product object. Also, you cannot implicitly convert a sql statement into a product. Looping through the response allows us to capture the row values and place them into our product object.
Now that we have our product class and getproduct function, we can write the code that will deal with the web request. Having our function call in this page will allow users to make requests to the file's url.
One important thing we need to do in this file is to convert our product object into a format that can be consumed by other devices, especially a Windows 7 Phone application. We can do this by calling our getproduct method which returns our product object. We can then use WebMatrix's json helper to encode our product response to a json format and print it out on our webpage. You may have noticed that our getproduct function takes in a string parameter of price. This means that we must supply a price variable or we will not get any results.
Create a new .cshtml file in the root folder of your website. You can take out all of the default html code. Add to your file:
@{
var price = Request.QueryString["price"];
if (price == null || price == string.Empty) {
<p>Please enter a Price value</p>
} else {
var product = getProduct.GetProducts(price);
Json.Write(product, Response.Output);
}
}
The price variable will contain the requested price in the url. There is code to handle a missing price variable so our code will compile properly. This means that if the price variable is not supplied, the user will receive a message instead of an error page. If a price is supplied, we call our getproduct function with our price variable and store the return product object into a variable. We then use the WebMatrix json helper to encode our product object to the json format and print it to the page. We could use the json encode method but since we want to encode and write to a response stream, we can simply use the Json.Write method. If another device makes a request to our page they will receive a json formatted string which can be decoded.
Now that we have our simple web service, we can either make requests in the browser to this page or we can use another device to make requests. First, let's try out our service in the web browser to make sure it is working properly. Run your file by clicking "run" on the menu ribbon. Because we are running it this way, we won't be supplying a price variable. Our page should display our error message.
Now we can add our price variable by adding ?price=number. If I were to enter then my page should print out the json object.
Now that we have our web service working we can begin working on our Windows 7 Phone application.
Microsoft offers some great resources to get started on developing Windows 7 Phone applications. For this tutorial we will be using the Visual Studio 2010 Express for Windows Phone software. This can be downloaded for free at create.msdn.com/en-US.
create.msdn.com/en-US Also offers great resources on getting started developing phone applications. If you are an absolute beginner it provides a wonderful set of videos to get your orientated with the software and coding for a phone application. I strongly suggest checking out some of these videos before you continue on with this tutorial as we use some of these concepts.
To download the development tools, click the three links near the middle of the page on the create.msdn.com/en-us/home/getting_started page. Listed here are the three different downloads you must complete in order to use the software package.
Clicking on the first link you will be asked if you wish to run or save the file. Choose to run it.
Next you must agree to the license terms. Click the "accept" button.
Once you agree you will be asked to install now or customize the installation settings. Choose "install now."
The software will begin installing. This may take more than a couple minutes.
Once that is completed you will need to install the January 2011 Update. A dialog will pop up. Once it is finished downloading it will close automatically.
After that is done you must download and install the Windows Phone developer tools fix. Clicking the link will open the installation wizard. Click the "next" button to continue.
You will be once again asked to agree to license terms. Select the check box and click the next button. You will not be able to continue on until the box is selected.
The tools fix will begin installing. This also may take up to a few minutes to complete.
You will be notified once the installation is complete. Click the "finish" button to close the installation wizard.
With all these components installed we are now ready to begin working on our Windows 7 Phone application.
Now that we've easily created our web service, let's see how easy it is to create a phone application that consumes this service. Silverlight has a class called WebClient that allows use to easily make HTTP requests and receive responses. We can then use the DataContractJsonSerializer class to decode our web response. But, before we write our code behind, let's add some elements from the toolbox to our phone application.
First things first, open Visual Studio 2010 Express for Windows Phone and create a new Windows Phone Application project. Give your project a name and hit ok.
You will now have a new phone application project. Your project .xaml file will be open. This is the front facing code of your project. A nice thing about this software is that you can click and drag elements from the toolbox onto the windows phone. This way you can add, edit and remove features on your application without having to write the code for it.
Let's give our application a title. To do this we can remove the "page name" text and add our own. To do this click on the page name text. This will select the textblock that contains the text.
With the textblock selected, we can now change the text. You can change the text in the properties window.
Now let's add some elements to our application. Let's add a text block, a text box, a button, and another text block. You can have these arranged any way you wish on your phone. We will use the first text block to print some text instructing the user what to do. We will use the text box as a way for the user to enter input. We will use the button to fire an event when it is clicked by the user. We will use the last text block to print out our json web response that we have decoded. With all these elements on your phone, it should look similar to this:
Now that we have all the elements we need, let's create some code behind. First, let's add our event when the button is clicked. You can quickly do this by double clicking on the button. This will open the open behind and make the button event for you. Your code behind can be found in the .xaml.cs file of your project.
Since we are going to use a stream object as well as the json serializer class, we need to add these namespaces to our project. To use the json serializer we need to add a reference to our application as well as the namespace. To do this, right click your application root in the solution explorer on the right. Select "add reference" on the menu.
Clicking add reference will open a pop up box with all the different references that we could add. Choose the System.Servicemodel.Web option. Click ok to add the reference to your application. If you were going to use XML instead of json you would use the System.Runtime.Serialization reference.
All of there references in your application can be found under the "references" folder in the solution explorer. Now let's add the namespaces to the top of our code behind file. Add to your file:
using System.Runtime.Serialization.Json;
using System.IO;
Now let's add our web request code. Firstly, let's add our WebClient as a global variable. At the top of the page, directly after public partial class MainPage : PhoneApplicationPage {, add:
WebClient productClient;
Now we have our WebClient as a global variable but we still need to initialize it before we use it. We could place our WebClient in our page so it made the request as soon as the page loaded but since we want to add user input to our web request, we should make our request on the button click event.
Add the following code to your button_click event:
public void myButton_Click(object sender, RoutedEventArgs e)
{
int num;
if (myTextBox.Text != string.Empty && int.TryParse(myTextBox.Text, out num))
{
string price = myTextBox.Text;
productClient = new WebClient();
productClient.OpenReadCompleted +=
new OpenReadCompletedEventHandler(productClient_OpenReadCompleted);
GetProduct(price);
}
else
{
myTextBlock.Text = "Please enter a valid price. This number should be an integer.";
}
}
Our code first checks if the button was clicked and the text box was empty. If the user did not enter text into the box before clicking the button, our second text block will prompt the user to enter a price. If they did enter text and the text was an integer (we use the TryParse method to check this), then we place the text they entered into a variable. We then initialize our WebClient. We also attach an event handler to our OpenReadCompleted event. We do this so that we can make our web request without blocking the rest of the application. This is a good practice to use in case your web request runs into an error. When our request is completed our event handler will be called. We then call the method that makes our web request. Let's add that method now.
private void GetProduct(string price)
{
string requestUri = "" + price;
Uri uri = new Uri(requestUri);
productClient.OpenReadAsync(uri);
}
Our GetProduct method creates a string that we will use as our request uri with the value the user has entered into the textbox. We then create a uri object with our request string. With our request uri assembled we make a class to the OprenReadAsync method of our webclient object.
We now need to write our OpenReadCompleted method that we called earlier in our code. This method is where we will receive our web response, deserialize our json response and print out our response to our second textblock. Add to your page:
void productClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
myTextBlock.Text = "An Error Occurred";
return;
}
var serializer = new DataContractJsonSerializer(typeof(Product));
var s = (Product)serializer.ReadObject(e.Result);
string name = s.Name;
string price = s.Price;
if (name == null)
{
myTextBlock.Text = "There is no product with a price equal or greater than " + myTextBox.Text;
}
else
{
myTextBlock.Text = "Our " + name + " is $" + price;
}
}
The first thing we check in our method is whether we received any errors during our web request. If we ran into an error, we print an error message in our textblock. If all went well with the web request we can deal with our response. We first create a new DataContractJsonSerializer with the type of set to a Product object. You may be getting red squiggly lines under this part of your code because we haven't added our Product class yet. This class will be the same class that we had in our WebMatix code. We will add this next. We then use our serializer to read and decode our json web response, which we store into a variable. We then set the name and price variables of our Product object equal to the information we received from our web response. We next check if we actually received valid data from our response. If the user enters a number that doesn't match any of our database data, our web response will return an empty name and a price equal to 0. We can easily check if this was the case. If it is true, we print out a message to our textblock. If our response contained good information we then print out our information to our textblock.
The last thing we need to do is add our Product class. This is really simple to do. Add to your file:
public class Product
{
public string Name { get; set; }
public string Price { get; set; }
}
That's it! That's all the code we need to consume the web service we created with our WebMatrix application. Let's debug our phone app to make sure it is working properly. Make sure "Windows Phone 7 Emulator" is select on the toolbar. To run your app click the green triangle.
Your app will now run. The Windows 7 Phone Emulator will open. If it is not already open it make take a minute or two before it's ready. The Emulator acts as if you are using your live app.
You can submit a blank textbox, enter a string, or enter a number to see if your app is working properly. You should see the corresponding message to whatever action you choose. If we were to enter 9 then our app would look like this:
So that's it. We successfully create a web service with WebMatrix and created a Windows 7 Phone application that consumes our web service. Although this was a very simple approach, understanding the fundamentals is important to creating bigger, more complex applications.
Download webmatrix
Learn how to Download and Install WebMatrix
Learn more
Create a website with a WebMatrix site template
Publish your website
Learn to download, edit and republish your website
Learn more about Windows Phone development
You can discuss this article using the adjacent Facebook talkback.
For technical questions please visit our discussion
forums,
where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to
answer your questions! | http://www.microsoft.com/web/post/creating-a-webservice-with-webmatrix-and-consuming-it-with-a-windows-7-phone-application?category=How-To | CC-MAIN-2015-11 | refinedweb | 3,505 | 74.29 |
.
Advertisement
Get truth delivered to
your inbox every day.
If you have trouble leaving a comment, review this help page. Still having problems? Let us know. If you find yourself moderated, take a moment to review our comment policy.
By drbhelthi, October 20, 2011 at 2:58 am Link to this comment
@ ofersince72
Comprehensive summary.
Who are the owners of the “Federal Reserve”?
By steve, October 18, 2011 at 5:33 pm Link to this comment
(Unregistered commenter)
I have been subject to Gang Stalking, and they seems to know my location and hear my conversations. I believe is through phone, but is it possible when speaking at vicinity of any phone cell or landline the conversation could be picked up? In case of my phone I could take the battery out.
By lefty avenger, October 14, 2010 at 11:22 am Link to this comment
(Unregistered commenter)
Sounds like the tale of two cities.
By ofersince72, August 29, 2010 at 2:18 am Link to this comment
Cris, why do you always beat around the bush?
Let me explain real short for you, Progressive Democrat.
“Yearning For Facism” ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Obama can’t stop social security reform, or really
can’t do much of anything else either. Cris, we don’t
own this country anymore. The ones that hold our national
debt now own this country and dictate policy, which
the lawmakers and the president have to follow. Pretty
much like what the World Bank and the IMF did to all of
the Latin American countries, and all of the Central
African countries, and many Asian countries, get them all
in debt, then dictate policy. It really doesn’t matter
if Barrack Obama, or Sara Palin is president, or if we
have a Democrat or Republican Congress, it is going to be
the same. This really amusing media game is all for show
and I really didn’t believe that I would have to explain
it to Cris Hedges, former New York Times Journalist.
So keep pretending that Rachael and Keith, and Stewart
and Colbert are our friends, keep pretending that
General Electric and Viacom are nicer than Murdock and
keep pretending that the airwaves aren’t 100% controlled,
and keep pretending that all the non-issues of fear politics are real issues. Go ahead Cris. Keep pretending
that all of the Sunday morning political talk shows are
meaningful discussions if it makes you feel better.
Keep pretending that the Palin and tea baggers Glen Beck
show isn’t contrived by all the media whores and MSMs
if it makes you and your so called Progressive Democrat
followers be able to have condescending attitudes or the
haughtiness that some seem to have by holding on to this
stupid belief perpetuated by the media whores.
But the bottom line is Cris, none of this matters, we
don’t own this country anymore, that is why we can’t stop
the wars…..
It is not our military…..we just pay for it
It is not Congress’s military….they just appropiate $$$
It is not the president’s military…he just gets a title.
It belongs to the ones that are profiting from these
military adventures and military industrializations, and
they are also the ones that own a good portion of our
debt. So we will have the 1984, perpetual war..didn’t
you get it??? So there is no YEARNING…cris.
Now, go read The Times, the WAPO , and watch all the
MSMs so you might be the most informed person in the world. And don’t believe for a minute that they are
making non-issues, issues.
GOD BLESS AMERICA.
FROM THE RADICAL LEFTY LIVING IN THE “SHOW ME” STATE.
By Steven, July 24, 2010 at 10:58 pm Link to this comment
(Unregistered commenter)
@99: Well, based on evidence I’ve seen I have to
disagree with you on 2 things:
1. Most the foaming far leftists, as well intentioned
as most of them may be, are unfortunately being used
as nutty pawns of a sort{or at least most of them
are}.
2. But as for the rabid far right? The elites don’t
hate them, no, in fact, they LOVE them. Why?
A. They make up the majority of the troublemaking
groups. Organizations like the ‘Aryan’ Nations, ‘The
Order’, ‘Christian’ ‘Identity’, ‘Phineas’ Priesthood,
NSWPP, even the old-as-the-f***ing-hills KKK and
Jewish Defense League, have ALL played a role in the
elitist network.
B. Has anybody ever noticed that the far right has
infiltrated certain sectors of our government? Not
just the police or National Guard. I’m talking about
a SERIOUS of compromisation here; it has even gone up
all the way to the level of the FBI, CIA, and even
our National Security Agency. I am NOT kidding,
folks, it is THAT bad.
C. I’m sure a lot of you folks have noticed the
destruction of many of our liberties in the past 10
years….........here’s a little tidbit: evidence has
come out that the 1968 gun control act intro’ed by
then Sen. Tom Dodd{D-CT}, may have been inspired by a
German law that had been approved…......in 1938.
D. And finally; they’ve even infiltrated the 9/11
Truth movement….........
People you should watch out for include:
Eric Hufschmid, Jimmy Walther, Chuck Baldwin, Mike
Delaney, and Texe Marrs, and many, many others.
That’s it for now, folks, but I hope I have brought
some additional insight into just how serious and
grave our problems really are.
Some websites that I’ve come across that appear to be
genuinely for the exposing of crimes in general are:
spitfirelist.com{Dave Emory’s website. Very good
information all-around for the most part, and you can
get a few free e-books, too! }
take-over-world.info{HUGE respository of stuff you
can download, and LOTS of good info about 9/11,
Israel/Palestine, fascism, etc.}
ifamericansknew.org{Definitely a good website if
you’d like to take an alternative look at the
Israel/Palestine conflict}{Another great site}
And finally, maebrussell.com{This website is what got
me started learning the truth….......sadly, I had
spent the past 2 years believing all sorts of disinfo
and believe me, it isn’t fun to learn you were
screwed with. Mae Brussell was THE very first person
to have a truly alternative radio show….......about
25 years before Alex Jones, in fact! Simply, the
creme de la creme; the best of the best, in my humble
opinion}
Thanks for your time, everyone…..........and good
night. .
By Go Right Young Man, May 2, 2010 at 4:01 am Link to this comment
1. Still no violence and almost no arrests attributed to the Tea Party protesters.
2. Last week, police had to clear Lafayette Park across the street from the White House because DADT protesters became so rowdy.
Obviously Hedges, Robinson and ITW have their collective heads up their ideologies.
By Go Right Young Man, April 28, 2010 at 3:40 am Link to this comment
I’ve been warning for months that denigrating the Tea Party protesters is a monumental mistake.
In place of simply and respectfully listening to protesters most in the media and the democratic party have accused the protesters of being loons, racists, Nazi’s and dangerous. Here’s the problem. Many of these protesters are “independent voters”. In other words; the people who actually decide elections!
Last week’s Pew Poll holds plenty of bad news for all in the congress.%.
I will say it again. Denigrating these protesters is a monumental mistake. Listening would have been much simpler and less costly.
By drbhelthi, April 25, 2010 at 11:35 pm Link to this comment
Hear, Hear !!!
Nor will the election of a ½ Negroid person to the US presidency,
via world-wide sympathy for the abuse of the Negroid race by
English-German-Spanish-heritage, USA politicians, bring about the
needed change.
Nor will Genocide of Middle-East Moslems, via israeli-dictator and
CIA control of the US military and US politics accomplish the
desired goal.
Nor will the CIA manipulation of bankruptcy in Greece, with the
attempt to pull-in Germany and bankrupt the EURO also, accomplish
the desired change.
Nor will Mrs. Angela Merkels sucking-up to the Obama-CIA-agenda,
and speeding up the collapse of the EURO and the EU, accomplish
the desired goal.
The desired goal will be accomplished only via the practice of the
Christian belief, not the “fronting” of the belief while practicing
satanism.
By Boyd, April 25, 2010 at 12:56 pm Link to this comment
to
overturn the stalls of these buyers and sellers of
spiritual fraud. The prayer that God will gladly hear
is the one that crucifies our false prosperity built
on the exploitation of those little ones whose deaths
we casually encompass for the sake of our SUVs..
By ScottSchneider, April 23, 2010 at 3:58 pm Link to this comment
After today’s enactment of Arizon’s Anti-Immigration Law, the wisdom of Chris’s warning is perhaps clearer:
By J. C. Sweet, April 13, 2010 at 7:25 am Link to this comment
(Unregistered commenter)
Mr. Hedges:
Let me paraphrase Benito Mussolini, leader of the first modern Fascist State: Fascism is, a corporate capitalist political economy supported by state militarism. Sound Familiar?
By Go Right Young Man, April 12, 2010 at 6:12 pm Link to this comment
Another of the myriad of examples of violence
and/or intolerance so many are frightened of?
-
“Gov. Bobby Jindal’s chief campaign fund-raiser
is recovering from injuries she suffered in a
Friday night altercation with a group of people
after a Republican fundraiser in the French
Quarter, the governor’s office said Monday.”
“Allee Bautsch suffered a broken leg and her
boyfriend suffered a concussion and a fractured
nose and jaw in the incident.”
By Go Right Young Man, April 10, 2010 at 12:20 pm Link to this comment
ITW,
LOL…you have forgotten that I called BULL**** first.
Why is it that you keep insisting I MUST produce links to incidents I have described, yet you continue to offer no assistance in locating the incidents you have repeatedly described?
I have repeatedly, written that I have failed to locate any evidence that Tea party protesters have used the terms “Nigger” and “fagot”. You insist it happened but have been unable to produce, or even direct me toward, anything tangible.
Why continue to demand of me what you refuse to do yourself? Just wondering.
By Go Right Young Man, April 10, 2010 at 12:07 pm Link to this comment
ITW, - “What strikes me as odd is you won’t post links”
I’m sorry, however, you’ll have to do it yourself. I’m done putting in the time others won’t take themselves. No offense toward you personally.
Query: John Kerry+bill Maher.
You’ll find the “Bulls***” I’ve been writing about on the first results page of any search engine of your choosing.
Post Script. Your being unaware of a situation does not make it “Bulls***” It only makes you unaware.
By Inherit The Wind, April 10, 2010 at 10:12 am Link to this comment
What strikes me as odd is you won’t post links, and you’ll NEVER find the evidence you’re looking for on Fox’s web sites.
I’m STILL waiting to see the link proving John Kerry advocated killing a US President. I call “Bulls***” and say “Prove it!”
By Go Right Young Man, April 10, 2010 at 6:27 am Link to this comment
More to the point of the Hedges article, and just for chuckles, try querying the following: Clinton+Fascism or Bush+Fascism or Carter+Fascism or Truman+fascism.
There is nothing new under the sun, my friend. Only bias, short sighted, myopic journalism.
In light of what you find. How is Chris Hedges’ or Eugene Robinson’s opinion pieces anything new? How is today’s “Hate Speech” deserving of being unequally or uniquely frightening or appalling?
And I can find no verifiable evidence that today’s protesters have used the words Nigger or Fagot. All I’ve located are numerous accounts of the same three (3) people making claims about a single incident after more than a year of protests. Does this not strike you as somewhat odd?
By Go Right Young Man, April 10, 2010 at 6:01 am Link to this comment
ITW, _ “I have not heard about an arrest for the threat against Cantor’. - ‘Nor have I heard about LEFTIST protesters burning Obama in effigy, nor about flag-burning since, oh, George Bush was President—the ELDER George Bush.”
-
Any Search engine of your choosing.
Query: Threats against Cantor
Query: President Bush burned in effigy
Query: President Clinton burned in effigy
Query: John Kerry+bill Maher
Query: Gabriel Range: Death of a President
Query: Google Image: Bush+Nazi
Query: Kill Bush
Query: Hate Bush or Hate Clinton or Hate Reagan or Hate Carter.
The most recent DNC talking point is the sudden danger of new right-wing violence, and the inflammatory push-back against health-care. I’m sorry, but all this concern is a day late and a dollar short. The subtext is really one of class — right-wing radio talk-show hosts, Glenn Beck idiots, and crass tea-party yokels are foaming at the mouth and dangerous to progressives. In contrast, write a book in which you muse about killing George Bush, and its Knopf imprint proves it is merely sophisticated literary speculation; do a docudrama about killing George Bush, and it will win a Toronto film prize for its artistic value rather than shock from the liberal community about over-the-top discourse.
Socialism and totalitarianism are tough charges from the hard right, but they seem to me about as (or as not) over-the-top as Al Gore screaming “digital brown-shirts” or John Glenn comparing the opposition to Nazis. When 3,000 were murdered in Manhattan, and Michael Moore suggested Bin Laden had wrongly targeted a blue state, I don’t think that repulsive remark prevented liberal politicians from attending his anti-Bush film premiere. Yes, let us have a tough debate over the role of government and the individual, but spare us the melodrama, the bottled piety, and the wounded-fawn hurt.
Like it or not, between 2001 and 2008, the “progressive” community redefined what is acceptable and not acceptable in political and public discourse about their elected officials. Slurs like “Nazi” and “fascist” and “I hate” were no longer the old street-theater derangement of the 1960s, rhetoric.”
By Inherit The Wind, April 9, 2010 at 1:38 pm Link to this comment
GRYM:
I’ve said it before: Violence against our elected officials is a CRIME and needs to be treated as such. I have not heard about an arrest for the threat against Cantor. I did hear about the bullet hole, but it was due to some a-hole randomly firing a gun into the air.
Nor have I heard about LEFTIST protesters burning Obama in effigy, nor about flag-burning since, oh, George Bush was President—the ELDER George Bush.
By Go Right Young Man, April 9, 2010 at 6:58 am Link to this comment
I know I said that you would get the last word, however, more information has come to light.
Apparently threats against congress has risen 40% of late. Of course the -always liberal all the time- Washington Post neglected to quote the Sargent at Arms saying that these threats, while mainly concerning the new Health-Care legislation, appeared to be coming from both sides of the issue.
CNN ran a segment last evening, with accompanying video, of protesters 300 Ft. from the White House the same day as Nancy Pelosi’s “Symbolic March” and the Tea Party protests.
This new video of protesters from the Left displayed a burning American flag, Obama being hung and burned in effigy, shouts of “Death to America” - “This is what should happen to the United States” - and “Anarchy Now”.
There is also the recent revelation that an individual has been arrested this week after threatening the life of Congressman Cantor.
So I will write it again. People such as Eugene Robinson and Chris Hedges are bigots who seem to believe that one can single out groups of people as being either Bad or Good, Smart or Stupid people.
And still nobody can deny the vitriolic hatred, name calling and ill will that is daily spread on almost every thread on TruthDig.
No single group can be singled out for it’s Good and Bad behavior. To think otherwise is, by definition, bigotry. Plain and simple.
Post script: If the Tea Party protesters had displayed the first Negro American President being hung and burned in effigy almost the entire media establishment, along with the Democratic Congress, would run with the story of the Evil, Racist, Right Wing Kooks outside the White House. <—You know this to be correct, yes?
By David Jeremiah, April 8, 2010 at 6:49 pm Link to this comment
(Unregistered commenter)
Thank You for your update. Herewith some refreshment on the same matter:Global Economics and You: America is Collapsing:
By Inherit The Wind, April 8, 2010 at 6:23 pm Link to this comment
GRYM:
(chuckle!)
By Go Right Young Man, April 8, 2010 at 5:28 pm Link to this comment
By Inherit The Wind, April 7, 2010 at 7:47 pm Link to this comment
And you are the one still reading the myopic
rantings of the teenager in his parents
basement, Shingo…...LOL
You win!
**********************************************
With THAT you made me laugh! Because you are right—why AM I still reading it? And for that I thank you!
By Go Right Young Man, April 7, 2010 at 7:24 pm Link to this comment
I have to tell you. You are, by far, the one
with the superior intellect. You will,
unquestionably, take the word of three
Washington politicians about being called nasty
names. You need no confirmation before
repeating their claims. You simply know it is
as they say. I bow to your powers of divining
the truth.
And you are the one still reading the myopic
rantings of the teenager in his parents
basement, Shingo…...LOL
You win!
By Go Right Young Man, April 7, 2010 at 6:54 pm Link to this comment
Inherit The Wind, April 7 at 10:30 pm
Written by an individual with strong opinions
yet keeps coming up empty. LOL…..
Offer something. Anything of substance. Any
examples that can be verified by others of the
claims you have made. Otherwise you are wasting
both our time.
You get the last word.
By Tennessee-Socialist, April 7, 2010 at 6:36 pm Link to this comment
DR. PAUL CRAIG ROBERTS IS QUITTING JOURNALISM BECAUSE THE FAKE-LEFTIST SITES COUNTERPUNCH, COMMONDREAMS, ALTERNET AND ANTIWAR WON’T ACCEPT HIS 9-11 INSIDE JOB ARTICLES (LEFT-GATEKEEPERS ARE FUNDED BY US GOVERNMENT)
.
By Inherit The Wind, April 7, 2010 at 6:30 pm Link to this comment
GRYM;
So…if YOU assert that the Earth is flat, you don’t have to prove it’s flat, but I have to prove it’s not flat?
OK. George W. Bush was the WORST President America EVER had, and Barack Obama is THE BEST President since Lincoln. I stated it. It’s a fact. Now it’s up to YOU to disprove it.
The Great Pumpkin picks the perfect pumpkin patch, then emerges from it on Halloween to fly around the world giving candy to boys and girls. It’s up to YOU to prove me wrong.
Imagine if that was how a court of Law worked. You are accused of a crime. Nobody has to prove you actually did it. No evidence, no witnesses, just an assertion. It’s up to YOU to prove you didn’t do it.
That is the logical absurdity you have presented and continue to defend.
No wonder this nation went into the WORST economic decline since the Great Depression when your heroes were running things, with that kind of “logic”.
By Redwein, April 7, 2010 at 4:15 pm Link to this comment
Wanted to submit a question for tomorrow’s q&a but unable to access. I just get a blank page with an oblong rectangle across the top. What’s up? Is the q&a closed already?
By Go Right Young Man, April 7, 2010 at 3:23 pm Link to this comment
Inherit The Wind, April 7 at 5:45 pm
It’s interesting that you say all that. Because what you describe is you. You offer nothing on this subject but your strong opinions.
I can find no evidence that what you and others are claiming is true. You yourself have been unable to offer tangible and verifiable examples that Tea Party protesters have conducted themselves as you and others claim. Dodging that fact repeatedly is, well, either disingenuous or, at the least, ambiguous.
I will not do the 7 minutes of search it would take for you to see my claims first hand. If you are that incurious then WHAT, pray tell, are you even writing about?
My examples of horrendous behavior are tangible, verifiable, and easy to locate. I cited very distinct examples. I am under no obligation to go out of my way for you. I will simply write what I know to be factual. As I always do. I repeat. I will not lift a finger to do the homework for you or anyone else.
I do not write or opine on what I cannot prove. Do your own homework and know what I know. failing that you are only opining and pretending to be shocked over protesters words and actions.
You too seem a smart individual. But you are still not discussing these matters with honer, Sir. I can’t be any more frank than that.
By Inherit The Wind, April 7, 2010 at 1:45 pm Link to this comment
You keep asserting the same things without facts, and then claiming they are facts….Sorry guy, but logic and debate don’t work that way.
You just seem totally incapable of understanding. I don’t get it. You seem like an intelligent guy.
I don’t expect you to AGREE with me—I don’t care if you do or don’t. I EXPECT you to be able to support your assertions and your conclusions based on those assertions.
If you can, I will be forced to re-evaluate my own positions—it’s happened. If you cannot, your position is meaningless.
Consequently, your current position is meaningless.
By Tennessee-Socialist, April 7, 2010 at 8:07 am Link to this comment
Sharon: Even though you are right, about the excess of debating over irrelevant gossips of both capitalist mafia-cartels (Democrats and Republicans), you said that you are tired of “isms”. But i don’t understand why you reject the fact that countries are ruled by Political-Systems, and that governments in this world have indeed a political-philosophy and are not governed by pure passion and emotions. That’s like baking a cake, you need a scientific recipe to bake it. And in order to fix our reality we need a theory, a philosophy and a scientific-analysis and plan on how to fix it. The USA has a capitalist-system, and this stage of capitalism is called “Monopoly-Capitalism”, or Neoliberalism, or Corporate-Capitalism. It is a stage of capitalism where only the big businesses can make a lot of money, while small-businesses and the proletariat class (US workers) are beating the bullets economically.
For Monopoly-capitalism we need a plan, a medicine. And that medicine is not progressive-liberalism (Capitalism with a human face), that medicine is socialism. Socialism (The Dictatorship of the proletariat) is the only solution for USA.
I am an absolute mechanicist, determinist marxist-leninist, and I believe 100% in the theory of Historical Inevitability of Socialism in the USA. According to some Marxist-Scholars in America capitalism will collapse and will be replaced by socialism (The Dictatorship of the proletariat) around the year 2050.
By Tennessee-Socialist, April 7, 2010 at 7:52 am Link to this comment
Hello all:
I just have a simple question for you about a real change in the USA.
How and when do you think that a Socialist Party can rise to government power in USA and change USA from capitalism to a socialist workers state.
Because to tell you the truth i am damn tired of capitalist-America, of Mcdonalds, Burger Kings, Wendies, and KFC all over the place, of big hulking smelly SUVs and big trucks spending gas like there is no tomorrow.
Of constant dollar devaluations (which lowers our personal liberty), of constant wars which also leads to poverty, unemployment and misery here at home, and of lack of personal-satisfaction and progress because who can progress and move foward in a capitalist american system where you have to be rich to join a College, and where every thing is so expensive and economically-banned and prohibited for the general american population.
Capitalist-America is literally a jail for the majority of US citizens, it is a death-penalty impossed by force on all americans, because in US elections we don’t have choices to choose between socialism, monarchy, fascism or capitalism. The only real options in USA are 2 narco mafia capitalist cartels (Democrats or Republicans).
It is time to have a socialist system like Venezuela in the USA
Thanx
By Go Right Young Man, April 7, 2010 at 6:35 am Link to this comment
ITW- “All you have are ASSERTIONS, not facts.”
Call them what you will. That Game interests
me none. The fact is you have not been able to
disprove my “assertions”. Nor have you been
willing to show evidence of your own.
You have a small few people (democrats you are empathetic toward) who have made “assertions”
and you claim those assertions are what they
claim. No film. No sound bites. No witnesses
to speak of. Not even with DOZENS of media and democratic aids filming Ms. Pelosi’s Symbolic March.
On the other hand every one of my “assertions” of hateful, violent or untoward behavior are tangible and provable for all to see.
Nearly all of the so-called Left applauded when the previous president was unable to complete the time-honored walk to the capital on inauguration day 2001 due to items being thrown from a few in the crowd. It was the first and only time in history the opposition displayed such hatred and violence.
Howard Dean supporters LOVED it when he openly spoke of his “hate” for Republicans.
Bill Maher did not chastise Sen. Kerry as going to far when the candidate for President suggested he could kill “One at 1600 Pennsylvania Ave” to make a point about war.
And nobody from the so-called Left, including yourself, has come close to suggesting that perhaps Nancy Pelosi’s “symbolic march” was probably not the best choice for her photo-op. Unless, of course, vitriolic confrontation was the agenda of Speaker Pelosi.
Your indignation regarding the actions or unkind words coming from opposition protesters rings hollow to even the most casual observer.
No one group has a monopoly on Good and Bad
behavior. To think otherwise is, by its very
definition, Bigotry!
By Inherit The Wind, April 6, 2010 at 8:39 am Link to this comment
What facts? All you have are ASSERTIONS, not facts. It is not my job to prove your assertions are false—it is YOUR job to prove they are true, and then I may challenge that proof.
I cannot simply assert “The Earth is Flat” and then say “Prove me wrong!” That is what you do and all you do.
By Go Right Young Man, April 6, 2010 at 5:17 am Link to this comment
“You are going to have to PROVE John Kerry ever
called for violence against the President. I
call “bullshit” on that as well.”
**Sen. John Kerry on the Bill Maher program.
Look it up!**
“If you don’t know the difference between
calling someone “Nigger” versus calling someone
“Re-thug-lican” or “Democ-RAT” then you have
shown your moral bankruptcy once again.”
Complete nonsense. Bigotry is bigotry. It
matters none if you personally agree with the
offended.
We are both entitled to our opinions, yes. The fact is, however, you have presented no facts and have, so far, been unable to dispute even a single fact I have shared.
You have repeatedly issued your opinions on the
Tea Party crowd calling your side of the isle
Niggers and/or Fags, HOWEVER, you have not
shared a single shred of evidence that these
things have taken place.
In the mean time I have presented unequivocal
examples of hate speech and violence from the
political left.
The former head of the DNC openly tells people
that he “Hates Republicans”.
Hate speech IS, I Fact, what so many do when
they refer regularly to “Rethuglicans” and
“Repugs”. - In Lieu of Fagot or Nigger.
Inciting violence is Sen. John Kerry openly
talking of killing someone at 1600 Pennsylvania
Ave. in order to make a point about war.
Hate speech and talk of violent harm to another
is seen on this Web site daily. - along with
the wish that Vice President Cheney shoot
himself in the face.
Twisted, violent and unhinged behavior can be
seen in the first President-Elect in American
history unable to walk to the Capital on
Inauguration Day due to things being thrown at
him by political opponents.
If you, ITW, or anyone can top these tangible
and proven examples of hatred and violence feel
free to jump right in. Otherwise your simply opining.
Your honer is as real as your perceptions of politics. Having some understanding of this can change your entire life!
By Inherit The Wind, April 6, 2010 at 4:20 am Link to this comment
Go Right Young Man, April 5 at 6:07 pm #.
****************************************
I have no idea what you are talking about. I evaded NOTHING. You didn’t get the answers you pre-programmed with your leading questions? Not MY problem!
You remind me of Folktruther, who would simply invent and post pure bullshit about me and pretend it was the truth, even though it had no connection with reality.
You are going to have to PROVE John Kerry ever called for violence against the President. I call “bullshit” on that as well.
If you don’t know the difference between calling someone “Nigger” versus calling someone “Re-thug-lican” or “Democ-RAT” then you have shown your moral bankruptcy once again.
Do I have to spell it out? Being Black or Gay is NOT a choice. Being Republican or Democrat is a choice. As a “Conservative” you should believe that we are responsible for our choices and as we reap the rewards, so should we suffer the penalties.
You are entitled to your own opinion. But you are NOT entitled to your own facts.
By Go Right Young Man, April 5, 2010 at 3:15 pm Link to this comment
You have your belief system in which you opine on regularly. I have the reality of living and breathing human beings to draw upon. Let us compare realities.
Hate speech is Howard Dean telling a group of people that he hates Republicans. We can all tangibly prove Gov. Dean “hates” a very large group of human beings.
Hate speech is what so many do when they refer
regularly to “Rethuglicans” and “Repugs”. - in lieu of fagot or Nigger. - Tangible and proven.
Inciting violence is Sen. John Kerry openly talking of killing someone at 1600 Pennsylvania Ave. in order to make a point about war. A “liberal Senator” advocating death to a political opponent. Tangible. Proven. Unequivocal.
Hate speech and talk of violent harm to another is seen on this Web site daily. - along with the wish that Vice President Cheney shoot himself in the face. Tangible. Unequivocal.
Twisted, violent and unhinged behavior can be seen in the first President-Elect in American history unable to walk to the Capital on Inauguration Day due to things being thrown at him by political opponents. Tangible. Violent. Unhinged. Hate-filled. - Provable.
If anyone can top these tangible and proven examples of hatred and violence feel free to jump right in.
True and raw hate speech is witnessed on this very Web site each and every day. Not a soul alive can deny this is so.
There is no monopoly on Good and Bad behavior amongst groups of people. This is tangible and unequivocally provable.
By sharonsj, April 5, 2010 at 2:42 pm Link to this comment
(Unregistered commenter)
So after a respite I came back to read all the newer comments and what do I find? A major argument over why Nancy Pelosi walked through a belligerent crowd. Who the hell cares? Maybe she did it to prove a point. But it has nothing to do with solving the serious problems this country faces.
Then there are postings so long-winded and complex that just the attempt to translate them tires me out. I don’t care about debates over which “ism” is correct. I don’t subscribe to conspiracy theories. I say the answer is quite simple: the country is for sale to the highest bidder. And the power elites can get away with it because most human beings are downright ignorant.
Before the Tea Party even existed, I woke up one day and realized that I was completely enraged over a long list of terrible problems, from hacked voting machines to banking fraud. The mainstream media hardly mentioned things that mattered, preferring to dwell on Michael Jackson or “American Idol.” If you listened to pundits, the screamfests over abortion and gay marriage were much more important than the dismantling of our jobs. Anti-war protests were hardly mentioned while Tea Party antics made headlines.
I don’t know whether to give up or start collecting bottles from the local bar to make Molotov cocktails. I think this is the crossroads where many of us now stand.
By Go Right Young Man, April 5, 2010 at 2:07 pm Link to this comment.
You have your belief system. I’ll take honer over politics. I’ll take on the real, every-day working and living human interaction over the television, newsprint and Internet. Unequivocal.
Yelling Nigger and Fag in public is deplorable. I will be the first to speak out, both in public and here, when I see it. When you or anyone else holds some tangible evidence that the Tea Party crowds are prone to it, display it RIGHT HERE in this post for all to see.
Otherwise all you have is a small few on your side of politics making claims that never seem proven.
Good day.
By Inherit The Wind, April 5, 2010 at 11:07 am Link to this comment
Thank you.
Go Right Young Man, April 5 at 8:18 am #?
****************************************
And I answered it: She’s a politician looking, like all of them, for press. It’s still a semi-free country and she SHOULD be able to march. See Dr. MLK and Mohandis K. Gandhi for further insight into the use of non-violence.
****************************************?
*********************************************
And I answered as well. You really must pay better attention.
They have the SAME right as Pelosi and I do not and never will defend the use of violence in that situation.
I went on further to specify that calling names that reflect ones actions, like “Murderer!” or “Socialist”(as a nod to your side) is perfectly legitimate, but calling someone “Nigger!”, “Faggot!” or “Kraut!” is definitely NOT acceptable and DOES qualify as hate speech. This is to help you differentiate between what is and is not acceptable—to draw the line, so to speak.
I FURTHER say that ANYONE advocating and inciting violence instead of lawful protest deserves the full weight of the law on their head.
**************************************************
-
Let me know if these questions remain ambiguous to you.
************************************************
And I suggest if these answers are somehow still ambiguous to you, you’ll need to brush up on your rhetoric skills.
By lyco, April 5, 2010 at 8:25 am Link to this comment
Unfortunately, Chris, you appeal to the same political establishment, within the framework of the same liberal solutions, that led to the crisis you depict: .” The Washington concensus has indeed shown its bankruptcy. We are at a crossroads, but the alternatives are not fascism and more of the same, but rather “fascism” and the emergence of a revolutionary leadership/movement of the grassroots that can pose a clear and realistic alternative to fascism. There are some promising starts, all issue-oriented as of now, directed against Obama’s neoliberal project.
On the other hand, I don’t believe a fascist movement is about to take power in the U.S., although a totalitarian, right wing government is in the offing… in fact, that rightward drift, presaged by Samuel Huntington’s call for an end to “excessive democratic expectations,” has been the tendency since the end of the postwar boom.
Unlike the European fascist movements, with their bonapartist leaders, which seized power to save a shaky ruling class, the ruling class in the U.S. is and has been firmly in control. In fact, they have rather skillfully played off the liberal left and fascist right, fanning the flames of fear of “big government” and “socialism,” on the one hand, and the end of bourgeois legality and the “welfare state [sic],” on the other. This distinction is important in one sense, and I think you miss this. In the absence of the kind of mass fascist movement that occurred in Germany, Spain or Italy, there is room for struggle at the base.
By Go Right Young Man, April 5, 2010 at 5:31 am Link to this comment
As I have written in the past; it’s a foolish
and bigoted mistake to label the Tea Party
protesters as a fringe movement. Huge mistake!
April 5,
Tea Partiers Are Fairly Mainstream in Their
Demographics -Gallup/USA Today
43% of Tea Party protesters are self-proclaimed
Independents - The people who actually decide
national elections.
I will write it again. It’s a monumental
blunder, and also Highly Bigoted, to denigrate
the people who will decide the direction of the
nation in next election cycle.
By Go Right Young Man, April 5, 2010 at 4:18 am Link to this comment?
Let me know if these questions remain ambiguous to you.
By Tennessee-Socialist, April 4, 2010 at 8:38 pm Link to this comment
USA IS NOT HEADING TO FASCISM !! USA IS FASCIST SINCE 1776. USA WAS FOUNDED BY RACISTS AND FASCISTS !!
US ORIGINS In Genocide/Extermination:
But this policy of eliminating people, whether in the form of genocide of whole peoples, or of key individuals who possessed followers, when they are perceived in the way of White Man’s “progress” – prosperity for the few through expansion at any cost – has been the guiding cultural ethos of USAmerica since our origins.].].
By Tennessee-Socialist, April 4, 2010 at 6:05 pm Link to this comment
TOWARD A SOVIET USA. THE AMERICAN SOCIALIST GOVERNMENT
WHEN the American working class actively enters the revolutionary path of abolishing capitalism it will orientate upon the building of Soviets, not upon the adaptation of the existing capitalist government. revolutionary organized’ organizations, army, navy, etc. The principle of recall of representatives applies throughout. Citizenship is restricted to those who do useful work, capitalists, landlords, clericals and other non-producers being disfranchised.
The local Soviets will be combined by direct representation into county, state, and national Soviets. The national Soviet government, with its capital in Chicago or some other great industrial center, will consist of a Soviet Congress, made up of local delegates and meeting annually, or as often as need be, to work out the general policies of the government. Between its meetings the government will be carried on by a broad Central Executive Committee, form of continental union. The American revolution will doubtless carry with it all those countries of the three Americas that have not previously accomplished the revolution.
The Soviet court system will be simple, speedy and direct. The judges, chosen by the corresponding Soviets, will be responsible to them. The Supreme Court, instead of being dictatorial and virtually legislative, as in the United States, will be purely juridical and entirely under the control.
By Tennessee-Socialist, April 4, 2010 at 5:56 pm Link to this comment ‘Mad.
x
By Inherit The Wind, April 4, 2010 at 4:39 pm Link to this comment
Try, just this once, and with honer, try
answering my direct questions. Breaking with
TruthDig tradition, a tradition you yourself
heavily engage in, and have a true conversation
with someone whom who you do not agree with.
*******************************************
Now you are being totally sophist and flatly dishonest. I asked you TELL ME what YOU think the issue is, and you respond with an attack on honor for the umpteenth time.
I asked you a totally honest question: What is the topic I’m avoiding. And…you AVOIDED answering it, repeatedly! Why is that? (rhetorical question—I know you won’t answer meaningfully).
If you cannot answer a simple question like that, where I was not even asking what your position is, just what you think the topic is, then NOBODY here is going to see you as engaging in legitimate debate.
The only dishonest and dishonorable one is you, GRYM.
And I’ve wasted enough time on this with you.
By John Hutchinson, April 4, 2010 at 4:19 pm Link to this comment
(Unregistered commenter)
Dear Mr. Hedges:
You state…
“The Balkan war was not caused by ancient ethnic hatreds. It was caused by the economic collapse of Yugoslavia.”
This argument is akin to saying that WW1 was not caused by the petty nationalisms, the imperial competition, breakdown of the balance in the balance of power arrangements, even ennui among other things. But rather to say it was caused by the
assassination of Archduke Franz Ferdinand.
By some chance, I was connected to Croats in the mid-70s who demonstrated these odd and inexplicable animousities. They spoke of street fights in the streets of Toronto. One spoke of how towns were such that walking from block to block and one experienced a different dialect.
I cannot speak of all the causes of the Balkan Wars as I have not looked at in depth. However, it is Yankee cultural blinders that always takes the pretexts of economic dissolution as underlying causes for events. I do sense that Tito could only keep the country together by strong-arm and draconian autocracy. And with the dissolution of the Soviet threat, that which kept the various groups in alliance against a common Soviet adversary, was no longer in play. Furthermore, when many families have had grandmas and grandpas killed by their adversaries in times past (i.e. WW2, WW1, Balkan Wars prior to WW1 etc), don’t be surprised if the latent motives for honour revenge come hurdling out the moment the screws are loosened.
Finally, there is something to be said for the argument that the more statist a country is, the more prone toward civil war. If a large part of the scope of human endeavour is in the control of the state, the greater the importance of controlling the Commanding Heights. Men, with any spirit in them, cannot abide living by an inordinate number of external rules that have no internal resonance within themselves.
This I find is the problem with your writing. You are really good at the insight of reportage but are questionable as to depth of analysis. Furthermore, your ideological convictions have analytical blinders.
Yes, the lower classes have been receiving the shaft. But they are not particularly a noble lot neither, but have degraded in parallel manner as all other segments of society.
When I was 17, I was irked by the relative truth and morality ethos that was being put upon us by leftist teachers in the public school. It was consciously apparent that if such be true, then the purpose and value of knowledge is futile; learning is futile; truth and good is that which turns one’s crank or gets mankind through the dark night of existence. I am sure that others did sense, even semi-
consciously, this intellectual and psychological logic of philosophical skepicism. If knowledge is pointless, is it any wonder that there is no seriousness left?
Your understanding of the Christian Right is out to lunch. From the moment Puritans touched these shores, there was always Dominionists; in far greater numbers than now. And most Protestants by the early 18th Century had rejected that political model. But I suspect that most people are taught that serious US history didn’t begin until the Revolutionary War.
Dominionism is a concern. It is the reverse and reaction of the fear of persecution and oppression that gave rise to the Christian Right in the late 70s in the first place. It can easily be theologically destroyed, especially by showing the inconsistency with Scriptures and the internal logical absurdities in a kindly but scathingly humourous manner.
It is more likely that this big bogeyman that you portray is going to implode out of the theological and moral rot that lies within and lose moral authority like the Christian left, than become the handmaiden of tyranny. If the latter scenario does happen, it is because the rot is complete. We will experience something like the behavioural and ideological totalitarianism of the Late Roman Empire.
By Go Right Young Man, April 4, 2010 at 11:59 am Link to this comment
ITW.
Once again you changed the subject. As you well
know “name calling” is not my nature.
Try, just this once, and with honer, try
answering my direct questions. Breaking with
TruthDig tradition, a tradition you yourself
heavily engage in, and have a true conversation
with someone whom who you do not agree with.
By Inherit The Wind, April 4, 2010 at 11:13 am Link to this comment
You have a terrific knack for avoidance when
you find yourself on feeble ground. In place
of addressing the issue straight on you
repeatedly change the subject. That is no way
to display true passion for your stated
positions.
*************************************
And what IS the issue I’ve missed? I’m not being deceptive: I thought you were attacking Pelosi for walking AS IS HER LEGAL AND CONSTITUTIONAL RIGHT through a crowd of loud, yelling tea-baggers and therefore (it is your contention) that SHE instigated House members being called “Nigger!”, “Faggot!” and one being spat upon.
If I am incorrect, please explain just what you think the issue is that I’m supposed to be skirting. Enlighten me, and save name-calling for when it’s earned, not simply when you cannot prove a point. I get enough of that from Ardee and TD3.
By Go Right Young Man, April 4, 2010 at 9:26 am Link to this comment
ITW, - “So, you think a politician should avoid
getting press? Or should only DEMOCRATIC
politicians be held to the standard of avoiding
getting press?”
As you well know I wrote nothing of the kind.
You have a terrific knack for avoidance when
you find yourself on feeble ground. In place
of addressing the issue straight on you
repeatedly change the subject. That is no way
to display true passion for your stated
positions.
By Inherit The Wind, April 3, 2010 at 5:48 pm Link to this comment
Now TDers should read the latest yearner for fascism: Omop. I believe every TDr from GRYM to Shingo will condemn this neo-nazi’s stereotypical attacks on ALL Jews, not merely Zionists (which, as Calabashe points out, is a political view).
By Inherit The Wind, April 3, 2010 at 2:16 pm Link to this comment
Go Right Young Man, April 1 at 7:52 am #
ITW, - “ITW, - “Uh, I dunno. Maybe because the Protesters were between and where she works, the Capitol?”
I neglected to mention that Speaker Pelosi’s office (where she works and where House members normally caucus) is located in the Rayburn office building. Not the Cannon office building, where she began her “Symbolic March”, which took her fear filled members Directly Through the protesting crowd.
**************************************
So, you think a politician should avoid getting press? Or should only DEMOCRATIC politicians be held to the standard of avoiding getting press?
I know of only ONE politician who avoids getting press, and, unfortunately, he is MY congressman, a Republican, and he wouldn’t stand out in a crowd of two. He’s the most do-nothing congressman on the Hill and consistently ranked one of the least effective. Without even discussing his politics, he just plain SUCKS at the job of representing our district, which, Dem or GOP, is what he is SUPPOSED to do! The guy he replaced, also GOP was actually very effective and good for the district. Unfortunately, he died of cancer, which forced him to withdraw from the 1994 race. The nothing even has a name that goes back to the Revolution: Frelinghuysen, aka “Do Nothing Rodney”.
By maninwarren, April 2, 2010 at 9:22 am Link to this comment
I realize stuff like this is going on all over the US, but this is a powerful illustration of the police-state insanity taking hold in this country.
NOTE: I tried sending this via the “feedback” page on truthdig, but then got an email saying it couldn’t be delivered. I hope Chris Hedges reads his comments.
By Alan MacDonald, April 1, 2010 at 5:20 pm Link to this comment
(Unregistered commenter)
Jean, Hedges, Sheldon Wolin, and Andrew Bacevich are all prophets—- regarding the impact that the global corporate/financial.militarist Empire is having on our country and our world.
Best,
Alan MacDonald
Sanford, Maine
By Jean, April 1, 2010 at 9:11 am Link to this comment
(Unregistered commenter)
Chris Hedges is a prophet… I believe him.
By Maxim, April 1, 2010 at 8:26 am Link to this comment
(Unregistered commenter)
Maxim
There is a kind of confusion when the author declares, referring to a certain Fritz Stern “a scholar on fascism” that “in Germany there was a yearning for fascism before fascism was invented”: a happy turn of phrase but but somewhat inaccurate. If only because of the confusion between “Fascism” and “National-Socialism” which have very different roots as well as doctrines. As regards Germany and in accordance with the real objective of the Versailles Treaty, the conditions were calculated to prevent a prompt German recovery: as this country had to pay some 132 bn of Deutsche Mark (Gold) which indemnity could only and possibly be fully extinguished in….1988 (in the meantime amended by the Dawes and Young plans then de facto cancelled). It should have been probably wiser to take into account (from France and England namely) that this situation should unavoidably condemn any democratic regime to economic and social stagnation keeping alive a spirit of resentment and revenge (the American Congress did not accept to ratify this treaty). But further on and in order to summarize intricate developments one should remember that there was in Germany and this, until 1932, harsh political but also physical continuous struggles between communists and left leaning socialists on the one hand, and “the right” on the other hand, the latter keeping in memory the hard revolutionary fighting in 1918 and 1919. Let us also remember the violence of the “Spartakists” in Berlin in 1918 (Karl Liebknecht, Rosa Luxemburg, Clara Zutkind and Karl Radek sent by Moscow ) as well as the bloody communist revolution in München with Kurt Eisner-Lewenstein (killed on 21st Febr 1919 by the young count Arco-Valley) immediately taken over by three Russian political commissioners, Levin, Lewiene and Axelrod. If” (the unmistakable “if”) the Reichswehr had not been dismembered and limited to a kind of passive border guard, under strict French supervision with direct consequences i.e.the Bolshevik attempts to take control of East Prussia but also the Poles, eager to use their freshly recovered but disparate army, there should not have been kind of “sponateneous” generation of German “irregular forces”: the Spartakist and Communist revolutions should have been almost impossible in a well-organized state but in 1920 the state was in a state of near collapse deprived of any real authority.This violent period left a residual influence on the German society generating the unavoidable re-action and it is only in 1933 after a decade of clashes between political factions but also the world crisis of 1929 with a stunning unemployment rise, that national-socialism could only get off the ground.
In his article, the author exposes the dangers of a latent “fascism” in the United States but in Western Europe where unemployment also reaches too a high level, it could possibly drift toward a left-leaning socialism while in the Unites States, the “working class” ( or what’s left of it) is more inclined to a kind of unbridled extreme-right . Especially as it is possible in most states to own weapons, contrary to Europe where it is strictly controlled if not forbidden.
There is also and right now, the poisonous example of Wall Street, with its “toxic assets”, subprimes framework, hazy hedge funds etc drawing the wrath of the “new poor people” .
In case of serious social trouble, the government should be obliged to call in the National Guard or event some Army Units with the ensuing dangers. Of course this is not an apology of any “ism” regime as the Wall Street wealthy people should anyway go through, unscathed: “unforeseen circumstances excepted ? “
Maxim
By Go Right Young Man, April 1, 2010 at 3:52 am Link to this comment
I neglected to mention that Speaker Pelosi’s office (where she works and where House members normally caucus) is located in the Rayburn office building. Not the Cannon office building, where she began her “Symbolic March”, which took her fear filled members Directly Through the protesting crowd.
By Go Right Young Man, April 1, 2010 at 3:28 am Link to this comment
ITW, - “Uh, I dunno. Maybe because the Protesters were between and where she works, the Capitol?”
Yes. I’m sure you’re right. Speaker Pelosi had No Choice but conduct her “symbolic march” directly through the protesting crowd when she did and where she did.
After she herself had helped to drum up fear of violence from the Tea Party crowd her CHOICE to march directly through the crowd was only a matter of “necessity”. We can be sure Her Choice to conduct this “Symbolic March” was not intended to incite the crowd. We can be sure Ms. Pelosi, who claimed to fear these people, was only doing what she thought was Right and Best for her members and the country.
And after several dozen Tea Party protests all over the nation for many months, with nary a sign of racism, no signs of violence or destruction of property, on this single occasion we should simply trust that this SINGLE crowd of protesters started yelling racist remarks.
Interesting how none of these things were caught on film. All the while democratic aids and several dozen from the media were there to document the ENTIRE symbolic march. Interesting how not a single reporter witnessed these heinous acts themselves. We should simply trust that this ONE CROWD acted in ways they never had before. We should simply trust that they took place because a few democrats claim it did.
Interesting too is how the National Park Service stated that after last year’s Tea party protests, where tens of thousand of people congregated, they were amazed at how clean the grounds were after the protesters departed. - Usually the grounds are completely trashed after such gatherings.
It’s fascinating that these unruly, nasty, and violent “Tea Baggers” actually took the time to clean up after themselves.
By bogi666, April 1, 2010 at 3:17 am Link to this comment
(Unregistered commenter)
Brain D., you’ve got it right Americans have been brainwashed into MINDLESSNESS, the inability to discern thought from facts. Laziness is the main reason and in the USA MINDLESSNESS it’s MINDLESSLESS to the 10th power because Americans take the thoughts of others as their own facts. Being a society conditioned into being NARCISSISTIC, CONSUMERIST, GLUTTONS with a philosophy of “I’m not responsible, god told me or Satan made me do it but I’m not responsibile”. This false doctrine is fostered by, especially the churches, business and government which give the “I’m not responsbile…...” legitimacy. The practice of this doctrine is readily observable by watching TV.
By drbhelthi, April 1, 2010 at 1:28 am Link to this comment
The concept that “Democrats and Republicans are
driven by opposite forces” might be a bit more
explained. Both are driven by the desire for power
and the desire to govern, or “rule.” That they
allegedly had “opposite” political philosophies -
perhaps thirty years ago - is in my opinion still a
bit overstated.
While the philosophical concept of “democracy”
differs from that of “socialism,” in actual practice
they still reflect the underlying desire of the
“leadership” of either to control, manipulate and
rule. When we compare the CURRENT “democracy” of
the US NAZI/israeli-oligarchy with the “socialism”
practiced in the Republic of Germany - - ?
The German leadership has not attacked any nation in
oil-theft activities, nor are they forcing socialism
on any nation, under the guise of “freeing the
populace from its abusive leadership.” Nor does
swapping a masculine anus for a feminine vagina fit
my concept of “freeing woman-hood.” Nature assigns
excrement to the anus, regardless of gender. Nature
assigns child-bearing only to the female, with
motherly characteristics.
German involvement in NATO, perhaps also the UN,
tends to tarnish their otherwise clean world-stance.
Here again, the NAZI/CIA/Israeli PR-subterfuge that
underlies “NATO” simply reflects power-grabbing,
power-maintaining with its associated, militaristic-
genocide-debauchery & assassination of specific
individuals. Here again, the top socioeconomic level
of “elitists” always “have the floor.”
The genocide that has accompanied “U.S. Democracy”
since the NAZI take over, beginning 1945,
joined by the Israeli tribe in the 1970s, reflects
neither the democratic nor the republican philosophy.
It reflects, perhaps more, the history of the Israeli
tribe, which was continued by the dunce from Austria, and
which has not stopped.. The “effective PR” of the
NAZI system inflicted the German folk and the world
with the dunce´s “Mein Kampf.” Of course, with
financial assistance of political and business
leaders of Europe and stooges in the USA. The family
Bush, for example.
This time, the same NAZI-type, “effective PR”, once
again enforced by the same top-level-elitists, has
over-run the naivete of American folk instead of
German folk. Nor does this PR, with its elitist
ownership, reflect the desire of patriotic Americans!
Nor patriotic Germans ! Nor the patriotic folk of any land !
By BR549, March 31, 2010 at 6:41 pm Link to this comment
(Unregistered commenter)
Chris, you said it all with the statement, “Our problem is a problem of governance.” Crappy managers, like those sleezy ones we see in places like MacDonalds and WalMart, always seem to trash those beneath them to better themselves. They never do understand that management is in control and has only itself to blame when things go wrong. That’s when, with managers possessing personal
responsibility skills, they either change THEIR actions or they resign.
What’s missing in the present picture? Competence? Could it be that our politicians, too much like used car salesmen, are too consumed in their commission checks to ever consider whether their customers were getting what they signed up for?
By Inherit The Wind, March 31, 2010 at 4:59 pm Link to this comment
Go Right Young Man, March 31 at 10:05 am #
I’m sorry. The below post should have read:
Why, do you believe, did Pelosi chose to walk her Members (with video cameras at the ready) directly through a crowd of upset protesters when she could have chosen to perform their symbolic march in dozens of other places
and at any other time?
**************************************
Uh, I dunno. Maybe because the Protesters were between and where she works, the Capitol?
By elisalouisa, March 31, 2010 at 4:39 pm Link to this comment
TAO Walker I cannot disagree with your post in any way. The nature of the beast is such that one must have a tough skin to be part of Truthdig. I am sure you have that TAO Walker however, you may wonder, as others have, if your efforts are being put to good use. Who can say? Remember, as gerard said, “You never know
where thoughts take root.”
By L Murray, March 31, 2010 at 2:55 pm Link to this comment
(Unregistered commenter)
One wishes that one could “report this” if the post lacks logic, but sadly that won’t get it taken off. Please tell me the post from “Cheryl Merrill” was a joke…right? No one could actually be that confused about history and politics.
By mic jor, March 31, 2010 at 1:55 pm Link to this comment
(Unregistered commenter)
Chris you have to avoid the brown acid it is a bummer.
You are much too young to be worrying about stuff like
this. Go back on Olberman and look cute as a little
bug !
By Tennessee-Socialist, March 31, 2010 at 10:49 am Link to this comment
COMRADE CARL DIX FROM THE REVOLUTIONARY COMMUNIST MAOIST PARTY OF USA TALKING ABOUT THE USA POLICE HELL AND HOW EVIL THIS CAPITALIST SYSTEM IS IN USA, HOW PEOPLE ARE KILLED EVERY DAY BY FAT-COPS ON STEROIDS !!
By Tennessee-Socialist, March 31, 2010 at 10:21 am Link to this comment
ALEX JONES TALKS ABOUT THE LATEST FALSE-FLAGS OF RUSSIA WITH WEBSTER TARPLEY
.
By MikeNYC, March 31, 2010 at 10:15 am Link to this comment
(Unregistered commenter)
From the election of Ronald Reagan, the country slowly started it’s course toward Fascism. By electing George Bush twice, it was clear that the country was emulating the beginnings of the German Reich. Invasion of other countries on a false pretext, reminiscent of Poland in 1939. Dictating who can and cannot marry, like the marriage laws prohibiting Aryans from marrying Jews. Anything goes warfare including all types of torture, repeating the SS and German Military. Little by little our liberties have disappeared without anyone noticing. The current administration may attempt to stop it, but the fact remains that conservative America is determined to have a kind of controlled and manipulated society similar to the Third Reich. They are selling it just as the NSDAP did in the 1930s, convincing people through propaganda and massive rallies (see the tea party rallies) that this is the salvation for America. If people don’t wake up soon, we will soon enter the Germany of 1940.
By sam, March 31, 2010 at 8:35 am Link to this comment
(Unregistered commenter)
This article bothers me. The fall of America is not going to be caused by crazy poor and middle class Americans who are so angry they burn the country down. This is just a reaction to the real cause of our destruction: the centralized policies of the banking and corporate elite and their cronies, our politicians. All I can say is Ron Paul 2010. On second thought, Cynthia McKinney would be awesome as well. I had to laugh that Americans actually thought the empty rhetoric of “Hope and Change” would mean anything good for the average American. All that gibberish meant was that the elite bankers were hoping for more change in their pockets. And they got it.
By LEROY FERGUSON, March 31, 2010 at 6:57 am Link to this comment
(Unregistered commenter)
Despite the fact that both parties are beholden to
corporations, they are driven by opposite principles.
History Prof. Dee Andrews of Cal. State U. explained
those driving forces well in a letter to the Mar. 29
issue of The New Yorker.
Democrats, he noted, believe in “civic intervention
otherwise called government regulation and
progressive taxation.” Republicans seem to believe
that fiscal policy should protect the acquisition of
wealth.
When I go to the polls, I vote on those Democratic
principles, which I hold dear - and just hope that
they will somehow prevail.
By suds mcduff, March 31, 2010 at 6:51 am Link to this comment
(Unregistered commenter)
Goriight:
“One can wonder what might have happened if Dick Cheneyhad done the very same (riled the crowd for effect) inthe midst of an anti-Bush/Cheney protest. Do you thinkCheney would have been spat upon and called names?
Would you also have an opinion on that?”
——Anti Bush protesters were commonly segregated to areas away from rallys and the media coverage….should the Dems do the same?
By suds mcduff, March 31, 2010 at 6:22 am Link to this comment
(Unregistered commenter)
Re:GoRight
“Andrew Breitbart is UPPING THE STAKES: $100K to United Negro College Fund if Rep Lewis shows evidence of anyone yelling the N-Word at CBC at last weeks Capitol HCR protest.”
——And the spitting incident?
“I’m curious if anyone here holds an opinion as to what motivated Nancy Pelosi to lead House Members to “symbolically” march directly through the protesting crowd with congressional aids and the media filming? Pelosi’s symbolic photo opportunity could have taken place anywhere at any other time of her choosing. Why walk directly through the protests?”
——When do you think the protesters would have abandoned their places? Midnight, perhaps?
Perhaps they should be relegated to certain areas, as anti Bush protesters were?
By One Little Victory, March 31, 2010 at 6:14 am Link to this comment
I usually find Hedges to be even too far off the deep end for me, and I am pretty far to the left. In this case, while I think he is over the top on the Democrats (as usual), he none the less raises some very good points.
I won;t highlight everything here (I put some musings down in my blog), but think he raises some very interesting questions on how we affect the change this nation so desperately needs.
By Go Right Young Man, March 31, 2010 at 6:05 am Link to this comment
Why, do you believe, did Pelosi chose to walk her Members (with video cameras at the ready) directly through a crowd of upset protesters when she could have chosen to perform their symbolic march in dozens of other places
and at any other time?
By Marc Schlee, March 31, 2010 at 5:29 am Link to this comment
(Unregistered commenter)
Under representative democracy, the order authorizing your murder is never more than a signature away.
FREE AMERICA
REVOLUTIONARY (DIRECT) DEMOCRACY
By Go Right Young Man, March 31, 2010 at 3:43 am Link to this comment
ITW, - “Duh! She’s (Pelosi) a POLITICIAN! They LOVE
parades and she would have done it even if there
weren’t protesters.”
Why do you believe Pelosi chose to walk her Members directly through a crowd of protesters with video
cameras at the ready when she could have chosen to
perform their symbolic march in dozens of other places
and at any other time?
By Alphysicist, March 31, 2010 at 3:35 am Link to this comment
Truedigger3,
Yes I agree. I used the term “liberal media” to designate a subset of the corporate media. This includes, New York Times, Washington Post, Boston Globe, etc. I am fully aware that Foxnews and so forth are another subset of the same corporate media. I think their founders understood the (justifiable) anger certain groups of people feel against the “liberal media”, and capitalized on it, without actually creating anything which would compromise the status quo. In the run-up to the Iraq war I was actually convinced that Foxnews and NYTimes are beating the same wardrums, the differences were only in the style in which the news were reported, which can be attributed to the different cultural habitats of the viewers/readers.
By Inherit The Wind, March 31, 2010 at 3:18 am Link to this comment
Go Right Young Man, March 31 at 7:00 am #
It may be helpful to simply answer my original questions.
What do you think motivated Nancy Pelosi to lead House Members to “symbolically” march directly through the protesting crowd with congressional aids and the media filming the Entire Episode?
******************************************
Duh! She’s a POLITICIAN! They LOVE parades and she would have done it even if there weren’t protesters.
*******************************************
Pelosi’s symbolic photo opportunity could have taken place anywhere at any other time of her choosing. Why walk directly through the protests?
********************************************
Same answer.
*********************************************?
**********************************************
“Hurtful” names? Like what can you call either Bush or Cheney that compare to “Nigger!” and “Faggot!”...“WASP!”???????
Don’t you understand? Attacking people for things they don’t choose like race and sexual orientation isn’t the same as attacking them for things they DO!
As for physical attacks: I cannot and will not defend UNDER ANY CIRCUMSTANCES violence against our elected and appointed Government officials. Period.
I have NO problem with protesters calling for Bush or Obama to impeached. Why should I? Impeachment is a LEGAL procedure. I may object to it being used in a particular case (as I felt an impeachment of Bush would both fail and hurt the Democrats), but it is not only LEGAL but CONSTITUTIONAL and I do not question the right of citizens to call for it.
******************************************
I see nothing fascistic in asking questions. I have a few more questions for you if you honorably try and tackle the first few.
****************************************
I never said there was. But your premises showed a fundamental disregard for the foundation of our freedom.
You use the word “Honor” to liberally and loosely for one who bends facts into pretzels. Clean your own house first. You’ve attacked MY honor too many times for me to have any respect for you. But ask rational question and I will respond to them in kind.
By Go Right Young Man, March 31, 2010 at 3:00 am Link to this comment
What do you think motivated Nancy Pelosi to lead House Members to “symbolically” march directly through the protesting crowd with congressional aids and the media filming the Entire Episode?
Pelosi’s symbolic photo opportunity could have taken place anywhere at any other time of her choosing. Why walk directly through the protests??
I see nothing fascistic in asking questions. I have a few more questions for you if you honorably try and tackle the first few.
By truedigger3, March 31, 2010 at 2:50 am Link to this comment
Alphysist wrote:
“Of course the Sarah Palins and co. tap into the justified anger of these people. What is particularly dangerous is that the liberal media does not discuss this in context. They write tirades against the Sarah Palins, without ever analyzing the causes”
___________________________________________________
Alphysist,
What you are calling, the “liberal” media, doesn’t exist.
It is neither liberal nor independent. It is owned and controlled by the ruling corporate powers, and consequently it will never shed a true light on the REAL reasons for the anger of the disenfranshised and it will never explain what is REALLY going on.
By drbhelthi, March 31, 2010 at 1:10 am Link to this comment
Congratulations to Go Right Young Man, for having won
the pseudonym of “GRYM” from the scape-goating, kill-
the-messenger-types. They think their comments are
the only ones that have the right to be posted.
“We’ll know our disinformation program is complete
when everything the American public believes is
false.” —William Casey, CIA Director (from first
staff meeting, 1981) as recorded by the great
American investigator/historian, Mrs. Mae Brussell.
Their “kill the messenger” posture fits right in with
the direction of the NAZI CIA and the israeli false
zionists who tossed in with them between 1970-1980.
These groups are being “mis-used” as stupid
puppetry, by the double-hand-full of elitists who
rule the world. The plan of the “dozen” elitists is
well delineated by Lesley Williams. The alleged “new
world order” will not remove the greed of humans, it
is merely a manifestation of the greed of the self-
appointed, superior “elite” group of humans.
This group of “elitists” were born like the rest of
us, will die like the rest of us, whose spirits will
take none of their wealth with them, like the rest of
us. Meanwhile, their excrement stinks, just like the
rest of us.
Meanwhile, their plan with efforts stink. NOT like
the rest of us.
By C.Curtis.Dillon, March 31, 2010 at 1:02 am Link to this comment
Don’t leave TAOwalker ... we need all the voices of sanity we can find in a world gone mad.
I know this post is a bit confusing ... I’m suffering from horrendous allergies and am doped up, so bear with me:
Fascism ... Communism ... Socialism ... Capitalism ... the “isms” fly fast and furious whenever times get tough. I am often amused by the “stark” differences one sees between all these ideologies. One can only stand in amazement at the professed underpinnings of these movements when compared to how they actually work. And it is truly interesting that both Fascism and Communism used “socialism” as their foundation (National Socialism vs. Union of Soviet Socialist Republics). For example, when one steps back and looks at WW 2, you don’t really see a titanic battle between Fascism and Communism/Capitalism ... you see a war between personalities. Germany was about Hitler, not Fascism. It was about absolute power in the hands of the few. Fascism was only a propaganda term used to justify this power. The same goes for Soviet Russia. It was about Stalin and his absolute control of that union. Both sides were very willing to sacrifice huge swaths of their populations in a effort to own more and more territory. Hitler was a megalomaniac ... so was Stalin. In the end, it was about power to the few ... the “isms’ had little to do with it.
I guess what I’m saying is we need to get beyond the “isms” and understand what is really going on. Throughout history, those with power and money have worked to increase their wealth and power. It is that simple. In America today, the people have been stripped of their influence and wealth by those in power. There is no profound movement afoot here ... it is just a battle for wealth and influence between those at the top and the rest of us. Fighting over the “isms” is just another way we allow ourselves to be distracted from the real issue. As is always the case, we allowed ourselves to be placated by an illusion of power and some affluence. We dropped the ball people, got fat, stupid and lazy, and let the greedy “elites” confuse and diffuse our power! We need to fight the uphill but necessary battle and rectify this situation. Once we do, the “ism” war will fade away.
By Alphysicist, March 30, 2010 at 10:33 pm Link to this comment
I think America is not yearning for fascism, but rather, for a civil war. At least the disenfranchised working class does. Essentially in the last decades we saw the deterioration of the middle and working classes such that inspite of America being a “democracy”, just about everything happened without the consent or out of the control of these people. As within the rules of the present system they have no way of taking their fate in their own hands, not to mention, any chance of curing their ills, the answer is, unfortunately, potential violence.
Of course the Sarah Palins and co. tap into the justified anger of these people. What is particularly dangerous is that the liberal media does not discuss this in context. They write tirades against the Sarah Palins, without ever analyzing the causes. This is also very dangerous.
A side remark: I think the ethnic component in the dismemberment of Yugoslavia was non-negligible. Yugoslavia was patched together by the winning powers of WWI without any regard to the culture or history of Mitteleuropa, and it turned out to be disfunctional. It had a relative success during the 60s and 70s, mainly because it was a “misfit” among the Communist Bloc, therefore it had a more than favourable nation status from the west, and because of a successful tourist industry. Many Western companies invested there (Adidas, for example). One might not have been able to see the ethnic differences under the internationalist veil of communism (the communist upper class did much to homoeneize the country, and to stress a “Yugoslav” ethnicity, instead of Serbian, Croatian, etc.), but under the surface it was there. Moreover, Yugoslavia (or Tito’s partisans) never really came to terms with their own post WWII past, when Italians, Hungarians, and Germans were either exterminated or deported (Foibe, Backa massacres). In some places this amounted to the destruction of much of the educated class.
By 99, March 30, 2010 at 8:48 pm Link to this comment
(Unregistered commenter)
PLEASE! Chris! I think you are marvelous, but PLEASE, get OFF your high horse
and climb a tree or something, because if you cannot see how beyond the pale
NOT lucid it is to call people protesting fascists “Nazi Brown Shirts” all is lost.
THE PEOPLE IN POWER ARE NOT OUR FRIENDS, NOT FRIENDS TO ANY OF US,
RABID CONSERVATIVE OR FOAMING LEFTIST OR ANYONE IN BETWEEN.
Thank you.
By Scott Schneider, March 30, 2010 at 7:45 pm Link to this comment
(Unregistered commenter)
Chris is correct to point out the dangers. Even Norman Mailer would probably agree since he used the word “pre-fascist” to describe the USA post 9/11. Mailer also warned that fascism may be a more natural state of human government than republicanism.
The only technical error Chris makes – common in the arrogance of the Anglo- American tradition – is to refer to America as a democracy. It was never one, and was never intended to be. Populism was generally feared by the framers, with the possible exception of Thomas Jefferson (if one excludes his temporary reversal with the infamous Alien and Sedition Acts).
Representative government, yes. Democratic republicanism, if you like. As Benjamin Franklin famously cautioned, “A republic, if you can keep it”. Even that is difficult enough. But democracy?
That was tried once, over 2000 years ago, with mixed results. Ironically the nation that invented and practiced democracy is now the epicenter in a huge global battle for economic and political freedom. For more, see:
By Tennessee-Socialist, March 30, 2010 at 7:28 pm Link to this comment
WE HAVE TO BE LIKE THE REVOLUTIONARY-ANARCHIST DURRUTI. USA NEEDS MANY DURRUTIS TO DEFFEND THE COUNTRY FROM THE BOURGEOISE-CAPITALISTS WHO HAVE STOLEN THE USA FOR THEMSELVES
By Cheryl Merrill, March 30, 2010 at 7:23 pm Link to this comment
(Unregistered commenter)
OMG, you’ve got it completely wrong! It’s reverse - the liberals are the fascists! Hitler rose, not on the backs of conservatives, but on that of liberals (citing Liberal Fascism, Jonah Goldstein).
As someone who used to be a liberal who believed as you guys do, you’ve been brainwashed! You are compartmentalized not to see the entire picture. For instance, think about why our gov’t has allowed so many illegal third world impoverished immigrants into our country, while advocating 50 million abortions the past few decades? There’s an entire nation of babies who were killed and replaced with poor third world immigrants. Jobs were shipped overseas! America no longer has any production capacity to maintain itself so it’s involved in unjustified wars to fund itself.
There’s a much larger picture operating here. The Rockfellers, Rothchilds and other similar banking families have a very huge plan for our world and they have been slowly bringing America down incrementally.
The problem is the Federal Reserve are private banking families who print out money with no value backing it up. They buy out our politicians with the printing press they own. They fund both sides of wars throughout history. We don’t have a real country any longer. The politicians do whatever they want and keep up an illusion of a democracy. The two parties are one.
Obama is a wall street shill and his real name is Barry Sartaro. He hasn’t produced a birth certificate. He was born in Kenya. Our country has been taken over by criminals who have serious evil plans for our country worse then Hitler ever did. Far worse due to technology available to them.
By Inherit The Wind, March 30, 2010 at 6:26 pm Link to this comment
Go Right Young Man, March 30 at 2:47 pm #
ardee,.
***************************************
GRYM, do you even UNDERSTAND the fascism you are advocating? Are you saying an American citizen, indeed, a group of American citizens should NOT walk peacefully down the street because they are “provoking” the assholes who will curse at them, call them “Nigger!” and “Faggot!” and even spit on them? That those assholes should be allowed, even ENTITLED to own the streets? Talk about enabling!
For once I agree with Ardee in his assessment of your position. (maybe not the name-calling—this time!)
By Tennessee-Socialist, March 30, 2010 at 6:25 pm Link to this comment
LISTEN TO THIS MP3 BY CINDY SHEEHAN AND TEMIR PORRAS VENEZUELA VICE-MINISTER OF FOREING RELATIONS
Temir Porras - March 28, 2010 (SOAPBOX #55) - Cindy welcomes Temir Porras, Venezuela’s Vice Minister of Foreign Affairs, in charge of the Middle East and Asia. In today’s world, Venezuela and its popularly beloved President, Hugo Chavez, are tarred as a “communist dictatorship” because of robber-class fears that his good example could give others ideas, too. (Where would the world be if we let people realize that Hugo Chavez is beloved precisely BECAUSE he takes good care of all his people - not just the wealthy and powerful few.) The National Endowment for Democracy is a Washington D.C-based non-profit, funded by the U.S. national budget to subvert real democracy wherever it threatens to stay established. In particular they spend millions of dollars of taxpayer money every year in Venezuela to delegitmatize and destabilize Chavez’s democratically elected government. The U.S. media, showing all their characteristic perspicacity and integrity, faithfully all spout this same “party line” and forbid any alternative view. But not Cindy. Today, with this absolutely marvelous interview, she gives us all some deeper insight into the realities of life and viewpoint in Chavez’s “communist dictatorship” - while back at home in “the freest nation on earth” our President keeps us safe by killing us - if we’re suspects - and all without any namby-pamby trials. This perspective is worthwhile plus, and usually unavailable to us.
By Tennessee-Socialist, March 30, 2010 at 6:20... Ver más D.R. Zing, March 30, 2010 at 6:03 pm Link to this comment
Bowie wrote this circa 1979. It always sounds a little bit like “fascists” to me.
—
Fashion
David Bowie
Scary Monsters
There’s a brand new dance
But I don’t know it’s name
That people from bad homes
Do again and again
It’s big and it’s bland
Full tension and fear
They do it over there
But we don’t do it here
Fashion - Turn to the left
Fashion - Turn to the right
There’s a brand new talk
But it’s not very clear
That people from good homes
Are talking this year
It’s loud and it’s tasteless
I’ve not heard it before
Shout it while you’re dancing
On the -er dance floor
Oop bop - do do do do do do do do
Fa fa fa fa fashion
By Tennessee-Socialist, March 30, 2010 at 4:30 gerard, March 30, 2010 at 3:47 pm Link to this comment
Taowalker: It saddens me a lot to read your prevous post above. I hope you will reconsider and stay with me/us. I recognize your feelings of frustration and a desire to quit trying, but ... if we drop (along with several other people who are trying to keep this site from dropping into the depths of negativism,) TD will sink under the black weight of negative diatribes. Our vocabularies are different, yours and mine, but along with similar others, I think we are needed here. Many times I despair—and then I am called back by a voice saying “You never know where thoughts take root.”
Please reconsider, and stay with me/us.
By Samson, March 30, 2010 at 3:39 pm Link to this comment
One sign of the hatred and propaganda is the quickness to attack anyone who dares to stray from the party line.
When I read a thread that tells me that both Chris Hedges and Cynthia McKinney are really right-wingers, I can only crack up laughing.
But this is the treatment given to anyone these days who doesn’t just chant a very shallow party line at all times.
By freethot, March 30, 2010 at 3:28 pm Link to this comment
I don’t see any hate from the Democratic side…it’s all Rightwing!
I always suspected Hedges of being a Rightie pretending to be a moderate…
He’s been in opposition to Liberal thinkers in every debate I’ve ever seen him in….plus he seems incapable of smiling!
Expect him as a regular on Fox Newz any day now…he’s not a happy camper…....
By TAO Walker, March 30, 2010 at 3:18 pm Link to this comment
This Old Savage isn’t “gloating,” as plainsman suggests, about the mostly self-inflicted suffering our tame Sisters and Brothers are in the throes-of these Days….even that of theamericanpeople, who’ve been mere tools in the efforts of the tormentors to “subdue the earth.” It’s the plain facts of their condition, not any make-believe moral-ism, that prompt observations offered here.
The Tiyoshpaye Way has been described often on this site as the Lakotah word for the natural organic FORM of Humanity withion the Living Arrangement of our Mother Earth. That form (Call it in English: Genuine Living Human Community.) is in-keeping with the effective fulfillment of our given organic FUNCTION as vital components in Her immune system. There’s no “mystery” in any of it….just plain basic biology.
There isn’t really much more to say about The Tiyoshpaye Way, as such. It once prevailed all over the World, and no one even had any words for it….or needed any. It can’t be “built” or “instituted.” It occurs naturally or not at all.
The “bread-and-butter” of truthdig seems to be in catering to the appetites for fake fright and righteous indignation that titillate the still relatively comfortable peers of its publishers. Happening on it one Day, this Old Indian had the impression of the focus being a sincere discussion of The Situation with a view to coming to some mutual understandings about its shape and content….which would then naturally suggest mutual responses with some potential for helping us all go on Living together, which has always been the basic agreement in our Council Circles.
Since then, however, it appears more-and-more to be just another gathering place for those much more interested in preserving their own comforts and CONveniences, on terms they like. In-short, it is the haunt of those with axes-to-grind and positions to defend….not those truly interested in digging-into the truth unless it reinforces they’re cherished pre-CONceptions of what ‘truth’ is.
It looks like we’ve passed a kind of point-of-no-return (beyond which further offerings will be to no good purpose), anyhow. With the High Ceremonial Season approaching here in Indian Country it is probably time to let what’s out there now do what it will to alert some to a Way through these latter-day difficulties….call them: The Eye of The Needle.
See you all, sooner or later, on The Other Side.
HokaHey!
By Samson, March 30, 2010 at 2:54 pm Link to this comment
One would think that having watched the country go from Bush to Clinton to Bush to Obama that by now people would start to figure out that nothing much really changes as the party in power switches back and forth from Democrat to Republican.
Yet, there is such an effort to make everyone afraid of there being another Republican president.
What might happen ... do you think a Republican might escalate the war in Afghanistan? do you think a Republican president might give hundreds of billions of our public treasury to Wall Street? do you think a Republican might refuse to prosecute the criminals on wall street who’s frauds crashed the economy? do you think a Republican might push a health care bill that really just makes the corporations richer at the people’s expense?
If you pay close attention, the major policies haven’t changed since Reagan beat Carter in 1980.
Beware the politics of fear. Both parties use this to try to con voters into voting them into power. So the Republicans scream that Obama is a socialist and the Democrats scream that the Republicans are the next coming of Hitler.
But, the illusion is shattered when you realize that very little changes when one party defeats the other in an election.
By Samson, March 30, 2010 at 2:48 pm Link to this comment
There’s an old technique called ‘Divide and Conquer’.
In America, there’s a corrupt group who has control of the government. The political system is set to allow the government to be bought, and thus the government functions for the benefit of those with the money to buy it.
This of course generates opposition from the people who believe that this is a democracy and thus have the strange notion that the government should be responsive to the people.
Maybe once there was a left-right political spectrum, but these days its just the group in power versus all-comers. But since people still believe the notion of a left-right political spectrum, some of the opposition views themselves as being on the left, and others in the opposition view themselves as being on the right.
Those in power of course try to make sure these two groups never hook up. So, one sees a lot of effort trying to convince those on the right that the left opposition is a bunch of communists. And one also sees a lot of effort on the left deriding the right opposition now as ‘tea-baggers’.
This has not only the benefit of keeping the opposition divided and thus more easily conquerable, but its also used to try to convince each side to accept the rule of the corrupt people in power due to the myth that the other opposition would be even worse. So, the right are rallied to vote for the corrupt by the fear that the ‘communists’ will take charge, and the left are rallied to vote for the corrupt by the fear that the ‘tea-baggers’ will take charge.
———————————————-
Last month, Obama came to Denver. So I went out to protest. The protest area was about equally divided with groups from the left and the right.
I made a deliberate effort to go over and talk with the ‘tea-baggers’. Much of what they say is exactly what you can read from the leftist comments on a site like this. I’d guess as much as 80%.
Now, I did find that in order to hold a civil conversation, I had to bite my tongue on a few things they said. And, I’m pretty sure I saw some tongue biting going on over things I said at times also.
But, I’d encourage anyone to go do the same. Go find what the ‘tea-baggers’ are up to in your area, then go talk with them. If you take the time to talk to real people, instead of just reading the propaganda that’s churned out, you might be very surprised to find out that what they are upset about are pretty much the things that you are upset about.
You won’t agree on everything. But ask yourself this. Is there enough there that you agree on that two groups could maybe work together to throw our current corrupt government out of power.
———————-
One thing is clear. Right now, neither the left opposition nor the right opposition has enough power to create the change they want on their own. In fact, the corrupt group running our government is so powerful that it may not be enough to combine forces.
But, surely the chances are better if we can find a way to work together? And, you might ask yourself why does there seem to be such massive efforts to make sure that doesn’t happen.
By truedigger3, March 30, 2010 at 2:21 pm Link to this comment
Re:By nemesis2010, March 30 at 2:50 pm #
This is an excellent post. | http://www.truthdig.com/report/item/is_america_yearning_for_fascism_20100329?ln | CC-MAIN-2017-09 | refinedweb | 15,733 | 61.87 |
In order for a GCC developer to fix a bug, the bug must be reproducible by means of a self-contained test case. Our bug reporting instructions ask for the preprocessed version of the file that triggers the bug. Often this file is very large; there are several reasons for making it as small as possible:
There are basically two methods: either directly construct a new testcase that reproduces the bug, or iteratively reduce the original testcase. It is possible to automatically reduce testcases. Most test cases can be reduced to fewer than 30 lines!
Always try a direct approach before resorting to the brute-force method of minimizing a large test case:
printf), specify the function's declaration directly rather than including a header file.
The brute force approach is simply an iterative method to cut down
on the size of the test case by deleting chunks of code. After each
attempt to shorten the test case, check whether the bug still is
evident. If not, back out to the previous version that demonstrated
the bug. For this, either use the undo function of your editor, or use
frequent backup files; alternatively, you can use
#if 0
and
#endif. The automatic and recommended way to
reduce
a testcase is using the Delta tool.
If you have access to the original sources, it is better to start with the original sources and when those cannot be reduced further, generate and reduce the preprocessed sources. Both methods are described below.
Copy the original source file, plus header files that you might need to modify, to a separate location where you can duplicate the failure. Try the following, backing up from the unsuccessful attempts.
inlinedirective or write a dummy function to call it.
printfand declare it directly:
extern "C" int printf(const char *, ...);.
int,
double).
#includedirectives, or replace them with only the code that is needed from the included file to compile the main file.
Usually, the file will now be down to fewer than 30 lines, plus includes. Repeat the same steps with remaining included header files. To reduce the number of files you are working on, you can directly include the content of the header file into the source file you are working on.
In the next step, run the compiler with
-save-temps to get the
preprocessed source file.
The preprocessed file contains lines starting with
#
that tell the compiler the original file and line number of each line
of code. Remove these file and line directives from the preprocessed file so
that the compiler will report locations in the preprocessed file, using one
of the following:
cat bug.ii | grep -v '^# .*$' | grep -v '^[[:space:]]*$' > bug2.ii
perl -pi -e 's/^#.*\n//g;' bug.ii
sed '/^#/d' bug.ii > bug2.ii
vi:
:g/^#/d
The preprocessed sources will now consist largely of header files. Follow the same steps as for stripping the original code, with these additional techniques.
extern "C"blocks, or blocks enclosed in
namespace XXX {...}.
At this stage, you will be able to delete chunks of hundreds or even thousands of lines at a time and can quickly reduce the preprocessed sources to something small.
Copyright (C) Free Software Foundation, Inc. Verbatim copying and distribution of this entire article is permitted in any medium, provided this notice is preserved.
These pages are maintained by the GCC team. Last modified 2014-06-28. | http://www.gnu.org/software/gcc/bugs/minimize.html | CC-MAIN-2014-35 | refinedweb | 565 | 64.41 |
Dear users/developers,
I'm trying to find out how to use OStream() objects in PyRosetta. This is necessary for certain functions, e.g. ConstraintSet().show_violations() must take an OStream() object.
I saw that you cannot use rosetta.utility.OStream() directly, what is the recommended way then to get an OStream to e.g. sys.stdout or stderr?
Or is it possible to use show_violations() without OStream?
Thanks!
The ostream objects the show() functions typically are meant to accept are basic.Tracer objects, which Rosetta uses to print information to the standard output. I believe you should be able to instantiate one in Python and then pass it into any function which expects an ostream. Note that you may need to call the .flush_all_channels() method of the object to get the stored output to display.
As Rocco mentioned you should be able to use Tracer objects. For example of constructing one please see test/T007_TracerIO.py in your PyRosetta build.
Thanks for the replies! So I tried the following in ipython. I forgot to mention that I was using PyRosetta compiled from the Rosetta 3.4, which makes it I think 2.011.
from rosetta import *
init()
cio = rosetta.core.scoring.constraints.ConstraintIO.get_instance()
from rosetta.core.scoring.constraints import ConstraintSet
cst2 = ConstraintSet()
pose = pose_from_pdb("protein.pdb")
cio.read_constraints_new("ecs2.cst", cst2, pose)
tr = rosetta.basic.Tracer()
cst2.show_violations(tr, pose, 10)
The last command gave me this:
ArgumentError: Python argument types in
ConstraintSet.show_violations(ConstraintSet, Tracer, Pose, int)
did not match C++ signature:
show_violations(core::scoring::constraints::ConstraintSet {lvalue}, core::pose::Pose {lvalue} pose, unsigned long verbose_level, double threshold=1)
show_violations(ConstraintSet_exposer_callback {lvalue}, std::ostream {lvalue} out, core::pose::Pose {lvalue} , unsigned long verbose_level, double threshold=1)
show_violations(core::scoring::constraints::ConstraintSet {lvalue}, std::ostream {lvalue} out, core::pose::Pose {lvalue} , unsigned long verbose_level, double threshold=1)
The first prototype is just a wrapper that I wrote in the .hh file to drop the requirement on OStream. The last one should be the applicable prototype but it seems like it doesn't like a Tracer object instead of an OStream. | https://www.rosettacommons.org/node/3588 | CC-MAIN-2020-50 | refinedweb | 351 | 51.85 |
If you're interested in learning how to make an app, the Sencha Touch framework makes it easy to build awesome multiplatform, touch-enabled applications. We'll use it to build 'Do I need my Umbrella?' – an app using weather information from to determine if you need said umbrella.
You can see the app itself here, while the code can be found in this GitHub repo: the solution-tutorial directory contains the raw code, the final directory the code plus a Sass template. In addition, the goodies-tutorial directory on the repo contains the files you will need as you work through the tutorial.
Generate and run the demo application
Start by creating a sencha folder somewhere on your hard disk. Download the Sencha Touch 2.2.1 framework and extract it into the newly created sencha folder. Now create the folder for your app. I've called mine dinmu as it's shorter than 'DoINeedMyUmbrella', but it's up to you.
Now open your command line (MS-DOS Prompt or Terminal), navigate to the Sencha framework folder (cd sencha/touch-2.2.x folder) and run the following command to generate your Sencha Touch MVC folder structure:
sencha generate app -name Dinmu -path ../dinmu
This command generates your app's full MVC structure. It takes a namespace Dinmu, to prefix all your classes. Review the folder structure it has created.
Now it's time to start your webserver via the command line, using the command below, and replacing the filepath at the end with the path to your own sencha folder. (If you would rather use your own Apache webserver, start it yourself and skip this step.) On Mac OS X, you might need permissions for executing the command: if you run into permission errors, prefix it with sudo.
sencha fs web -p 80 start -map /path/to/sencha/folder/
This will start your built-in Jetty webserver. You need your CLI window open to keep the server running, so it makes sense to open a new CLI window for the next of our command-line commands.
Test the app: in a modern browser, run. You should see the Sencha demo app interface with a bottom tab panel and two slides.
The data package
In the next few steps you'll -name Setting –fields id,city,country,units,geo:boolean
This command generates the model for your app. It takes the classname Setting and one string with all the field names to define all the different fields. id field will define ids for every model record in your application. To let it behave as a unique ID, you will need to configure it. Before the fields array, configure an idProperty and an identifier:
idProperty: 'id', identifier: 'uuid',
The logics for these unique IDs are in a Sencha class we need to 'import' into our app. We can use a requires: it needs the class Ext.data.identifier.Uuid.
requires: ['Ext.data.identifier.Uuid'],
The next step is to create some validations for our model by creating a validations array after the fields array. This contains two validation objects to check whether the data for these fields is present:
validations: [{ type: 'presence', field: 'city', message: "Please provide a city." }, { type: 'presence', field: 'country', message: "Please provide a country." } ],
As we want to save the local settings data to the device, the last step is to add a client proxy. We will use localstorage for this. The localstorage proxy will make sure that all the data will persist into the browser localstorage. Define the proxy object directly after the validations array:
proxy: { type: 'localstorage', id: 'weathersettings' }
The view components
The standard tab panel interface Sencha Cmd generates looks nice, but Do I need my Umbrella? needs a carousel. Open app/view/Main.js in your IDE or text editor: Dinmu.view.Main extends from the Sencha Touch Ext.tab.Panel class. It has a tabBarPosition property to add the tabs to the screen bottom.
We don't need this, so can remove tabBarPosition: bottom and change the extend to Ext.Carousel, to extend from the Sencha Touch Carousel class. Open your browser and run. You'll see the Sencha demo app, with the tab interface replaced by a carousel. You can slide views horizontally.
Let's remove more default components. You won't need the demo video, so remove the Ext.Video from the requires array. Empty the items array, since we'll replace it for two new items. The first item object (a container by default) contains only the html property. This can be set to a placeholder text (Settings) so you know that you can code it later. The second item object has a property itemId: 'mainview' and a cls property (for styling) set to the value textview. You need to add a direction property, to set the Carousel direction to vertical:
Ext.define('Dinmu.view.Main', { extend: 'Ext.Carousel', xtype: 'main', requires: [ 'Ext.TitleBar', ], config: { direction: 'vertical', items: [{ html: 'Settings' }, { itemId: 'mainview', cls: 'textview' } ] } });
Viewed in a browser, the app looks basic. Let's add a top titlebar and a bottom toolbar. Before the item with the Settings placeholder, create a new object:
{ xtype: 'titlebar', cls: 'title', docked: 'top', title: 'Do I need my Umbrella?' },
Let's do the same for the bottom toolbar: the xtype is toolbar not titlebar, and instead of the title property we'll use an html property set to a copyright string of our choosing, with a ui property set to light. Add Ext.Toolbar to the requires array in the top of the file, so the correct framework class loads into memory.
{ xtype: 'toolbar', cls: 'footer', ui: 'light', docked: 'bottom', html: '<span>Powered by © Sencha Touch</span>' },
Next we'll create some buttons in the top titlebar. Below the title, add an array containing a back button, which will be displayed when you're on the settings screen, and a settings button, to be shown on the default screen. You needn't set the xtype to button, since the default items of an Ext.TitleBar are buttons. The back button is hidden by default and is left-aligned in the titlebar. The settings button shows an icon of a settings gear; it's right-aligned:
items: [{ cls: 'back', hidden: true, ui: 'back', action: 'back', align: 'left', text: 'back' }, { iconCls: 'settings', action: 'settings', ui: 'plain', align: 'right' }]
Open your browser and run: again. You should see a button with a gear in the right-hand corner of the Ext.TitleBar.
Creating forms
Now we can start with creating a form. Navigate to the dinmu folder on the command line and run the following to generate your Sencha Touch form:
sencha generate form -name SettingsView -fields geo:toggle,units: select,city,country
Review the form class that's been scaffolded. Open app/view/SettingsView.js. The Dinmu.view.SettingsView class has an xtype set to settingsview. You can assign custom classes to item arrays with the xtype property. Let's do so now.
Open Dinmu.view.Main (app/view/Main.js), and find the settings item in your code. By default, if you don't specify its xtype, it's set to container. You'll need to refer to the new xtype, settingsview, so add xtype: 'settingsview' to the code. The placeholder string isn't needed any more: remove the html: settings property. Don't forget to add Dinmu.view.SettingsView to the requires array.
To make the form look better, let's add a fieldset to Ext.form.Panel. This contains the four new fields and the submit button. The fieldset will be a child of the formpanel, and has its own children: the form fields and the button.
Back in SettingsView.js, create a second items array in the config object (after the title property.) Nest the new items array as a child. The parent items array contains one fieldset xtype, with a title (Your location), and a line with instructions; the child array contains all of the fields and the button. The code should look like this:
Ext.define('Dinmu.view.SettingsView', { extend: 'Ext.form.Panel', xtype: 'settingsview', config: { items: [{ xtype: 'fieldset', title: 'Your location', instructions: "In case you do not want the app to detect your location, you can prefill the city and country.", items: [ //form fields here ] } ] } });
Open your browser and run. You'll see the select unit field has no values. Let's add some values to the units selectfield. Create an options array with two objects with text Celsius and Fahrenheit, and values c and f. The label GEO in the togglefield makes little sense. Change it to Detect location? As the text of the label now takes up far more space, we'll set the labelWidth to 55%. Set the value of the geo field to value: '1' to enable geolocation by default. Change the labels of all the other fields to lower case and disable the city and country fields by adding disabled:true to both fields. The button text should be Refresh instead of Submit. Change this in the button component. Add a margin with the value 10 5. Add an action property to the button and set it to refresh. This way, we can reference the button later.
{ xtype: 'button', ui: 'confirm', margin: '10 5', action: 'refresh', text: 'Refresh' }
You might notice the console outputting some warnings. The Ext.Loader, the mechanism that loads' ],
The interface is finished. But what about the main view? You'll dynamically prefill this page with data;:
sencha generate controller Main
This command generates the Main controller. Open app/controller/Main.js: you'll see a controller with empty references (refs) and control objects.]' },
Now these events, you must hook the controller to app.js. Open app.js, create a controllers array below the requires array, and pass in the string 'Main', mapping the Main controller to the app/controller/Main.js file:
controllers: [ 'Main' ],
Now we'll add some logics. Go back to Dinmu.controller.Main and add the functions I've written for you in the goodies-tutorial directory on the GitHub repo. You can find them in functions.txt.
Setting up stores and static methods. In it we'll define a new class, Dinmu.store.Settings: this class extends all the methods and properties from the Ext.data.Store class. In the config object, we will create a property called model. It should connect to the Setting model. The settings store also needs to load automatically:
Ext.define('Dinmu.store.Settings', { extend: 'Ext.data.Store', requires: ['Dinmu.model.Setting'], config: { model: 'Dinmu.model.Setting', autoLoad: true } });
Open app/controller/Main.js. In the config object, create a stores array and add the Dinmu.store.Settings store to it:
stores: 'Dinmu.store.Settings',
Sometimes it's nice to set up your business logics outside the MVC folders. In the app folder, create a folder called utils. In it, create a file named Functions.js, and define a class called Dinmu.utils.Functions. This has a property, singleton, set to true. Now your class is a singleton: you can't create any instances of it, but can run the static methods from everywhere in your code:
Ext.define('Dinmu.utils.Functions', { singleton: true, //statics methods here });
Add Dinmu.utils.Functions to the requires array of app.js. Now add some statics functions. Open the functions.txt snippet from the goodies-tutorial directory on the GitHub repo, and copy all the functions into the app/utils/Functions.js file.
The snippet contains the functions you need for requesting weather data from. If you'd rather use your own API_KEY, you can edit it on top of Functions.js by changing the string for the API_KEY property. It also contains logics for requesting geolocation on the device and prefilling the template in the main view (I have commented the text for you).
To test the logics, open Chrome DevTools, switch to the Console tab, and type Dinmu.utils.Functions.getWeather('Amsterdam'). The app should return a weather object for Amsterdam, and display some text in the main view. The app is finished! Open your browser and run again.
Words: Lee Boonstra
This article originally appeared in net magazine issue 247. | https://www.creativebloq.com/app-design/build-your-own-weather-app-sencha-touch-51411609 | CC-MAIN-2020-34 | refinedweb | 2,041 | 66.74 |
WCF WSDL generated paths for xsd:schema, wsdl:import, soap:address wrong for WCF behind a firewall.
- Wednesday, May 24, 2006 8:11 PM
My WCF server is behind a firewall
but the schema locations are incorrect in the wsdl
<xsd:schema
<xsd:import
<xsd:import
<xsd:import
</xsd:schema>
How do I change this to generate schemaLocation="" for all of these above.
I also have the same question for wsdl:import and soap:address.
<wsdl:import
<soap:address
Thanks for any info.
All Replies
- Monday, June 12, 2006 8:21 PMModerator
You can setup your service to use a static wsdl with the correct addresses by using the ExternalMetadataLocation property on the ServiceMetadataBehavior.
Daniel Roth
- Friday, August 17, 2007 12:18 AM
When i set ExternalMetaDataLocation property on the ServiceMetaDataBehaviour to
When i test the service and click the link, page can not be found error is coming.
using the below also not working.
<host>
<baseAddresses>
<add baseAddress= />
</baseAddresses>
</host>
Can anyone help me how can i display ip address instead of machine name for the link to .svc wsdl while testing the WCF service?
Thanks in advance
- Friday, August 17, 2007 12:48 AMI have posted the same question, and I do not think there is a way to do that - hopefully Microsoft will implement this shortly (ie., an additional parameter to the .svc file, specifying a domain name to be used instead of the machine name). I was forced to set the ExternalMetaDataLocation property to a static wsdl, and also create the xsd files and put all files in the virtual directory for the web service. The reason you have to create the xsd file(s), is the .svc file that generates these files is not correct due to the machine name thing. I was able to create the xsd file(s) by hitting the link in the wsdl (...?xsd) on my browser and saving the file to disk.
- Friday, August 17, 2007 6:28 PM
Thanks for your reply. Can you suggest me the file name and extension to be used for xsd files to save in the virtual directory folder? Do we need to save the wsdl file also? Any changes required (like schema url) in xsd or wsdl while saving?
Can you provide me the steps required to do this?
--Thanks
- Friday, August 17, 2007 7:06 PM
1) Produce the wsdl in the browser and save to file (by hitting .svc?wsdl from browser)
2) Produce the xsd files by hitting url from wsdl (xsd=xsd0, etc), and save to file from browser
3) replace all machine name references from wsdl with domain name (or ip address) and change xsd references and save
4) replace all machine name references from xsd files with domain name (or ip address)
5) make sure to name xsd file with .xsd extension (ie, name_0.xsd, name_1.xsd)
6) copy wsdl and xsd file(s) to virtual directory
7) add the following entry in your web.config file:
<behaviors>
<serviceBehaviors>
<behavior name="CallRoutingBehavior">
<serviceMetadata httpsGetEnabled="true" externalMetadataLocation=""/>
</behavior>
</serviceBehaviors>
</behaviors>
- Friday, August 17, 2007 7:23 PM...or just run disco.exe on the ?wsdl and it downloads it all and then tweak it.
- Friday, August 17, 2007 10:26 PM
Thanks alot. It is working. Sometimes while adding service reference, i m getting error like
Cannot find file "C:\Documents and Settings\padmajab\Local Settings\Temp\23hzb1ps.ym5\Service1.cs".
Service.cs is my WCF service class.
- Friday, August 17, 2007 10:30 PM
When i give
externalMetadataLocation=,
i am getting the error as
Cannot find file "C:\Documents and Settings\padmajab\Local Settings\Temp\23hzb1ps.ym5\Service1.cs".
When i use externalMetadataLocation = , everything is working perfect.
Thank you so much.
- Friday, August 17, 2007 10:33 PM
create the cs file by calling svcutil and passing the wsdl as the parameter, or you can try add web reference instead of add reference.
Your welcome,
John Shore
- Monday, August 20, 2007 8:33 PM
Can you tell how you have configured the service in .config file to get the wsdl and xsd's with IP address.
My problem is exactly opposite to you. I need to create wsdl and xsd with url includes ip like your created files. My wsdl and xsd's got created refering the machine name by default when i click file.svc?wsdl in service test page.
Can you help me?
- Monday, August 20, 2007 10:22 PM
You have to follow these steps:
- Monday, September 24, 2007 4:51 PM
I have something similar I believe. Here is our situation:
We have a development server named DVL01. For each project we create a new web site and a DNS entry on our DNS server that points to that website.
For each project we also create a new Application Pool and a new service account in the Active Directory that will be used to set the security context of the application pool.
Next we create a Service Principal Name (SPN) in the Active Directory so that this service account can only be used in a specific correct context.
Eg:
We have a project called ProjectX. When we navigate to it will be resolved to. Navigating directly to gives a 401 (unauthorised) which is exactly what we want, that is the SPN kicking in. The problem now is that in the WSDL the schemaLocation for the XSD's point to and this gives a 401 (again SPN). The correct URI should be.
I have tried chaning the host header value, I have also tried adding a baseAddress in the web.config but nothing seems to help.
Are you trying to say that this is not possible by configuration?
- Monday, September 24, 2007 5:21 PM.
- Tuesday, September 25, 2007 5:21 AMI already tried that but that doesn't change the uri of the schemaLocation it still points to instead of
- Thursday, November 29, 2007 3:08 AMAnyone know if anything has been done to resolve this problem?
- Friday, February 22, 2008 3:22 AMI can't find any way to fix this, I've spent the day going crazy over this stupid rediculous issue. How can they not view this as an issue that needs to be fixed? ARGH!!
- Friday, February 22, 2008 4:35 AM.
Also, you have to open up the security to c:\windows\temp since this is where WCF creates the temp files.
- Friday, February 22, 2008 4:09 PM
jvshore, not sure your solution will work for a self hosted (ie outside if IIS) WCF service behind a firewall.
Bottom line there should be a in code and config file way to set what gets generated in the wsdl at runtime, all the comments about generating the wsdl and tweak the content are defeating the whole purpose of interop with wsdls.
- Friday, February 22, 2008 9:35 PM
I'm glad I found this thread...I've been pulling my hair out for several days trying to figure this out. I believe I'm having the same problem as others here. I finally had a little time to start looking at WCF and I had put together a test service. It worked fine on my dev machine, but once I put it on a server, it will only generate the wsdl with the machine name.
Doesn't matter what I specify for the endpoint address, or the dns identity value, etc...it won't use the IP or domain...it just keeps using the machine name for the wsdl. This is going to be extremely problematic. I guess I can stop wasting my time trying to figure out what the problem is though, and just wait until this is resolved before doing any more WCF stuff.
Not sure why it refuses to honor what I specify in the web.config file.
-Matt
- Thursday, February 28, 2008 11:22 PM
Matt, you may be waiting a long time, I opened this thread going on two years now, well in the beta feedback time before the first RTM release of WCF in .net 3.0. MS did not seem to answer my post or change the code, but I have not tried it on the 3.5.
I have deployed and support many WCF in a production environment today, and the only practical way we have found to deploy it is:
Firewall->Proxy Server->Internal WCF Service.
The proxy server handles the https certificate and also does a search and replace on the internal url with the external on WCF responses, and external url with internal on client WCF request.
Sample
Client- Request -> -> Proxy -> WCF
Client- Response <- <- Proxy <- WCF
The setup works with WSDL client generation, and all request and response traffic.
Just make sure you have the proxy translate all the url lines that are incorrect.
Just info for others incase they want to get going today with WCF, while we wait for an elegant incode solution.
ACHawk
- Sunday, March 02, 2008 11:52 AM
Hello,
I have exactly the same issue. Addresses which are generated in the links for the schemas are not correct.
In order to solve it, I wanted to try the solution of jvshore but could you please describe me how to set the deault host header? I don't have access to my IIS, so I cannot configure it.
Thanks in advance,
Jerome.
- Sunday, March 02, 2008 4:02 PM
I used adsutil.vbs from inetpub\adminscripts:
cscript.exe adsutil.vbs set /w3svc/<site identifier>/SecureBindings ":443:<host header>"
This script set the host header for me for SSL, which you can't do from the UI. You can also set the host header for a site without referring to SSL using this command.
You also have to make sure that you have rights to c:\windows\temp. WCF uses this directory to create the schemas that are generated. If you do not set access rights to this directory, the WSDL will appear correct with the appropriate addresses for the schemas, but the schemas will not be created.
Hope this helps. I spent several weeks with this problem before I got the Microsoft engineers to view the debug files that showed the problem. Now everything is working great.
- Friday, March 07, 2008 10:45 AM
So, by setting the host header, WCF wsdl generation work behind the firewall?
- Tuesday, June 24, 2008 7:01 PMI think I have found a solution to these incorrect schemaLoction url values when the site is controled by a load balencer or firewall. The solution is not fully tested, but appears to work for me so far. You want to open Internet Information Services (IIS) Manager then locate your web. Right click on the web site and go to properties. In the web site properties window select the "Web Site" tab and click on the "Advanced..." button in the "Web site identification" section. Now select your ip address from the "Multiple identities for this Web site" and click "Edit...". This will open the "Add/Edit Web Site Identification" window. You will want to enter the url of your site in the "Host Header value:" textbox. It should be something like. Click "OK" out of all the windows then do an iisreset. This appeared to fix the problem for me.
- Wednesday, June 25, 2008 4:19 PM
This does not work for SSL sites.
- Wednesday, June 25, 2008 4:29 PM
Nor does it work for self hosted WCF solutions which is how this original post was opened ******y me.
******ut MS did not seem to care in their ******eta cycle or now, if anyone has any contacts in the WCF development team may******e they can help on this one.
AC
- Wednesday, June 25, 2008 4:53 PM
1) apparently the html editor on these forums has a bug. Seeing a lot of ******* inserted in text.
2) My admin freaked when I discussed the host headers solution above, so I am going to investigate the static WSDL (YUK).
3) I'm interested in your problem (service host) as I'm sure I'll eventually want to do the same.
- Wednesday, June 25, 2008 5:13 PM
- Monday, June 30, 2008 2:52 PM
Here is the solution that worked for me (thank you Amy at MS!):
1) Implement the Factory attribute to specify the custom ServiceHost in the .svc file:
<% @ServiceHost Language=C# Debug="true" Factory="HelloServiceFactory" Service="HelloService" CodeBehind="~/App_Code/HelloService.cs" %>
2) Create the ServiceFactory “HelloServiceFactory” class as follows:
class HelloServiceFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
HelloServiceHost customServiceHost = new HelloServiceHost(serviceType, baseAddresses);
return customServiceHost;
}
}
class HelloServiceHost : ServiceHost
{
public HelloServiceHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, GetBaseAddresses())
{ }
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
}
// read base addresses from AppSettings in config));
}
}
3) Add the baseHttpAddress to the web.config:
<configuration>
<appSettings>
<add key ="baseHttpAddress" value="<<>>" />
</appSettings>
</configuration>
- Friday, September 26, 2008 5:42 PM
I followed these steps, looks like the wsdl and xsd files are generated with proper references, but the disco file still references internal server name. Is there a way to specify server name in disco file. I manually changed the disco file on our server but I am not sure how to refernce it in web.config.
Please respond if you had the same issue and resolved it.
- Thursday, December 11, 2008 3:17 PM
WOW, I racked my brains out for days too with this same problem. I was starting to get embarrased about suggesting we write services in WCF. My situtation is a WCF service hosted in IIS on a server via HTTPS/SSL but HTTP is turned off. Worked fine on development servers, but as soon as we moved it out to the above setup, none of the clients could resolve the location of the opeations.
At first I thought it was because the server had a self-signed certificate, so we got a legit one. Only helped a little in that then wcftestclient worked fine but none of the ColdFusion or Flex clients would work.
In our environment there is no way to get the admins to add the host header to an SSL site - "hey, can you run this script you've never heard of on a production server hosting dozens of apps all written in different languages." Yea right.
I was about to punt and just re-write the services in ColdFusion or PHP since there seemed to be no way to get the location to match the domain name instead of the machine name by setting something in web.config. Seems really silly.
The static WSDL seemed like a last resort so I tried the Service Host Factory and that worked. I'm not happy about having a var that has to be set for the service outside the service section of config but...
Also funny that the ServiceHost directive in the .svc does not recognize factory attribute in intellisense, but yet it works. Remeber to preface the service host factory class name with its namespace
Factory="MyNampeSpace.MyHostFactory"
Yea, this needs to be fixed.
- Thursday, June 25, 2009 1:15 AM
This solution worked for us! We were rattling our brains on this one for several hours! Thank you!
- Monday, November 02, 2009 6:53 PMAll you have to do is make sure that your host headers have been setup properly in your IIS site. This may have to be done via the IIS Metabase or using the following command line. There are 2 bindings which need to be updated depending on whether you need SSL or not.
adsutil.vbs set W3SVC/1/ServerBindings “:80:”
adsutil.vbs set W3SVC/1/SecureBindings “:443:”
- Saturday, January 16, 2010 1:12 PM
I also had problems with the URLs generated in the WSDL
I fixed this by modifying the webconfig and hardcoding the WSDL path like so (path for the authentication service (yes I will move it to https)):
<serviceBehaviors> <behavior name="AuthenticationServiceTypeBehaviors"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://<sitename>/Services/Authentication.svc/wsdl"/> </behavior> </serviceBehaviors>
Hopefully this will save you some time.
Miro
- Friday, February 05, 2010 3:08 AMI noticed that this is an old post. But I came across this recently and followed the solution that was provided and still had some issues. the short of it is that i found the solution here i thought I would share this.
- Tuesday, November 02, 2010 10:41 AM
Guys, this really is the answer. It is a configurational "error". Kudos for JVShore.
You cannot set the host-header for SSL site via the IIS Manager. The default for your HTTP will be used.
So setting the securebindings using AdsUtils.vbs is the way to go.
I noticed in IIS 7.0 Manager it still is not possible to set the host-header specifically for SSL. You still have to resort to this script.
- Wednesday, March 09, 2011 12:36 AMThank you good sir!
- Wednesday, December 07, 2011 12:18 PM
I am creating a WCF Service on a SharePoint 2010 server.
That WCF Service will be consume in PHP in order to transfer files from PHP to SharePoint.
My issue is that the PHP client is accessing the WCF service from « » but the xsd references in the wsdl is « ».
I have two configurations :
When I create a simple web.config (like below) for my service and I put an externalMetadataLocation to a static wsdl i have created, it works great ! … but i cannot connect to the wcf service if he is on a web application with claims identification !!
SharePoint enables to configure itself the web.config thanks to the Factory MultipleBaseAddressBasicHttpBindingServiceHostFactory, and if i use that Factory, i can connect via Claims to my wcf service but i don’t know how to set the value for externalMetadataLocation.
I tried to create my own custom Factory but can change the parameter ; and futhermore, it only generate a mex instead of a wsdl so i don’t even know if php can use it.
Can you help me please ?
Thank you a lot in advance
<configuration>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior name="CustomUploadBehavior">
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceMetadata httpGetEnabled="true" externalMetadataLocation="" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="CustomBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="CustomUploadBehavior "
name="CustomUpload">
<endpoint address="" binding="basicHttpBinding" contract="MyAssembly.ICustomUpload" bindingConfiguration="CustomBinding">
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
MOSS | http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/c7fd51a2-773e-41d4-95a0-244e925597fe/#page:2 | crawl-003 | refinedweb | 3,078 | 63.49 |
Ron,
If you want to develop your own custom adaptor around the log4net API
then the best way to do this is to write an extension. By the sounds of
it you have already done this, and this is still the right way to do it.
I am not sure how to implement this better at the moment given that the
intention is to provide strongly types methods to looking up the logger
wrapper objects. We may be able to use generics in cli 2.0 to leverage
some code reuse in the LogManager/TraceLogManager.
The ILog/LogManager classes are actually just an extension, the only
difference between these and any 3rd party extension is they are
included in the standard log4net distribution.
There are examples of extensions in the download at extensions\net\1.0.
The net\1.0 may be confusing, but it is used to indicate that the code
is portable across all .net runtime platforms - actually this should
probably be changed to cli\1.0 as that is more explicit, we would also
have to update the examples in the same way.
An extension does not have to extend the ILog interface, however it
should extend the ILoggerWapper interface (the base of the ILog
interface). User may expect you to support the standard ILog interface
in your extension, but that depends on your application. Multiple
extensions can be used side-by-side, therefore the calling app can still
get an ILog implementation over the logger regardless of what other
extensions are in use.
In 1.2.9 changes were made to the LogImpl class to support rebinding
levels in the config file at runtime. This is not the most obvious
feature, but it is actually possible, although not advisable, to swap
the DEBUG and ERROR levels at runtime. The ReloadLevels method was added
to allow the LogImpl to keep up with any changes made to levels during
configuration. The TraceLogImpl overrides the ReloadLevels method to add
the TRACE level, while this is correct behaviour, it is not necessary if
you don't intend to reconfigure your levels at runtime.
If you need further clarification it may be helpful to briefly outline
what does your custom extension does, or what custom APIs does it
provides.
Cheers,
Nicko
> -----Original Message-----
> From: Ron Grabowski [mailto:rongrabowski@yahoo.com]
> Sent: 15 May 2005 20:55
> To: log4net-user@logging.apache.org
> Subject: Wrapping LogManager to make ILog not rely on log4net.ILog
>
> Nicko,
>
> Several months ago I found a post on the SourceForge forums
> that described how to abstract the log4net.ILog interface
> into something like MyProject.Logging.ILog to allow a project
> to change its logging implementation. You provided sample
> code that looked something like
> this:
>
> public class LogManager
> {
> private static readonly WrapperMap s_wrapperMap = new WrapperMap(
> new WrapperCreationHandler(WrapperCreationHandler));
>
> /* snip */
>
> public static ILog GetLogger(string domain, string name) {
> return WrapLogger(LoggerManager.GetLogger(domain, name)); }
> public static ILog GetLogger(Assembly assembly, string name)
> { return WrapLogger(LoggerManager.GetLogger(assembly, name));
> }
> public static ILog GetLogger(Type type) { return
> GetLogger(Assembly.GetCallingAssembly(), type.FullName); }
>
> /* snip */
>
> There is much more code than that but does that give you an
> idea of what I'm talking about? Do you a url for the post you
> made? I can't seem to find it.
>
> Is there a better (more effecient?) way to implement that in
> the new log4net 1.2.9 beta? I found these classes:
>
>
>
et/1.0/log4net.Ext.Trace/cs/src/
>
> I didn't know if that was the correct class to check my code
> again. I saw methods like:
>
> protected override void
> ReloadLevels(log4net.Repository.ILoggerRepository repository)
>
> that I don't have in my LogManager implementation and the
> /net/1.0/ directory structure also caused some confusion.
>
> Thanks,
> Ron
> | http://mail-archives.apache.org/mod_mbox/logging-log4net-user/200505.mbox/%3CDDEB64C8619AC64DBC074208B046611C59CCA2@kronos.neoworks.co.uk%3E | CC-MAIN-2015-18 | refinedweb | 627 | 55.84 |
Hi - Struts
://
Thanks. Hi Soniya,
We can use oracle too in struts...Hi Hi friends,
must for struts in mysql or not necessary... know it is possible to run struts using oracle10g....please reply me fast its
Developing Simple Struts Tiles Application
Developing Simple Struts Tiles Application
... will show you how to develop simple Struts Tiles
Application. You will learn how to setup the Struts Tiles and create example
page with it.
What is Struts
struts
into the database could you please give me one example on this where i i have... technologies like servlets, jsp,and struts.
i am doing one struts application where i...struts hi
Before asking question, i would like to thank you
Hi - Struts
Hi Hi Friends,
Thanks to ur nice responce
I have sub package in the .java file please let me know how it comnpile in window xp please give the command to compile,
what is meant by struts-config.xml and wht are the tags... can we get the struts.jar files and could u give the exact link to get that jar... of struts, u understand wverything
goto google type for strut-blank.jar
)If possible explain me with one example.
Give me reply as soon as possible.
Thank...struts Hi,
i want to develop a struts application,iam using eclipse... for struts ,its well and good
by the way one point i should say you can put.../struts/
Thanks. struts-tiles.tld: This tag library provides tiles
give a default welcomestrutsexample.jsp. plz give a example which work for me.
thanks and regards
Sanjeev Hi friend,
For more information.../struts/
Thanks
hi... - Struts
hi... Hi Friends,
I am installed tomcat5.5 and open the browser and type the command but this is not run please let me... also its very urgent Hi Soniya,
I am sending you a link. I hope
Struts - Struts
it is thread safe? if no, how to make it thread safe? Please give me with good explaination and example? thanks in advance. Hi Friend,
It is not thread...://
Thanks
Struts - Struts
provide the that examples zip.
Thanks and regards
Sanjeev. Hi friend...Struts 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
Struts - Struts
Struts hi
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean... one otherwise returns existing one.then u can put any object value in session
java - Struts
is given below;plse...slove my problem....ok..thanks
If possible ple send u r...java hi..,
i wrote login page with hardcodeted username and password ,but when i submit the page ,i give blank page...
one hint: error
Struts Tag Lib - Struts
Struts Tag Lib Hi
i am a beginner to struts. i dont have to understand the TagLib uri. Any body could you please give me some brief steps reg...://
Thanks
struts
struts how to handle exception handling in struts reatime projects?
can u plz send me one example how to deal with exception?
can u plz send me how to develop our own exception handling
Hi
Hi Hi All,
I am new to roseindia. I want to learn struts. I do not know anything in struts. What exactly is struts and where do we use it. Please help me. Thanks in advance.
Regards,
Deepak
java - Struts
to mark selected one of the option of object. So can u plz send me any code to make this happen. Hi friend,
Plz give full details and full source code to solve the problem.
Thanks
Struts Validation - Struts
Struts Validation Hi friends.....will any one guide me to use the struts validator...
Hi Friend,
Please visit the following links:
http
struts - Struts
the form tag...
but it is giving error..
can you please give me solution...struts hi..
i have a problem regarding the webpage
in the webpage i have 3 submit buttons are there.. in those two are similar and another one
struts validations - Struts
as validation disabled
plz give me reply as soon as possible. Hi friend...struts validations hi friends i an getting an error in tomcat while..._struts_validator.shtml
Thanks
Java - Struts
****
Please give me the suggestion.
And i have one more doubt i.e. how can i use more the one action button in the form using Java script.
please give me...Java
Hi Good Morning,
This is chandra Mohan
I have a problem
Hi... - Struts
Hi... Hi,
If i am using hibernet with struts then require... of this installation Hi friend,
Hibernate is Object-Oriented mapping tool... more information,tutorials and examples on Struts with Hibernate visit
validation - Struts
validation Hi,
Can you give me the instructions about... information,
Thanks... form.but i don't want the username to be duplicated.means one username must be entered
Single thread model in Struts - Struts
Single thread model in Struts
Hi Friends,
Can u acheive singleThreadModel , ThreadSafe in Struts
if so plx explain me. Hi
Struts 1 Actions are singletons therefore they must Architecture - Struts
Struts Architecture
Hi Friends,
Can u give clear struts architecture with flow. Hi friend,
Struts is an open source.../StrutsArchitecture.shtml - Struts
Struts hi,
I am new in struts concept.so, please explain example login application in struts web based application with source code... explain and details send to me. Hi friend,
Please add struts.jar
Struts - Framework
struts application ?
Before that what kind of things necessary to learn
and can u tell me clearly sir/madam? Hi friend... on struts visit to :
Thanks
Struts - Struts
Struts Can u giva explanation of Struts with annotation withy an example? Hi friend,
For solving the problem visit to :
Thanks
thanks - Java Beginners
thanks Sir , i am very glad that u r helping me a lot in all... to understood...can u please check it and tell me..becoz
it says that any two... it is giving its own values....
so if u can bare sometime of urs to problem with netbeans - Struts
please give me acton mapping problem solution
Hi Friend,
Please...struts 2 problem with netbeans i made 1 application in struts2 with netbeans but got one errror like
There is no Action mapped for namespace
struts - Struts
struts Hi ,
I have been asked in one of the technical interviews if struts framework is stateless or stateful . I could not answer. Please answer and explain a bit about it how it is achieved.
thanks
kanchan... - Struts
Hi... Hello,
I want to chat facility in roseindia java expert please tell me the process and when available experts please tell me Firstly you open the browser and type the following url in the address bar
Struts - Struts
compelete code.
thanks Hi friend,
Please give details with full...Struts Hello
I like to make a registration form in struts inwhich....
Struts1/Struts2
For more information on struts visit to :
if we have 2 struts-config files - Struts
in u r project. and this xml file in deployed in web-inf folder(same as struts...,
No we cannot have 2 struts-config.xml files. In one case we can use 2... information.
Thanks Code - Struts
But it is not appending..
Can any one help me.
Thanks in Advance...Struts Code Hi
I executed "select * from example" query... using struts . I am placing two links Update and Delete beside each record .
Now I
Struts - Struts
.
Thanks in advance Hi friend,
Please give full details with source code to solve the problem.
For read more information on Struts visit...Struts Hello
I have 2 java pages and 2 jsp pages in struts.
thanks - Development process
. please help me.
thanks in advance...thanks thanks for sending code for connecting jsp with mysql.
I have completed j2se(servlet,jsp and struts). I didn't get job then i have learnt
java - Struts
give me idea how to start with Hi Friend,
Please clarify what do...java hi i m working on a project in which i have to create a page in which i have to give an feature in which one can create a add project template
multiboxes - Struts
onclick event is coded in javascript)...
Can u please give me a solution either in javascript code or in struts bean. Hi friend,
Code to solve
Struts - Framework
struts application ?
Before that what kind of things necessary to learn
and can u tell me clearly sir/madam? Hi
Its good... knowledge of JSP-Servlet, nothing else.
Best of Luck for struts.
Thanks
struts
struts Hi
what is struts flow of 1.2 version struts?
i have struts applicatin then from jsp page how struts application flows
Thanks
Kalins Naik
Please visit the following link:
Struts Tutorial tags
struts tags I want develop web pages using struts tags please help me,but i searched many sites but that sites doesn't give correct information.
examples of struts tags are
Hi Friend,
Please visit the following
Struts Console
visually edit Struts, Tiles and Validator configuration files.
The Struts Console... Struts Console
The Struts Console is a FREE standalone Java Swing
Java - Struts
Java hello friends,
i am using struts, in that i am using tiles... doubt is when we are using struts tiles, is there no posibulity to use action class.....
how can use
plase tel me. thank u.
MVC - Struts
MVC CAN ANYONE GIVE ME A REAL TIME IMPLEMENTATION OF M-V-C ARCHITECTURE WITH A SMALL EXAMPLE...... Hi friend,
Read for more information.
Thanks
struts - Struts
struts what is the use of debug
2 Hi Friend... class.It is having three values:
0- It does not give any debug information.
1....
Thanks
Reply Me - Struts
Reply Me Hi Friends,
Please write the code using form element...because i got error in textbox null value Hi Soniya
Would you... to provide a better solution for you..
Thanks
Struts
Struts How Struts is useful in application development? Where to learn Struts?
Thanks
Hi,
Struts is very useful in writing web... applications.
You can learn Struts at our Struts tutorials section.
Thanks
struts
struts Hi,... please help me out how to store image in database(mysql) using struts
Display Tag Related - Struts
pls give me any suggestion to sort hyperlink values.
for the code reference...Display Tag Related Hi,
I am using display:column to display list... the attributes if i specify sortable = "true". but i have to display one column
struts 1.x
struts 1.x hi... sir. This is sreenu sir. I am learning struts2...
pls telll me sir.?
i using
this tag using but it is not work
pls give me one example
validation problem in struts - Struts
validation problem in struts hi friends...
m working on one project using struts framework. so i made a user login form for user authentication... for your best co-operation .
thanks in advance friends......
Hi
developers, and everyone between.
Thanks.
Hi friends,
Struts is a web... developers, and everyone between.
Thanks.
Hi friends,
Struts...Struts What is Struts?
Hi hriends,
Struts is a web page
Can you give me Hibernate one to one example?
Can you give me Hibernate one to one example? Hello there,
Can you give me a hibernate one to one example that explain the concept and mapping in Hibernate.
Thanks in advance
How to compare two tables, and insert values which r not in one table to another table?
How to compare two tables, and insert values which r not in one table to another table? Hi
I need to compare two tables MainTable and OUTTable... into the main table using jsp. I am doing this program using JSP. Please can you give me
struts internationalisation - Struts
struts internationalisation hi friends
i am doing struts... problem its urgent Hi friend,
Plz give full details and Source... to :
Redirection in struts - Struts
one page to another page in struts.
For Details you can click here:
Thanks...Redirection in struts
Hi Friends
Without
best Struts material - Struts
best Struts material hi ,
I just want to learn basic Struts.Please send me the best link to learn struts concepts
Hi Manju...://
Thanks
struts2 - Struts
for me, can some one help Hi Friend,
Please visit the following...struts2 hello, am trying to create a struts 2 application...
Hope that the above link will be helpful for you.
Thanks
Proplem with select data - Struts
Proplem with select data Hi , Please can u give me a example for display all data from the database (Access or MySql) using Struts
Difference between MVC1 And MVC2 - Struts
Difference between MVC1 And MVC2 HI Friends,Can u Give me difference between mvc1 and mvc2. Thanks Prakash Hi Friend,
Please visit the following link: | http://roseindia.net/tutorialhelp/comment/881 | CC-MAIN-2014-41 | refinedweb | 2,117 | 76.82 |
Suppose we have a positive integer L, which represents the number of levels in a perfect binary tree. The leaf nodes in this perfect binary tree are numbered starting from 1 to n. Where the n is number of leaf nodes. The parent node is the sum of children. Our task is to write a program to print the sum of all of the nodes of this perfect binary tree. So if the tree is like below −
So total sum is 30.
If we see closer, we need to find the sum of all of the nodes. As the leaf nodes are holding values from 1 to n, then we can use the formula n(n+1)/2 to get sum of leaf nodes. As this is perfect binary tree, the sum of each levels will be same. So find the sum of last level, then multiply it with number of levels.
#include<iostream> #include<cmath> using namespace std; int treeSum(int level) { int total_leaves = pow(2, level - 1); int leaf_sum = 0; leaf_sum = (total_leaves * (total_leaves + 1)) / 2; int sum = leaf_sum * level; return sum; } int main() { int levels = 4; cout << "Sum of all nodes for a perfect binary tree with level " << levels << " is: " << treeSum(levels); }
Sum of all nodes for a perfect binary tree with level 4 is: 144 | https://www.tutorialspoint.com/find-sum-of-all-nodes-of-the-given-perfect-binary-tree-in-cplusplus | CC-MAIN-2021-43 | refinedweb | 218 | 77.47 |
21 April 2010 03:18 [Source: ICIS news]
SHANGHAI (ICIS news)--The Borouge II cracker and downstream project at Ruwais in ?xml:namespace>
"The complex is scheduled to start up by the middle of this year, but production will be ramped up in stages, with full capacity of close to 2m tonnes/year of polyolefins is likely to be achieved by the end of this year or early next year," Yau said on the sidelines of the ChinaPlas 2010 exhibition in
Borouge is a joint venture between the Abu Dhabi National Oil Co and
The Borouge II project consists of a 1.5m tonnes/year ethane cracker, 540,000 tonnes/year polyethylene (PE) and 800,000,000 tonnes/year polypropylene (PP). The company is already operating a 600,000 tonne/year PE plant at Ruwais.
The company is also working on a further expansion (Borouge III), which, when completed will increase its polyolefins capacity to 4.5m tonnes | http://www.icis.com/Articles/2010/04/21/9352344/borouge-ii-crackerdownstream-fulls-ops-by-end-2010-or-early-2011.html | CC-MAIN-2014-41 | refinedweb | 158 | 59.16 |
#include <RBD_Object.h>
Definition at line 48 of file RBD_Object.h.
Accumulates into the given arrays all of our point's positions and velocities. Both are given in world space.
Marks that obj is glued to this.
Applies impulses from SIM_Impacts data.
Applies an impulse to this object. This results in an instantaneous change in velocity and angular velocity.
Determines what hard constraints are present at this time step and updates its internal model to reflect theses. We need the end time to be able to acquire non-interpolated objects to handle live pin constraints.
Builds the impulse model matrix for the given world space coordinate. This matrix when multiplied by an impulse will give the change in velocity at that point caused by the impulse.
This takes hard constraints into consideration. Builds the impulse model matrix describing the velocity change at point p given a force at point f. This is Mfp-1 in my naming scheme.
Builds the impulse model matrix describing motion of P on *this given an a force at f on *this. This is Mzfp-1(A) in my naming scheme, where this is Z.
Definition at line 216 of file RBD_Object.h.
Gathers all of our builder requests.
Definition at line 232 of file RBD_Object.h.
Definition at line 243 of file RBD_Object.h.
This returns the bounding box of the object inside it's own frame. This must be transformed by the orientation to get the world bounding box.
Definition at line 251 of file RBD_Object.h.
Definition at line 234 of file RBD_Object.h.
Definition at line 60 of file RBD_Object.h.
Returns our parent object, null if not glued.
Definition at line 111 of file RBD_Object.h.
This returns a list of all the objects that are frozen to us.
Definition at line 237 of file RBD_Object.h.
Definition at line 228 of file RBD_Object.h.
Discover the number of glued subobjects and retrieve a specific one
These cache the common RBD structures so we don't have to look them up every time we fetch them.
Definition at line 56 of file RBD_Object.h.
Calculates the property value at the given world position.
This is the radius of this object from the pivot position. It is thus orientation independent.
Definition at line 66 of file RBD_Object.h.
Definition at line 59 of file RBD_Object.h.
Gets the transform matrix from self to world from stashed state.
Definition at line 57 of file RBD_Object.h.
Returns true if the given object is one of our glue children.
This returns true if we have any frozen sub objects.
Definition at line 248 of file RBD_Object.h.
Calculates the bounding box.
Initialize for collisions.
Updates the state from geometry, unless already calculated.
Calculates the radius, unless already calculated.
Builds the SDF and updates the state from the sdf, unless sdf is already built.
Integrate position. Uses current velocity.
Integrate velocity. Finds & applies all forces.
Return if this object is glued to somewhere else.
Definition at line 126 of file RBD_Object.h.
Returns true if this object can intersect anywhere in space Used for things like implicit planes.
Copies our NewImpact data into Impacts. This is a pass through to SIM_Object, but ensures our cached impact structure is cleared.
Rebuilds the list of affectors for this object. Interpolates the affectors for the given time.
Reloads our impact data structure from the SIM_Object. This must be done whenever preserveImpacts is called.
Removes the constraints added. This restores stuff like the pivot to its original value.
Removes that object as being glued to this.
Restores the full state.
Restores the position of the state using changePosition.
Restores the velocity of the state using changeVelocity.
Definition at line 224 of file RBD_Object.h.
Definition at line 245 of file RBD_Object.h.
Stashes the current state internally.
Definition at line 265 of file RBD_Object.h.
Definition at line 264 of file RBD_Object.h.
Definition at line 259 of file RBD_Object.h.
Definition at line 258 of file RBD_Object.h. | http://www.sidefx.com/docs/hdk/class_r_b_d___object.html | CC-MAIN-2018-30 | refinedweb | 671 | 62.34 |
jGuru Forums
Posted By:
Alexey_Yastremskiy
Posted On:
Tuesday, April 5, 2005 02:11 AM
Hello everybody.
Consider the following class code:
public class test {
public static void main( String s[]) {
double a = 129.7;
double b = 18;
double c = a - b;
System.out.println( a + " - " + b + " = " + c );
}
}
the result will be 111.69999999999999? while expecting just 111.7. If I change a=29.7, then I will get 11.7 as expected. So, the result depends on the operands.
Could you please explain this...
Thanks
Re: confused with double operations
Posted By:
Anonymous
Posted On:
Friday, April 8, 2005 01:26 AM
Rules:
(a) When using double, always assume that the numbers will come out a little wrong!!! If this is not acceptable, you MUST USE BigDecimal (in package java.math)!!!!!
(b) If you want to know what really goes on, read any introduction to computer numerics (and prepared for quite some math). After you have understood all in there, you will know whan you can use doubles safely and when not.
RegardsHarald M. | http://www.jguru.com/forums/view.jsp?EID=1236606 | CC-MAIN-2015-22 | refinedweb | 174 | 68.16 |
What is the best authoritative DNS?
I'm searching for an authoritative DNS for a 10k users network, that would have good webfiltering features. Are there any opensources/cheap solutions?
Thanks for your help :D
See also questions close to this topic
- Flannel overlay network as docker container
How is possible to run flannel as a docker container whether docker need to know flannel subnet? Inside etcd i can configure only network and subnets for flannel but i can't assign them to a particulare node, so after flannel start seems that need to restart docker engine but flannel is inside a running container.
-
- How to notify wifi change system call in C
The C program needs to change the ssid of
wlan0, so I use
iw_set_ext()from
iwlib.h.
But
iw_set_ext()doesn't block until interface is connected.
There is also a way to do
sleep()or busy wait, but I want to use the system call because there is a problem with the program.
Is there a library that calls the callback function when the
wlan0interface is fully connected or waits?
->
- Why DNS lookup take a lot of time in local?
In order to have a quite "similar" approach in local and production, I set up an NGINX that proxy the request to
localhost:port. In production it redirects from
subdomain.example.comto
localhost:port. In local it redirects from
subdomain.example.localto
localhost:portand I changed my host according to :
127.0.0.1 sub1.example.local 127.0.0.1 sub2.example.local . . .
When I'm testing my builds Front-Ends, DNS lookup took a lot of time (10+ seconds) and I wonder why.
Thoughts ?
- InetAddress.isReachable(timeout) cannot reach Host in other Domain
I'm working on a project on creating a pinger that will ping massively around 400 ips given a .csv file. The .csv file is passed to a JTable and for each row of this table I create and run threads that will ping IPs to another domain that the java program is running.
Problem is that none of those IPs cannot be reached through the isReachable() method of the java.net.InetAddress class. I can ping through the ping command from cmd.exe of windows from the same pc that the java program is running the same IPs that the .csv file refers to successfully.
I have used 3 different methods to test my program (the original isReachable(), one method that uses sockets that tries to open a socket on port 7, and last method that uses the Windows ping command) and only the one that uses the ping command of windows manages to reach all of the IPs.
That said the program works but it uses too much resources given that for each thread now I do open a process for the Win ping command to work. Plus as I am measuring the response time for the ping it comes out to be away from the real ping command.
Note that using the isReachable() method of Java and editing the .csv file on the IP section giving an external IP for or so it does respond nicely. Only those IPs on another domain do not respond. I have asked the administrators to open the path from Firewall on ICMP, TCP/UDP ports 7,22 to test again my program (not yet implemented) to see if I have more luck with it.
My question is what is wrong with using the InetAddress.isReachable() on Domain (172.) to Domain (10.) base and if there is more to ask from the admin team so the method can do what is designed to.
I'm pasting the code of my thread bellow:
package my.pinger3; import java.io.IOException; import javax.swing.JTable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; public class PingerThread3 implements Runnable { //Declaring global variables JTable jt; int timeout = 400; //Initialise values to something resonable int sleepTime = 10000; //Initialise values to something resonable long startTime; long endTime; boolean boolVal = false; int countAll; int countFailed; int row = 0; final int COL_IP = 2; final int COL_DEL = 3; final int COL_SEN = 4; final int COL_OK = 5; final int COL_REA = 6; //Define the openPort var that tells the isReachable() method what port to use for socket connection final int openPort = 7; //Use the 7port as some say that is the open port for ICMP //Constructor PingerThread3(JTable jt, int row, int timeout, int sleepTime) { super(); this.jt = jt; this.row = row; this.timeout = timeout; this.sleepTime = sleepTime; //Initialise global variables startTime = 0; endTime = 0; countAll = 0; countFailed = 0; } @Override public void run() { try { //InetAddress address = InetAddress.getByName((String) jt.getValueAt(row, COL_IP)); //System.out.println((String)jt.getValueAt(row, COL)); while (true) { //Catch the time before reachable() method is called startTime = System.currentTimeMillis(); //Check if the address is reachable /* Use the InetAddress isReachable(timeout) method through isReachable(address) */ //boolVal = isReachable(address); /* Use the socket isReachsble Version method */ //boolVal = isReachable(jt.getValueAt(row, COL_IP).toString(), openPort, timeout); /* Use the hardcoded Widnows ping command method */ boolVal = isReachable(jt.getValueAt(row, COL_IP).toString()); //Catch the time after reachable() method has been called endTime = System.currentTimeMillis(); //Display the Delay column data in the specific cell jt.setValueAt((Long) (endTime - startTime), row, COL_DEL); /* Display the number of times the reachable() was called which actually is not equal to the number of requests done on the IP (ICMP port 7) given. */ jt.setValueAt((Integer) countAll, row, COL_SEN); if (boolVal) { jt.setValueAt("reached", row, COL_REA); } else { jt.setValueAt("NOT reached", row, COL_REA); //Increase the counter for failed operations countFailed++; //Set the color of this cell to red } //Display the %OK of packets send/received jt.setValueAt(calcOK(countAll, countFailed), row, COL_OK); Thread.sleep(sleepTime); } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException ex) { Logger.getLogger(PingerThread3.class.getName()).log(Level.SEVERE, null, ex); } } /* The InetAddress isReachable() method */ private boolean isReachable(InetAddress ia) { Boolean boolLocalVal = false; try { boolLocalVal = ia.isReachable(timeout); //increase the counter for all calls of this method countAll++; } catch (IOException e) { e.printStackTrace(); } return boolLocalVal; } /* The Socket version of isReachable */ private boolean isReachable(String addr, int openPort, int timeOutMillis) throws IOException { // Any Open port on other machine // openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc. Socket soc = new Socket(); try { countAll++; soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis); return true; } catch (IOException ex) { ex.printStackTrace(); return false; }finally { soc.close(); } } /* The hard coded Windows ping version of isReachable() note that this is the worst solution in resources and accuracy based observations */ private boolean isReachable(String add) throws IOException, InterruptedException { countAll++; // in case of Linux change the 'n' to 'c' Process p1 = java.lang.Runtime.getRuntime().exec("ping -n 1 "+add); int returnVal = p1.waitFor(); boolean reachable = (returnVal == 0); p1.destroy(); return reachable; } /* Method to calculate the %packet success. Note though that I might have to use Long.valueOf(i.longValue()) in order to convert Integer i to Long object and so that the method returns a long number for better precision on displaying the number % */ private Double calcOK(int cntAll, int cntFailed) { Double value = ((Double.valueOf(cntAll) - Double.valueOf(cntFailed)) / Double.valueOf(cntAll)) * 100; return Math.round(value * 100.0) / 100.0; } } | http://quabr.com/46685551/what-is-the-best-authoritative-dns | CC-MAIN-2017-47 | refinedweb | 1,212 | 56.35 |
Decision Incubator Tools/ODP Tour
ODP Background
What are Ontology Design Patterns (ODPs)?
There are many different types of ODPs (see for a graphical illustration ). The main idea is that ODPs are encodings of some kind of best practices or solutions to common problems, that can be reused, either intellectually or concretely as a reusable component. All ODPs are concerned with ontology engineering in some sense, but they have different focuses, e.g., there are reasoning patterns that describe common reasoning services that you may want to perform on some ontology to reach some goal, alignment patterns that describe typical correspondences between elements of two or more ontologies etc. Hence, not all ODPs are directly targeted at the construction/design of an ontology. The types that will be most interesting for us when creating vocabularies for decision making are probably the logical and content ODPs, possibly also re-engineering ODPs and naming ODPs.
Re-engineering ODPs
Re-engineering ODPs describe patterns of transformations that can be used to transform non-ontological resources, e.g., thesauri, database schemas etc., into ontologies. See for a list of suggested patterns.
Naming ODPS
In ontologies naming is much more important than for instance in software engineering (see also discussion in OWL tutorial). We can express some of the semantics of the domain through an ontology, but there will always be terms that indicate how to interpret classes and properties, i.e., the "base classes" by which others are defined, that are still implicitly defined through their naming and intensional descriptions. Additionally, there are good practices for forming URIs.
Logical ODPs
Logical ODPs describe solutions to problems of expressivity, i.e. "how do I express x in language y?". Examples are how to express n-ary relations, how to work around the issue that you cannot use classes as property values in OWL 1.0 etc. Examples from W3C can be found here (see working groups notes): There is also a catalogue from the University of Manchester: and there is a few logical patterns (mostly anti-patterns) in the ODP portal: Basically, if you want to model something and there is not a direct solution provided by the language, a Logical ODP can tell you how to do it. But a Logical ODP only considers logical constructs, i.e., they are abstract "ways to model".
Content ODPs
Content ODPs are from a theoretical perspective instances (of combinations) of logical ODPs. This means that Content ODPs treat similar issues as logical ODPs but from a more concrete perspective. Where logical ODPs only present how abstract logical structures can be applied to solve abstract problems of expressivity, Content ODPs present actual domain-dependent solutions to such problems. Domain-dependent here does not mean "valid in only one industry domain", it is not mainly about industry domains, but it means that these patterns contain actual concrete classes, properties, axioms etc. Hence, the domain can be very general, e.g., modelling time or events, but since the ODPs do contain actual classes they belong to some domain.
You can view Content ODPs as abstract solutions, and they are described through a template with a set of headings, see catalogue at: but they can also be seen as small concrete modelling component, i.e., highly reusable, well-specified, small ontologies. While a Logical ODP can be reused by intellectually understanding the idea of the solution and then start modelling from scratch, the idea of Content ODPs is to import, specialize, compose and extend the small modules/small vocabularies provided through the OWL building blocks of the Content ODPs.
So how do I use Content ODPs for ontology design?
There is a method proposed specifically for reusing Content ODPs, called eXtreme Design (XD). There is a paper about it if you want a more detailed look (1). In summary, the idea is to use an agile and iterative approach for developing ontologies. XD is heavily based on reusing ODPs and thereby a divide-and-conquer paradigm is inherent, which also results in highly modular ontologies. To take a small example: a common way to start modelling an ontology is to start listing all the relevant terms, create classes for those, start thinking about specializations and generalizations of those classes, then considering relations between classes, finally restrictions and so on. This is a kind of "waterfall"-like approach to ontology design. XD takes a quite different approach: first divide your problem into pieces based on small stories that describe particular modelling issues, develop modules solving these small partial problems and carefully test them, then integrate the new module into the overall solution ans test the overall before proceeding to the next part of the overall problem.
The current version of the method guidelines contain the following steps:
- 1. Familiarize with the domain and task. - You need to know what the domain is about, and what the customer really wants to do, set the scope etc. Also agree on things like naming conventions, conventions for URIs etc.
- 2. Collect requirements stories. - The customer writes small examples stories exemplifying the type of information to be represented and what they want to do with it. The stories need to be prioritized.
- 3. Select a story. - This is where the iteration starts. Developers usually work in pairs, so the team is divided into such development pairs, and each pair selects one small story to start with.
- 4. Transform the story into CQs. - Competency Questions is a common way to represent ontology requirements, but in principle this step just means extract the actual requirements from the story. If you have a story like: "During 2009 10 people were employed at the computer science department, half of them worked on project x during the first quarter." you could derive CQs like: "Who worked on what project during what time?", "Who was employed at what department at what time?". However, these should of course express the real tasks that the customer intend the ontology to support, so if these are not things that the system should be able to provide to the user, then these are not good requirements although they can be derived from the story. In addition to CQs you may want to represent additional constraints, e.g. in our example things like "a project always has at least one person working on it".
- 5. Select one or more CQs - This is the start of the second, "inner", iteration, where the development pair selects among their own CQs, and chooses a coherent set to address in one iteration, i.e., the solution will end up in one module.
- 6. Match CQs to GUCs of Content ODPs - The General Use Case (GUC) is the requirements that are covered by the pattern, so a set of very general requirements (usually expressed as CQs). The idea of this step is to try to find useful ODPs that cover some part of or problem. There is a search functionality in XD Tools, the XD Selector, and there is the possibility to view the detailed annotations of the ODPs, but from an "ease of use" perspective you may feel that it is easier to understand ODPs by accessing their page in the ODP portal.
- 7. Select the Content ODPs to reuse - From the task before you get a set of possible ODPs that cover parts of your CQs. Usually you don't have a one-to-one mapping between problem and Content ODP, there may be overlapping ODPs, ODPs on different levels of abstraction that all fit the task etc. So now you have to select as subset that fits your needs. A good rule of thumb is to prefer a more specific ODP over a general/abstract one, but also consider not to select a complex ODP for a very simple requirement, then it may even be better to model from scratch.
- 8. Reuse and integrate selected Content ODPs. - This is the step of the actual modelling. Here you can use the XD Tools specialization wizard to help you in importing and specializing the ODPs, but don't forget that you usually also need to extend the solution in some way and connect ODPs together (if you are reusing several for your module). Below is a brief description of operations/task that can be useful.
- Import - An operation "native" to OWL, adding owl:import statements to your ontology. Importing means that ALL the statements of the imported ontology will be present in the ontology you import it into. You cannot change any imported statements, but you can add statements that refer to the imported elements. A common way to reuse a Content ODP is to import it into your ontology (module) and then proceed to specialize it.
- Specialize - An operation that can be performed on classes or properties in OWL by adding subClassOf or subPropertyOf statements, i.e. creating more specific classes and properties. When we say that we "specialize" a Content ODP it means to specialize one or more of its elements, add more specific restrictions etc.
- Extend - Usually there are some CQs, or parts of CQs, in your requirements list that are not covered by any Content ODP, or that are so simple that no ODP is needed (e.g. the CQ "What is the birth date of a certain person?" is a perfect candidate for modelling using a simple datatype property, rather than trying to ruse some ODP). So after specializing some ODPs, you may need to add some extra properties/classes/restrictions in order to cover the CQs completely.
- Integrate/compose - A special case of extending your model, but that is often forgotten by inexperienced developers: if you reuse several ODPs most likely you need to add something to connect them, in order to support your CQ, e.g. a property or a restriction perhaps.
- 9. Test and fix. - This is a very important step. As soon as you have finished the small module representing the (one or a couple) CQs you selected, you need to test the model against the CQs. This means that you should transform the CQs into queries and use test instances to check if the queries give correct results. In most cases it is not actually running the queries that will point you at the mistakes, but rather trying to write them (then you discover if you've missed something or if there is some other issue). For an OWL model we can use the query language SPARQL to write these queries, usually these type of queries are called "unit tests". Test instances can be added based on the user story you had at the beginning, or invented. Additional tests that can be good to try, apart from the unit tests, is to run the reasoner. First of all you can make sure you have a consistent model, but if you also add some instances you can then see if you agree with all the new classifications etc. that the reasoner gives you. If you don't agree, e.g. your person "Mike" is classified to be of type dog, then you can start debugging from there, trying to analyze how this was inferred. For any error you find, of course you don't proceed until you have removed it and all tests run without problems.
- 10. Release module. - Make sure your module is properly documented before you "release" it, i.e. that all elements have a easy-to-understand human readable label, and that you add comments to all elements that are not completely self explaining. Also annotate the module as a whole, for example using the annotation properties in the CPAnnotationSchema, where you have properties that for instance can store your requirements related to that module (i.e. you store your CQs as a string value with your ontology). This point is also the end of the iteration for the design pair. Now the pair goes back to see if they have any CQs left from the current story, if so they proceed from step 5. If not, but there are still stories left to be treated, they go back to step 3.
- 11. Integrate, test and fix. - Once at least two modules have been released they need to be integrated into an overall solution, i.e. ontology. Depending on what overall architecture you want of the ontology you can do it in different ways, but one common way is to create a new ontology file for the "overall solution" and when new modules become available you import them there and integrate them with the rest. Of course there can occur any kinds of problems here. Sometimes it may be enough to just define some alignments, if here are for example overlaps, while in other cases you may want/need to do some refactoring of the model, e.g. to remove overlaps or solve inconsistencies. When you are done you should be able to run all tests from step 9 again (ok, you have to maybe change the names in teh SPARQL queries if you changed something) and all results should still be correct. Here you should also add any "global" constraints that may exist, e.g. restrictions from the customer that was not related to just one user story.
- 12. Release new version of the ontology. - Finally, you release a new version of the ontology, properly annotated with comments etc.
Note: XD is task-focused! This means that you should model what is in the current CQs, not less but not more either. It is important not to let things get out of hand by starting to model "the whole world", just because maybe it can be useful...
Now, just remember that this is not a prescriptive method, in the sense that you can skip steps or run them in parallel if you want, but this is a guideline that describes how we have worked with Content ODPs and reached good results.
Content ODP Tutorial
So, let's run a little exercise to try out the Content ODPs and the XD methodology!
Below is the current context that you can imagine, and then a set of requirements to model (so let's assume that you have already selected this story, although the story is actually too long to be a really good one, and that you have agreed on the CQs with the customer).
Problem
Develop an OWL ontology starting from the below story and CQs. Note that the text is only there to help you understand the domain and the context of the ontology, but the actual modelling requirements are the competency questions and the contextual statement (the restriction). You can find the Content ODPs at this page or you can access them through the XD Tools plugin.
Important: We are assuming that you will use OWL 1.0, some of the patterns are not intended for OWL2, and your model should be within OWL-DL. Treat the CQs and the contextual statement as the requirements of your model. The result of your modelling should represent these, but also conform to modelling "best practices", e.g. appropriate naming of concepts.
1. When did a certain theatre festival take place? 2. Where did a certain festival take place? 3. What plays could be seen during a certain theatre festival? 4. In what city is a certain theatre located? 5. In what country is a certain city located? 6. What play is the basis of a certain production? 7. Who are the members of a certain ensemble during a certain time? 8. What plays did a certain author write? 9. During what time period was a certain play written? 10. How many acts does a particular play contain? 11. When was the premier of a certain production? 12. What is the “star rating” given by a certain newspaper for a certain production? 13. At what time did a certain actor start working for a specific theatre? 14. What roles does a certain person have within a certain production during a certain time?
Contextual statement: 1. A production has exactly one premier.
Exercise
Above are the requirements and the scenario to address. So, how to start? In terms of the XD methodology, we are now at step 5; about to select one or more CQs to start solving. If you start reading the requirements, you start to realize that some "naturally" goes together and some are more independent, i.e., 1-3 all talk about theater festivals and what they are about, 4-5 talks about locations, while 6 may be treated independently or together with 8-10 that are also about plays etc. The idea is to decide on one, or such a set of CQs (but it should be a SMALL set, i.e. no more than 3-4 at a time is advisable), to start working with. Let's start with the CQs 1-3.
Step 6 then tells us to go look for Content ODPs. If we are using NTK (or TopBraid Composer) with the XD Tools this means we switch to the XD perspective and start browsing the available repositories, or search for patterns using the ODP selector view. When we mark an ODP in the list, either of the repository browser or the search results, we can see its annotations in a view to the right. If we are instead using the ODP portal to browse Content ODPs, we see the list of all proposed Content ODPs (note that they are all "proposals", i.e. suggestions by the community, but not always discussed and agreed so evaluate for yourself if it seems reasonable - the certification process of the portal has not been started yet), and we can click on the name of a pattern to get to see all the information about it (including a graphical illustration, which is not available through the XD Tools currently). Whatever method you use, you will probably be most interested in the information under the headings "domain", "intent" and "competency questions" (covered requirements) to start with.
Now, it is important to focus on the "modelling issue" rather than the individual pieces of the problem. So what are we going to model? A festival. What is a festival? Some kind of event. Basically a festival is something that connects some set of plays to some time and some location, according to our requirements (then in reality a festival may be more things, i.e. have a name, but we care only about our requirements now). Let's look at some patterns and see if something fits. I go to (you can also use XD Tools) and look at the list of patterns. First I make a rough selection based on intent and domain that is presented in the list; I find the co-participation that has something to do with events (domain is "general"), as well as n-ary participation, and time-indexed participation. I also find the time-indexed situation, and the situation pattern itself (a festival could possibly be seen as a situation). So then I proceed to investigate each of them. Co-participation: it has the event and things participating in the event, but these are objects participating, are plays really objects? No probably not. N-ary participation has the event and models the participation as a separate class in order to represent it as an n-ary relation, in order to express that something can participate in an event only during some particular time period, but in our case it is not actually the participation that has a time it is the event itself. Time-indexed participation is very similar, also setting a time for the actual participation. No, neither of those fit. Time-indexed situation seems more reasonable, here it is the actual situation that has a time, but that time is an interval. The situation pattern is just a projection of the n-ary relation logical pattern on the domain of general situations, so this would work, but there we don't have the time in the pattern we would have to add it.
For choosing between situation and time-indexed situation we need to figure out if the time here is a time interval or not. The time-indexed situation is actually just a composition of the situation and time interval patterns, so situation is a more general pattern than the composition. The requirements don't tell us whether we have an interval so in principle we have to ask the customer, but since this is an example we just assume the most reasonable thing. A theater festival would in my opinion possibly span several days, or at least some time interval during one day, so a time interval seems reasonable. Hence, I choose the time-indexed situation pattern. I now download the OWL building block and import it in an empty ontology, or use the XD Tools specialization wizard to create a new module where to import my result and then go through the specialization steps. Let's assume we specialize it without the wizard, so you get the idea of what to do.
First I create a new ontology module, i.e. a new ontology with its own URI. Remember that URIs should be resolvable, so we should use a URI that really exists, and then give the ontology module a good and descriptive name as well. I choose the URI: because I will put the module in the folder "examples" on the ontology.se domain when I'm done. This URI now becomes the XML namespace of this ontology. When I have the empty ontology, I proceed to import the OWL building block of the pattern, i.e. timeindexedsituation.owl. The pattern locally defines a type of situation, and a couple of properties, but it also in turn imports the situation and time interval patterns, as well as the cpannotationschema, which defines a set of annotation properties for documenting patterns (and ontologies in general).
The next step is to start the specialization. The rule of thumb is to specialize all the most specific classes and properties of the pattern, as far as we need them. Already when we analyzed the pattern before selecting it we thought of the festival as a kind of situation, so this should most likely be a specialization of the class "TimeIndexedSituation", let's add it as a subclass. Now we have the three things connected to the festival; the place, the time interval, and the plays that are shown. Time interval is already there as a class. Should we specialize it or not? Well, it can depend a bit on if we intend to keep the imported pattern or if we intend to remove it later, if we intend to remove it later we should make a subclass so that the module is more self-contained, but otherwise it does not make much sense to have a particular type of intervals just for festivals. I don't make a subclass, however I add some restrictions on the TheaterFestival class that I created to say that it always has some time interval associated. We can see that it is the "atTime" property that connects a time indexed situation to a time interval so I use this and state that a TheaterFestival is a subclass of all things that have some (this is the owl:someValuesFrom) time interval. Why not equivalent? Because there are other things that have time intervals that are not theater festivals (necessary but not sufficient condition)! Another possible condition would be that a theater festival has exactly one time interval.
Now, let's deal with the location. I want to say that the TheaterFestival is held in a place. I create the class "Place" and then create a sub-property of the "forEntity" property, which intends to relate the involved entities to the time-indexed situation (in our case one such entity is the place). I name it "hasLocation". The forEntity property has an inverse, called "hasTimeIndexedSetting", so I make sure I create an inverse of hasLocation as a subproperty of this, e.g. "isLocationOf", and explicitly state that they are inverses of each other. Then I again add a restriction on the TheaterFestival class, to say that all festivals are located somewhere.
Finally, we have the plays. I add a class "Play" and a property that is again a sub-property of the forEntity property. I create its inverse, and add a restriction on the TheaterFestival class.
Before to leave this problem and go to the next I should test my module, and see that I can create queries to retrieve the information corresponding to the CQs. First, I add some example instances (e.g. from the story) and then I write the following SPARQL query:
SELECT ?festival ?start ?end ?place ?play WHERE { ?festival :hasPlay ?play . ?festival :hasLocation ?place . ?festival timeindexedsituation:atTime ?time . ?time timeinterval:hasIntervalEndDate ?end . ?time timeinterval:hasIntervalStartDate ?start . }
With this small model I can see already when writing the query that it is going to give me the right results, but it is an important check. I also run the reasoner and check all the inferences I get, so that there is nothing strange there. Finally, when everything is ready I also check that I have annotated my module properly. All classes and properties should have labels, and to be safe also comments. Then the ontology could be commented as well, for instance using the cpannotationschema, to for example store the CQs corresponding to the module as the "covered requirements". My finished module can be found here:
Time to select a new set of CQs. Let's take the following 2 (4-5) about locations. I create a new ontology module, i.e. a new ontology with its own URI, again. Then start to look for patterns... and so on.
Time for you to do some modelling on your own! Proceed to follow the XD iterations and after each iteration also try to integrate your modules, i.e. when you finish the locations-module, create a new empty ontology, import both modules so far, and connect them. Either you are satisfied with just defining an alignment (e.g. stating that some classes and/or properties are equivalent or sub/super classes/properties) or you decide to do some refactoring, i.e. to go back into one module or the other and make some changes, e.g. so that both modules don't define the same concept, but maybe one module instead refers to (or even imports) the other one. If you make changes, then make sure that all your SPARQL queries still run (i.e. you have to rewrite them as well to be able to test). In this way you build your ontology incrementally, with the focus on one problem at a time.
A suggestion for complete solution can be found here: This is not the only correct solution, merely one possibility!
References
(1) Valentina Presutti, Enrico Daga, Aldo Gangemi, and Eva Blomqvist., 2009. Available at: | http://www.w3.org/2005/Incubator/decision/wiki/Decision_Incubator_Tools/ODP_Tour | CC-MAIN-2015-18 | refinedweb | 4,508 | 61.16 |
It was almost three weeks ago when I published my latest article in the LearnVSXNow series. I spent my time examining an important area of VSX; I dealt with the Visual Studio project system and hierarchies.
There are a large number of tasks in Visual Studio Extensibility that cannot be done without knowing the how to handle the project hierarchies. Working with custom editors, creating utilities generating source files and code, getting information about the structure of the currently loaded solution are all examples where the knowledge about Visual Studio hierarchies are indispensable.
Generally developers creating this kind of utilities are talking about Visual Studio Project System. However, handling hierarchies is a more generic part of the VS Shell functionality; it is not constrained only to the project system.
The documentation available in this topic is not an easy stuff. I wanted to get something to start with, but did not find a single document explaining the essence. I spend a few days to look after the missing information, examining source code and building up small utilities to understand what is behind the scenes.
In this post and a few future posts are introduce you the most important things I have learnt about hierarchies. This post is a short overview about the basics just to get into the picture.
In general we can say that Visual Studio uses hierarchies to handle and represent tree-like hierarchical information. The Solution Explorer, Class View and Server Explorer tool windows all work on hierarchies, but Team Explorer and Object Explorer are also good examples of living with hierarchical information.
All of these hierarchies are represented by tree view controls in the UI so you might think that Visual Studio hierarchies have similar structures to trees known from the tree view control. Unfortunately, this assumption is not true.
The key type to understand Visual Studio hierarchies is the IVsHierarchy interface. IVsHierarchy is a generic interface to a collection of nodes forming a hierarchy. There is a distinguished node in this collection, called the root node. Nodes in the collection including the root can have arbitrary properties associated with them. Nodes can be one of the following three types:
Leaf node: it has no children (no child node refers to it as its parent).
Container node: it has at least one child node.
Nested hierarchy: the node has a shortcut to a root node of another hierarchy.
Each node within a hierarchy are identified by a 32-bit integer (generally used as unsigned but sometimes used as signed integer) called VSITEMID. This is actually a cookie that may change as we move the node within the hierarchy. There are two special VSITEMID values (they are accessible through the VSConstants type of the Microsoft.VisualStudio.Shell namespace):
VSITEMID_NIL: represents the “null” VSITEMID reference. For example, when a node does not have a child node, its property called FirstChild has this value.
VSITEMID_ROOT: the ID of the root node. In a hierarchy one and only one node can have this ID.
So, an IVsHierarchy instance represents a collection of nodes forming the hierarchy. Nodes (often called “hierarchy items”) within this container can be addressed by their VSITEMID. If we want to refer to the root node, we use the VSITEMID_ROOT ID within the collection. If we want to access node with ID 1234, we must use 1234 as the VSITEMID of to address the node.
To understand how the structure of nodes is represented within the hierarchy, we must have an overview about the IVsHierarchy interface.
This interface has about a dozen of methods defining the behavior of hierarchies. Instead of going through the list of them, I try to explain the role of interface methods.
As you know, packages are sited in the Visual Studio IDE in order to access services provided by the shell. Similarly, hierarchy items are also sited to access the services. The SetSite method of the interface is called by the environment passing an instance of the Microsoft.VisualStudio.OLE.Interop.IServiceProvider type that can be used for accessing services. If you would like to know which IServiceProvider instance is used to obtain service objects for a specific hierarchy item, the GetSite method can be called to query this information.
Please notice that this IServiceProvider type is not the same than the System.IServiceProvider used when siting packages. The aim of both type is the same, however, their approach is slightly different.
The hierarchy system enables assigning arbitrary properties to any nodes. In order the hierarchy can be represented each node must support a set of properties. The most frequently used method is the GetProperty method of the IVsHierarchy interface, the shell calls it to obtain information about items when working with the item. GetProperty has the following signature:
int GetProperty(uint itemid, int propid, out object pvar);
The itemid parameter represents the VSITEMID of the node queried. The propid parameter tells the identifier of the property we want to query. If the specified property is supported (the node knows what we are talking about) its value is retrieved in pvar and the method return S_OK status. The reference documentation does not tell how this method should behave if the property is not supported. As I examined code samples, I identified two frequently used patterns:
The method returns DISP_E_MEMBERNOTFOUND status value.
A null value is passed back in pvar.
It is also not treated in the reference documents how the method should behave when an unknown itemid is passed (the specified node does not exist in the hierarchy). Most of the code samples I examined returned the DISP_E_MEMBERNOTFOUND status value.
The GetGuidProperty method has similar role as GetProperty:
int GetGuidProperty(uint itemid, int propid, out Guid pguid);
It provides access to properties having GUID values and uses the parameters on the same way; the property value is retrieved in pguid.
Of course, properties also can be set by using the SetProperty and SetGuidProperty methods:
int SetProperty(uint itemid, int propid, object pvar);
int SetGuidProperty(uint itemid, int propid, ref Guid rguid);
Just as in case of property getter methods, itemid is the VSITEMID of the node, propid identifies the property to set. The proposed value is passed to the methods by the pvar or rguid parameters. The reference documentation does not mention what to do with unsupported properties. Generally, the property is simply not set, but methods return without any error code.
Each method uses the propid value that is said to be the identifier of the property to get or to set. There are many property identifiers used by the shell. To avoid using 32-bit literal values, the shell defines enumerations for the property values. Right now there are three enumeration types named __VSHPROPID, __VSHPROPID2 and __VSHPROPID3 all together containing about a hundred identifiers. For example, the __VSHPROPID enumeration contains the __VSHPROPID.VSHPROPID_Parent value that tells the VSITEMID of the specified node’s parent.
The most complex thing in understanding how hierarchies work and what can be done with the project system is about knowing the function and semantics of the node properties. In a later post we are going to examine the properties defining the relation between nodes building up the hierarchy.
The hierarchy system allows logical nesting of one hierarchy into another one. This type of nesting is rather creating a shortcut from a hierarchy node to a node of another hierarchy. It actually means that we do not nest a hierarchy into another: a hierarchy node can point to another node. The IVsHierarchy interface theoretically allows to point from a hierarchy node to an internal node of another hierarchy, but the current implementation allows only shortcuts to the root nodes. The interface provides the GetNestedHierarchy method to query for this shortcut. The method has the following signature:
int GetNestedHierarchy(
uint itemid,
ref Guid iidHierarchyNested,
out IntPtr ppHierarchyNested,
out uint pitemidNested
)
The itemid parameter “names” the node we ask the nested hierarchy information for. The iidHierarchyNested GUID is the type identifier of an interface we expect the requested hierarchy to support. As the common root, we can use the GUID of the IVsHierarchy interface (pass the typeof(IVsHierarchy).GUID value). If we know the nested hierarchy node supports other more specific interfaces, we can use the corresponding GUID.
The two output parameters return the information required to access the nested hierarchy node. The ppHierarchyNested is a pointer to the hierarchy. The IntPtr.Zero value means the node specified by itemid does not have a shortcut to another hierarchy. The pitemidNested by pitemidNested and we should provide this value if we are implementing this method for our own custom hierarchy.
Even if we have VSITEMID values for nodes, those do not uniquely identify hierarchy items over time. The VSITEMID values are dynamically assigned to the nodes as we build up the hierarchy. If we close a (solution) hierarchy in Visual Studio, the next time we open it again, the structure of the hierarchy remains the same, but there is a high probability that VSITEMID values are altered. If we want to persist some information related to hierarchy nodes we need some identification mechanism that copes with time (remains the same between VS sessions). Because VSITEMIDs cannot play this role we need something else.
This is where canonical names come into the picture. A canonical name is a unique string naming the hierarchy item. IVsHierarchy provides the following methods to work with this name:
int GetCanonicalName(uint itemid, out string pbstrName);
int ParseCanonicalName(string pszName, out uint pitemid);
GetCanonicalName obtains the name for the item specified by itemid (retrieves in pbstrName). The ParseCanonicalName retrieves the current VSITEMID information in pitemid for the node having the name passed in pszName. Unfortunately the documentation does not tell what should be returned for a canonical name that cannot be parsed. I have seen examples passing back VSITEMID_NIL in pitemid as well as passing back literal 0 (which is different from VSITEMID_NIL). You should have your own strategy for handling unexpected canonical names.
I am sure you can imagine how important role is played by the events when managing hierarchies. As we click on an item, move it, open or close it, change its properties, we generally have a lot of things to do. Just think about what kind of complex tasks should be behind the Solution Explorer hierarchy handling our user interactions.
We can subscribe to (and of course unsubscribe from) hierarchy events using the widely-used pattern that is described by the AdviseHierarchyEvents and UnadviseHierarchyEvents methods of the IVsHierarchy interface:
int AdviseHierarchyEvents(IVsHierarchyEvents pEventSink, out uint pdwCookie);
int UnadviseHierarchyEvents(uint dwCookie);
When subscribing to the events (with AdviseHierarchyEvents) we pass an IVsHierarchyEvents-aware object instance in pEventSink and get back a cookie in pdwCookie. This cookie can be used in UnadviseHierarchyEvents when we unsubscribe from event notifications. By using the IVsHierarchyEvents interface we can detect (and respond to) the following events:
Event
Description
OnItemAdded
An item is added to the hierarchy.
OnItemAppended
An item is appended to the end of the hierarchy.
OnItemDeleted
An item is deleted from the hierarchy.
OnPropertyChanged
One or more properties of an item have changed.
OnInvalidateIcon
Icon belonging to a hierarchy item is changed.
OnInvalidateItems
Changes are made to the child item inventory of a hierarchy.
I suppose it is a bit confusing why these events are supported by the event model and not some others. In a future post I will tell you the details to make the picture clear.
When the environment does not need a hierarchy any more, it closes them. Even if we want to keep a hierarchy live, it may get closed when we exit Visual Studio. The IVsHierarchy interface provides the following methods to handle the persistence and cleanup tasks:
int Close();
int QueryClose(out int pfCanClose);
Visual Studio automatically calls the Close method on the hierarchies that are the part of a solution (all projects in the solution are hierarchies). If you have packages that define hierarchies outside of the solution, it is the package’s responsibility to call the Close method on those hierarchies. Close must undertake all cleanup and persistence task.
The QueryClose method is called before Visual Studio closes the hierarchy. Zero pfCanClose value prevents closing the hierarchy; any other values enable the close operation. If you have your own hierarchies, you’re responsibility is to call the QueryClose method.
The IVsHierarchy interface defines five methods from Unused0 to Unused4. Let’s say they are there by “historical reasons”. Should you implement IVsHierarchy, please take care these methods simply return the E_NOTIMPL status code.
In this post we had an overview of the IVsHierarchy interface that represents a collection of nodes (hierarchy items). The hierarchy abstraction provided by IVsHierarchy is very different from the one we get used to in connection with tree views. The hierarchy has a distinguished node called root node and each node can have a shortcut to other hierarchy. Each node has a collection of properties, a few defining the internal structure of the hierarchy and potentially unlimited number of arbitrary properties that can be accessed and interpreted in the context where the hierarchy is used.
In the next post we look into the properties determining the structure of the hierarchies.
Thanks for this.
In the previous part of this mini-series I gave an overview of the IVsHierarchy interface. My statement
My latest in a series of the weekly, or more often, summary of interesting links I come across related to Visual Studio. Miguel de Icaza announced that Microsoft has changed the Managed Extensibility Framework License . (Now MS-PL) New on Visual Studio
In the first two parts of this mini-series ( Part 1: Hierarchy Basics , Part 2: Structure of Hierarchies
It’s been a long time since I published the latest article in this mini-series. In the first part | http://dotneteers.net/blogs/divedeeper/archive/2008/10/07/LearnVSXNowPart34.aspx | crawl-002 | refinedweb | 2,309 | 53.41 |
Creating a App using JScript .NET and Windows Forms , Page 4
Working with Menus
Most modern applications implement a system of menus and shortcut keys that make it easier for novice and advanced users to take advantage of the application's functionality. Menus make an application's functionality apparent to novice users, while shortcut keys appeal to more advanced users that prefer not to use a mouse for common tasks or frequently used application functionality.
The sample application features two types of menus: a main menu (a 'traditional' menu that runs across, just under the application's title bar) and a context menu (a menu that pops up when a user right-clicks on the form), as shown in figures 5 and 6.
Figure 5 - Main Menu
Figure 6 - Context Menu
Whether you're working on creating a context menu or a main menu, the tasks you perform are the same - the only thing that changes are the names of the objects. The following listing shows how code the application's main menu (under the application's title bar):
private var mnuMain : System.Windows.Forms.MainMenu; private var mnuHelp : System.Windows.Forms.MenuItem; private var mnuHelpAbout : System.Windows.Forms.MenuItem; // mnuHelpAbout mnuHelpAbout = new System.Windows.Forms.MenuItem mnuHelpAbout.add_Click(mnuHelpAbout_Click) mnuHelpAbout.Text = "&About" mnuHelpAbout.Shortcut = Shortcut.CtrlA; mnuHelpAbout.ShowShortcut = true; // mnuHelp mnuHelp = new System.Windows.Forms.MenuItem mnuHelp.MenuItems.Add(mnuHelpAbout) mnuHelp.Text = "&Help" mnuHelp.ShowShortcut = false; // mnuMainMenu mnuMain = new System.Windows.Forms.MainMenu mnuMain.MenuItems.Add(mnuHelp) // *** Assign the main menu to the form... this.Menu = mnuMain;
The listing creates three objects: a MainMenu, and two MenuItem objects - configure the MenuItem objects before you add them to the MainMenu object, as shown in the listing.
MenuItem objects have a number of properties that make it easy to configure application-wide shortcut keys for an option, in addition to making keyboard based navigation possible. For example, you can access the Help menu by pressing Alt+H, and then A; alternately, you can also directly invoke the About menu by pressing Ctrl-A. See the listing for details on how to configure the menu and the shortcut keys.
Resizing Controls when the Form's Size Changes
A trait that most advanced graphical applications have a professional finish that comes from a very basic feature of Windows applications - the ability to resize a Window. When you resize a Window, like Internet Explorer's window, there are some controls that resize to match the proportions of the new window (instead of having a fixed size or staying in place as you resize the window).
Resizing controls based on the size of a containing window was a problem in the past, which often required a lot of extra code. The problem is so pervasive the Windows Forms includes automatic support for resizing controls through control anchors. For example, if you start the sample application and drag it's bottom right corner out and down, you'll see the text box, progress bar, and their associated buttons move along with the form's border as you resize it.
You can anchor a control using its Anchor property, which can have any or all values in the AnchorStyles enumeration. For example, the following line anchors the ProgressBar to the bottom, left and right of the form:
progressBar.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left;
When you resize the form, the ProgressBar stays at the bottom of the form, and resizes along with changes in the forms left and right borders. The button beside the ProgressBar does not change size but moves with the form's right side border because it's anchored to the bottom right of the form, as shown:
btnProgressControl.Anchor = AnchorStyles.Bottom | AnchorStyles.Right ;
If you anchor the button to the Left as well, it ends up resizing along with the form, which is an unusual visual behavior for a button control. As a result, the button's anchor has it move only with the bottom and right borders such that it maintains the same relative position as the form resizes.
Working with the sample code
The sample code works with .NET version 1.0 only. Download the ZIP file, extract its contents into a new folder, and build the sample using the build command at a command prompt. You can run the application by typing controls at the command prompt while you're in the same directory that you build the application with.
Summary
The Windows Forms package offers a cohesive programming model that makes it easy to build forms that have rich capabilities and a high degree of interactivity. Most classes you'll require to build Windows Forms applications reside in the System.Windows.Forms and System.Drawing namespaces. Windows Forms controls can be customized by programmatically manipulating their properties and methods. The next article in this series goes through the process of creating a Web Service and consuming it from a Windows Forms application, ASP.NET application, and directly from Internet Explorer.
Essam Ahmed is the author of "< a href="" target="new"
# # #
| http://www.developer.com/net/asp/article.php/10917_979251_4/Creating-a-App-using-JScript-NET-and-Windows-Forms.htm | CC-MAIN-2013-20 | refinedweb | 842 | 51.78 |
> One specific Python/APR divide I'm looking at is the APR "pool"
> mechanism. Passing pools about is very tedious and verbose. I
> understand the logic behind it, though! One possible API simplification
> that might help would be to have all pool parameters passed by keyword
> in Python, and then make a Python function decorator that adds a pool=
> keyword argument to a function, and automatically pulls its value from
> the caller's namespace if it isn't provided explicitly. Then, you could
> have the desired semantics for regular usage "by default", and
> explicitly create and manage loop subpools where necessary. Thoughts?
>
While it's early, and I haven't thought of all possible problems in this
approach (noting at the same time that it is more or less what we do
right now in C explicitly), the main one that pops out to me is the
python version requirement (IE decorators are 2.4+).
I'm sure you can work around this with explicit proxying or something.
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Tue May 2 14:26:37 2006
This is an archived mail posted to the Subversion Dev
mailing list. | http://svn.haxx.se/dev/archive-2006-05/0030.shtml | CC-MAIN-2013-20 | refinedweb | 208 | 52.39 |
DDNet Live: Twitch spectates an online game2016-01-10 · DDNet · Frugality
Last night I had an idea and implemented it, soo let’s see what will happen. But first, the idea:
Have a livestream [1] of DDNet running non-stop [2] that always shows some interesting [3] players on the server.
The resulting livestream is running on Twitch. All the scripts are on Github
1. Livestream
It’s surprisingly simple to livestream from Linux to Twitch. Only FFmpeg is needed:
#!/bin/sh INRES="1280x720" # input resolution FPS="30" # target FPS GOP="60" # i-frame interval, should be double of FPS, GOPMIN="30" # min i-frame interval, should be equal to fps, THREADS="2" CBR="2000k" # constant bitrate (should be between 1000k - 3000k) QUALITY="ultrafast" # one of the many FFMPEG preset AUDIO_SRATE="44100" AUDIO_CHANNELS="2" # 1 for mono output, 2 for stereo AUDIO_ERATE="96k" # audio encoding rate SERVER="live-fra" # for list source ./secret.sh ffmpeg -v 0 -f x11grab -s "$INRES" -r "$FPS" -i :0.0 \ -f alsa -i pulse -f flv -ac $AUDIO_CHANNELS \ -b:a $AUDIO_ERATE -ar $AUDIO_SRATE \ -vcodec libx264 -g $GOP -keyint_min $GOPMIN -b:v $CBR \ -minrate $CBR -maxrate $CBR -vf "format=yuv420p"\ -preset $QUALITY -acodec libmp3lame -threads $THREADS \ -strict normal -bufsize $CBR \ "rtmp://$SERVER.twitch.tv/app/$STREAM_KEY"
This works pretty well, but takes quite a bit of CPU on my old computer. So instead I wanted to run it on my new server with a Haswell-era J1900 CPU.
Possible ways to improve performance:
- Use an OpenGL recorder instead of x11grab
- Get Intel Quick Sync Video working for hardware H264 encoding
2. Running Non-Stop
My server is a small and cheap ASRock Q1900-ITX:
The nice part is that it’s passively cooled and quite power efficient, drawing only 5 Watts in idle. This machine has been running as my home server for quite some time, but barely gets any action. Let’s change that!
The X server starts without problems even without any monitors attached, the only thing that’s left to do is increasing the framebuffer size so that our game can run in it:
$ cat ddnet.sh #!/bin/sh pulseaudio --start xrandr --fb 1280x720 # Adjust framebuffer cp settings_ddnet.cfg ~/.teeworlds/ # Restore backup cd ddnet && ./DDNet $ xinit ddnet.sh
We don’t even need a window manager. After all we just run a single window in exactly the resolution of the framebuffer.
The FFmpeg recording still works in exactly the same way. Unfortunately I couldn’t get H264 hardware encoding to work with the J1900 CPU. Related bug reports make me believe it just doesn’t work on these cheaper Intel CPUs.
3.
Artificial Intelligence Twitch Control
Now that we have the game running and are streaming it to Twitch, we need to control it somehow. My goal was to find an approach that always shows some interesting players in action, so that you could watch the stream all day and enjoy it.
But finding a reasonable way to do this seems too complicated and I didn’t look forward to hacking the DDNet C/C++ source code, so instead I opted to utilize an existing system in DDNet: FIFO command input!
DDNet servers and clients can be remote controlled through a FIFO file. This is very useful to send the same commands to dozens of servers at once. But for the client its use was pretty limited, until now!
Instead of thinking of an algorithm to find interesting players, why not let the Twitch viewers themselves control who they want to watch through the chat?
I did not modify the DDNet source code in any way and instead wrote a small Nim script based on the IRC module to connect to Twitch’s IRC server and forward the commands to the FIFO:
import irc, strutils, secret const forbiddenCommands = @["exec", "quit", "exit", "disconnect"] var client = newIrc("irc.twitch.tv", nick = "ddnetlive", serverPass = serverPass, joinChans = @["#ddnetlive"]) fifo = open("input.fifo", fmWrite) proc handle(nick, cmd: string) = for f in forbiddenCommands: if cmd.contains(f): return echo nick, ": ", cmd stdout.flushFile() fifo.write(cmd) fifo.write("\n") fifo.flushFile() client.connect() var event: TIrcEvent while true: if client.poll(event): case event.typ of EvConnected: discard of EvDisconnected, EvTimeout: client.reconnect() of EvMsg: case event.cmd of MPrivMsg: handle(event.nick, event.params[^1]) else: discard
Right now there is really not much limitation to what you can do. Only a
handful of commands are explicitly blocked, otherwise the client can be
controlled freely and every single chat message is sent to the client. The
client commands and
client settings list the
available commands and settings. Chat
commands can be sent to the
server as well through the
say command. Some examples:
connect ger.ddnet.tw:8303 team -1 # Join spectators spectate_next # Spectate the next player spectate 0 # Spectate player with ID 0 say Hi from twitch.tv/ddnetlive # Write chat messages player_name DDNetLive # Change name
Let’s see how this goes. Luckily the Nim script runs independently from the server, so I will be able to make changes to it on the fly. Just be nice and don’t cause any trouble, thanks.
Feel free to head over to Twitch, watch the action and control the server using the Twitch chat. Twitch has some delay, so it takes a few seconds for you to see your command executed. | http://hookrace.net/blog/ddnet-live/ | CC-MAIN-2021-04 | refinedweb | 894 | 72.16 |
25 January 2011 16:21 [Source: ICIS news]
HOUSTON (ICIS)--High demand and production shortages will likely result in a higher price for ?xml:namespace>
Negotiations for the February Tampa ammonia contract between Yara and its clients Mosaic and CF Industries were ongoing this week, and market watchers suggested the price could settle $35-45/tonne (€26-33/tonne) higher than the $475/tonne CFR (cost and freight) Tampa January contract.
High demand this spring in the
Meanwhile, ammonia supply to the US Gulf has been strained by a nearly month-long outage of a 525,000 tonne/year Yara ammonia plant in
Sources indicated that Yara’s Tringen 1 plant in Point Lisas could be back in production by the end of this week.
Yara would probably like to settle at $525/tonne based on recent sales of ammonia in
But buyers Mosaic and CF were likely pursuing a figure closer to $500/tonne.
A consensus among market watchers was that the February Tampa contract would settle in the range of $510-520/tonne CFR.
A settlement for February was expected to be reached by the end of this week.
($1 = €0.73)
For more on ammonia visit ICIS chemical intelligence | http://www.icis.com/Articles/2011/01/25/9429277/us-february-ammonia-contract-may-rise-35-45tonne.html | CC-MAIN-2014-52 | refinedweb | 202 | 53.14 |
By: John Kaster
Abstract: Its official designation is "Delphi 8 for the Microsoft NET Framework", and Cary Jensen, Ph.D. has the complete scoop
By Cary Jensen, Ph.D.
Okay - it's not really named Delphi.NET; its official designation is
Delphi 8 for the Microsoft NET Framework . It's here nonetheless, and
Cary Jensen, Ph.D. has the complete scoop on the most eagerly
anticipated new version of Delphi in years. Now you can program for
the .NET platform at the speed of Delphi!
There is something poetic about the version number of Borland's first
release of Delphi for the Microsoft .NET Framework, Delphi 8. If you
enjoy coincidences, you'll be interested to know that the original
release of Delphi, Delphi 1, was also an eighth version.
Specifically, it was the eighth version of Borland's Pascal compiler;
Borland Pascal with Objects version 7.0 was the immediate ancestor of
Delphi 1.
I find this coincidence fascinating for another reason; Delphi 1
represented a major advance in Borland's Pascal technology without
making existing Borland Pascal code obsolete. The parallels are
uncanny. Delphi 8 for the Microsoft .NET Framework, which from this
point on I will refer to simply as Delphi 8 for .NET, represents
another major advance in the language we now call Delphi, without
sacrificing your investment in Borland technology.
Consider this. Any current Delphi developer can build applications
for the .NET Framework today using Delphi 8 for .NET, in some cases
merely by opening an existing Delphi application in Delphi 8 for .NET
and pressing [Ctrl][F9] to compile it. Even most of the tools you use
on a daily basis, including the Code editor, object inspector, and
integrated debugger, to name a few, are immediately recognizable, if
not identical, to the Win32 version of Delphi.
But while Delphi 8 for .NET maintains an unprecedented amount of
backward compatibility with Delphi for Win32, it simultaneously
introduces the necessary new features to make it not only a first
class .NET language, but also an exceptional development environment
for defining, designing, building, testing, and maintaining .NET
applications.
This article is designed to give you a broad overview of what you'll
find in Delphi 8 for .NET. Keep in mind, however, that this article
was written based on a pre-release version of the software.
Similarly, the names of the various Delphi 8 for .NET technologies
described in this article are based on early drafts of Borland's
documentation. The corresponding names in the shipping product may
differ.
For a detailed listing of the features of the shipping product, as
well as in which edition (Architect, Enterprise, or Professional)
those features appear, see the feature matrix available at.
The most obvious new feature in Delphi 8 for .NET is its IDE, shown
in Figure 1. This IDE, which made its first appearance in Borland's
C#Builder, appears similar to the IDE of Microsoft's Visual Studio
for .NET. It has a nice, clean layout, and is highly configurable,
giving you a wide range of options with respect to where your various
tools float or are pinned. (Pinning is what many Borland developers
would refer to as docking. In the .NET world docking refers to
alignment.)
A closer inspection, however, reveals its unmistakable Borland
heritage. Anyone familiar with the Delphi 7 IDE will quickly find
themselves at home. The tools, options, and dialog boxes are
generally accessed through the same or similar menu selections. For
example, the Run menu, shown in Figure 2, is almost indistinguishable
from that found in Delphi 7.
The Code editor is another place where you'll find all your favorite
coding support tools. In particular, Code Insight, code templates,
the todo list, and editor key bindings are all available. For
example, Figure 3 shows Code Completion, one of the Code Insight
features, operating within the editor.
On a similar note, the various key combinations and menu items
related to the Code editor are consistent with the previous version
of Delphi. For example, press [F5] to Add Source Breakpoint , [F9] to
Run , [F7] to Trace Into , and even [Ctrl][R] to Record Keystroke
Macro (if you're using the default key mapping).
But there are differences. One of the more notable changes can be
found in the Tool Palette, shown in Figure 4, which replaces the
Component palette in Delphi 7. Objects can be added to your projects
either by dragging and dropping from the Tool Palette, or by entering
the object name in the provided text box. With each letter of an
object's name you enter into this text box, the list of objects that
appears in the Tool Palette shrinks to include only those whose names
match the entered characters.
Objects in the Tool Palette are organized by category, and individual
categories can be collapsed and expanded as needed. In addition, you
can quickly go to a particular category by clicking the Category
button and selecting from the displayed drop-down menu.
The Tool Palette is context sensitive, displaying only those
components that are appropriate for the particular type of object on
which you're working. For example, if you're designing a Windows
Form, the Tool Palette displays those components that you can use to
build GUI Windows applications. By comparison, if you're designing a
Web Form, only Web-related objects appear.
Initially, the Tool Palette contains only a small, but well-chosen,
collection of the objects that can be configured within the IDE. For
example, although the 1.1 version of the NET Framework includes
approximately 4,500 different classes, the Tool Palette initially
contains less than 100 components.
You add or remove components from the Tool Palette by selecting
Components | Installed .NET Components , or by right-clicking in the
Tool Palette and selecting Installed .NET Components . This displays
the Installed .NET Components dialog box, shown in Figure 5. The
corresponding object will appear in the specified category in the
Tool Palette when the check box to the left of a class name is
checked.
As you can see from Figure 5, this is also where you install
unmanaged COM or ActiveX objects that you want to use in your
application, as well as components from the VCL.NET (the visual
component library for .NET; more about this later in this article).
Unmanaged code in DLLs can also be used in Delphi 8 for .NET
applications, but those are accessed using a different technique.
Another aspect of the IDE that looks a little different are the
various options dialog boxes, including the Options dialog box (for
general IDE options) and the Project Options dialog box. In this
case, while the interface is a little different (a tree view on the
left side of this dialog box displays the categories, instead of a
tabbed notebook interface), the various frames within these dialog
boxes are, again, familiar. The Options dialog box is shown in Figure
6.
There are many new features, as well. The Model View, similar to
Delphi 7's Diagram page, provides you with a diagram of the various
objects that you employ in your application. Borland calls this code
visualization. But if you're using the Architect version of Delphi 8
for .NET, the Diagram page becomes a sophisticated, synchronized UML
diagram editor. A sample of code visualization for a medium-sized
project is shown in Figure 7.
Another new tool is the Data Explorer, shown in Figure 8. This dialog
box provides you with a convenient browser for inspecting available
connections using Borland Data Providers, or BDP.NET. (BDP.NET is
described later in this article.) You can even drag tables, views, or
stored procedures from the Data Explorer and drop them on any WinForm
or WebForm application to have Delphi 8 for .NET add and configure
the required BDP.NET classes to your application.
No discussion of the new IDE would be complete without a few words
about the WebForms designer. This designer, which is very similar to
both the WinForms and VCL.NET form designer, permits you to build
your Web page interfaces visually.
As you drop the various WebForm components into the WebForms
designer, Delphi generates the corresponding HTML, inserting it into
the .aspx file associated with that form. Similarly, if the component
is one that has event handlers, such as a Button, Delphi adds the
class reference to the WebForm class in the code-behind file, the
file that contains the Delphi statements that will be executed on the
server. An example of a WebForms in the designer is shown in Figure
9.
Although there are many welcome similarities between the Delphi 7 and
Delphi 8 IDEs, there can be no doubt about Delphi 8's .NET
credentials. Delphi 8 for .NET is a .NET IDE, and the Delphi language
is a full-fledged .NET language.
Unlike Borland's C#Builder, which uses Microsoft's C# compiler under
license, Delphi 8 for .NET employs Borland's new .NET compiler for
the Delphi language. When you compile a Delphi 8 for .NET project,
this new compiler emits Microsoft Intermediate Language (MSIL), the
CPU-independent instructions that are converted to native code,
typically by a just-in-time (JIT) compiler. This MSIL is equivalent
to that generated by any of Microsoft's compilers, including those
for C# and Visual Basic for .NET.
Because Delphi 8 for .NET includes a full-fledged .NET language, it
has access to the entire .NET Framework Class Library (FCL), a
comprehensive library of classes, types, and symbols that constitutes
the .NET equivalent of Delphi's VCL. Classes in the FCL provide
extensive support for data access (ADO.NET), WebForms (ASP.NET and
Web Services), WinForms (Windows GUI development), XML development,
and much more. In short, as a .NET developer using Delphi 8 for .NET,
you're making no sacrifices.
Also as a result of its true .NET nature, Delphi 8 for .NET
developers have transparent access to any public classes declared in
legitimate .NET assemblies. This means that all third-party .NET
components are easily accessible to Delphi 8 for .NET developers,
regardless of the language in which those components were developed.
To accommodate many of the features of .NET, Borland introduced
significant enhancements to the Delphi language. These include the
addition of attributes (descriptive declarations that are used to
identify the characteristics of programmatic elements), unit
namespaces, operator overloading, and new visibility identifiers. For
example, class declarations now support both strict private and
strict protected visibility.
What is particularly exciting about these enhancements to the Delphi
language is that Borland has indicated that these new features will
also be added to future versions of the Delphi Win32 compiler. This
will be done to ensure that your code continues to be compatible with
the various Delphi language compilers.
Although Delphi 8 for .NET provides full support for the FCL, it goes
well beyond, making the Delphi language an especially attractive
solution for .NET development. Specifically, Borland has included in
Delphi 8 for .NET a number of technologies that extend and/or
complement the FCL. Borland refers to these technologies as Borland
Data Providers (BDP.NET), RTL.NET, VCL.NET, dbExpress.NET, IBX.NET,
DataSnap.NET, and BDE.NET.
The first two of these technologies, BDP.NET and RTL.NET, can be used
in standard WinForms, WebForms, and console .NET applications that
employ the FCL. BPD.NET is a collection of concrete classes that
implement the ADO.NET interfaces used for data access. These concrete
classes differ from the corresponding FCL concrete classes in that
they provide an open, portable solution for accessing a variety of
different database servers, including Microsoft SQL Server,
InterBase, Oracle, and DB2. (Note that BDP.NET is available only in
the Architect and Enterprise editions of Delphi 8 for .NET.)
The RTL.NET is a .NET version of Delphi's runtime library, the
collection of pure functions and procedures (and their associated
constants, variables, and types) that you can use from your custom
code. RTL.NET maintains a tight source code compatibility with Win32
versions of Delphi, smoothing the migration path of your existing
Win32 code to .NET, as well as permitting you to write routines that
easily compile under your platform of choice.
In my opinion, the presence of RTL.NET alone provides a compelling
argument to use Delphi as your preferred .NET language. RTL.NET
includes literally hundreds of useful routines, including those in
the Borland.Vcl.SysUtils, Borland.Vcl.StrUtils,
Borland.Vcl.DateUtils, and Borland.Vcl.Math units, to name a few.
Another Borland technology, Db Web Controls for ASP.NET, is available
for use when you're building WebForms. These are visual, data-aware
Web controls that you can use with ADO.NET and BDP.NET classes to
quickly and easily build database Web applications.
The remaining technologies listed earlier in this section are
designed to simplify the process of migrating existing applications
from Win32 to .NET, as well as to permit developers to leverage their
current skill sets when building new .NET applications. These
technologies can be broadly referred to as VCL.NET, with
dbExpress.NET, IBX.NET, DataSnap.NET, and BDE.NET being subsets of
VCL.NET technologies.
VCL.NET is a component framework that provides extensive source code
compatibility between Delphi Win32 and Delphi for .NET. The classes
and types available in VCL.NET represent a rich subset of the Win32
VCL. Furthermore, these classes and types sport interfaces that are
essentially identical to their VCL counterparts, permitting you to
easily create single source projects that can be compiled either to
the .NET platform or Win32, as well as to provide a greatly
simplified migration path to .NET.
At first glance, VCL.NET is truly remarkable. If one of your existing
applications makes use of common Delphi VCL components (Edit, Label,
DBGrid, MainMenu, and the like), you may be able to simply open that
project in Delphi 8 for .NET and compile it to MSIL.
For example, if you've installed both Delphi 8 for .NET and Delphi 7,
use Delphi 8 for .NET to open the ConvertIt project, which by default
is located in the DemosConvertIt folder under the Delphi 7
directory. Press [F9] to compile and run this project as a .NET
assembly without changing a single line of code. Amazing, isn't it?
As for dbExpress.NET (dbExpress for .NET), IBX.NET (InterBase Express
for .NET), DataSnap.NET (for building DataSnap clients under .NET),
and BDE.NET (Borland Database Engine for .NET), these are .NET
implementations of the associated VCL classes for data access. As
with other parts of the VCL.NET, these classes provide a nearly
seamless upgrade path to .NET for most existing database
applications. Here you will find such classes as TSqlDataSet,
TIBConnection, TClientDataSet, TDataSetProvider,
TDCOMConnection, TDataSource, and even TTable .
(Only the Architect and Enterprise editions ship with dbExpress.NET
and DataSnap.NET.)
Take a look at Figure 10. This is the FishFact.drp project, which is
located in the DemosDBFishFact folder located under the Delphi 7
directory. What you see in Figure 10 is a VCL.NET application that
uses BDE.NET to access a Paradox table. Like the ConvertIt project,
all I did was open FishFact.dpr in Delphi 8 for .NET and hit [F9] .
And voil` ! I get a running .NET managed code assembly.
I suspect that VCL.NET will be particularly important to two groups
of Delphi developers: those who need to run existing applications
under .NET with a minimum of changes (or future maintenance), and
those who need to create quick and dirty .NET applications without
having to learn the FCL.
For most other developers, it's probably best to bite the bullet and
learn the FCL. This will take time, but you won't be alone - nearly
every other developer using .NET is going through the same thing.
After all, the FCL is the native class library of .NET. It's a good
one too!
For more than a year now, Borland has been enhancing their
best-of-breed programming environments with a rich collection of
tools that help manage nearly all aspects of the application
lifecycle, from requirements management, to UML modeling tools, to
source code version control, to defect tracking.
Although most of these tools can be purchased separately, the
high-end editions of Delphi 8 for .NET include some or all of these
tools. Delphi 8 for .NET Enterprise includes all the features
available in the Professional edition, as well as CaliberRM and
StarTeam Standard Edition Client and Server (in addition to BDP.NET,
DataSnap.NET, and dbExpress.NET). The Enterprise edition includes all
of the tools that ship with the Enterprise edition plus ECO
(Enterprise Core Objects), a sophisticated two-way tool for building
and maintaining applications using UML class diagrams, as well as
OptimizeIt, Borland's .NET profiler.
Most Delphi developers will find Delphi 8 for .NET very exciting.
First of all, it permits you to build .NET applications today using
the tools you know and the language you love. Let's face it, if you
build applications for Windows, you will eventually need to be
working in .NET. Delphi 8 for .NET makes it easy.
If you're a Delphi developer, but aren't using Delphi 7, you'll be
interested to know that Delphi 8 for .NET includes a copy of Delphi 7
(for Win32). Even if you have only a passing interest in .NET
development at this time, the offer to get Delphi 7 bundled with
Delphi 8 for .NET should provide you with a pretty compelling
argument for upgrading.
For developers who aren't using Delphi at all, I personally think
Delphi 8 for .NET deserves a good look. As I pointed out earlier,
Delphi 8 for .NET includes RTL.NET, quite possibly the richest set of
.NET routines available. That, coupled with one of the easiest to
write and maintain languages available (I'm talking about the Delphi
language), and with Borland's outstanding compiler and support tools,
make Delphi 8 for .NET a very attractive .NET solution. And if you
must build applications for both Win32 and .NET, you'll find no other
language that makes this inter-platform migration as easy.
Cary Jensen, Ph.D. is president of Jensen Data Systems, Inc.,
a training and consulting company that won the 2002 and 2003
Delphi Informant Magazine Readers Choice Awards for Best
Training. Cary is the co-author of 19 books, including Advantage
Database Server: The Official Guide (McGraw-Hill/Osborne, 2003),
Building Kylix Applications (Osborne/McGraw-Hill, 2001),
JBuilder Essentials (Osborne/McGraw-Hill,1997), and Delphi
in Depth (Osborne/McGraw-Hill, 1996). He is the author and
trainer for the Delphi Developer Days tours, a Contributing Editor of
Delphi Informant Magazine , and a featured Web columnist on
the Borland Developer Network. For more information about Cary and
his company's services, including Delphi Developer Days 2004
workshops and seminars, visit.
This article originally appeared in Delphi Informant Magazine,, and appears with permission of Informant Communications Group, Inc
Server Response from: SC1 | http://edn.embarcadero.com/article/31980 | crawl-002 | refinedweb | 3,179 | 58.89 |
Show Table of Contents
Chapter 17.. For system administrators, using the nameserver allows them to change the IP address for a host without ever affecting the name-based queries, or to decide which machines handle these queries.
17.1. Introduction to DNS
DNS is usually implemented using one or more centralized servers that are authoritative for certain domains. When a client host requests information from a nameserver, it usually connects to port 53. The nameserver then attempts to resolve the name requested. If it does not have an authoritative answer, or does not already have the answer cached from an earlier query, it queries other nameservers, called root nameservers, to determine which nameservers are authoritative for the name in question, and then queries them to get the requested name.
17.1.1. Nameserver Zones
In a DNS server such as BIND (Berkeley Internet Name Domain), all information is stored in basic data elements called resource records (RR). The resource record is usually a fully qualified domain name (FQDN) of a host, and is broken down into multiple sections organized into a tree-like hierarchy. This hierarchy consists of a main trunk, primary branches, secondary branches, and so on.
Example 17.1. A simple resource record
bob.sales.example.com
Each level of the hierarchy is divided by a period (that is,
.). In Example 17.1, “A simple resource record”,
comdefines the top-level domain,
exampleits subdomain, and
salesthe subdomain of
example. In this case,
bobidentifies a resource record that is part of the
sales.example.comdomain. With the exception of the part furthest to the left (that is,
bob), each of these sections is called a zone and defines a specific namespace.
Zones are defined on authoritative nameservers through the use of zone files, which contain definitions of the resource records in each zone. Zone files are stored on primary nameservers (also called master nameservers), where changes are made to the files, and secondary nameservers (also called slave nameservers), which receive zone definitions from the primary nameservers. Both primary and secondary nameservers are authoritative for the zone and look the same to clients. Depending on the configuration, any nameserver can also serve as a primary or secondary server for multiple zones at the same time.
17.1.2. Nameserver Types
There.
17.1.3. BIND as a Nameserver. | https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-dns_servers | CC-MAIN-2018-09 | refinedweb | 388 | 53.51 |
Part I. Querying Active Directory and Building an Object Pool
Querying Active Directory can be time consuming and in order to avoid freezing the UI, we will run the AD queries on a worker thread. Below is the code to perform the query finding all the Active Directory groups. The DirectorySearcher and SearchResultCollection are members of the System.DirectoryServices namespace in the System.DirectoryServices dll (which has to be explicitly added to a project).
private static String[] GetAdGroupsFromAD(){ DirectorySearcher srch = new DirectorySearcher();
const string query = "(&(objectCategory=group))";
srch.Filter = query;
SearchResultCollection sResult = srch.FindAll();
List<String> results = new List<string>();
if (null != sResult) for (int i = 0; i < sResult.Count; i++) if (null != sResult[i].Properties["name"] && sResult[i].Properties["name"].Count == 1) results.Add(sResult[i].Properties["name"][0] as String);
return results.ToArray();}
This query can take a long time to execute and we don't expect the results to change very frequently so we can use a caching mechanism to store the results.
Because the object pool (the cache) will eventually be hit by an asynchronous call and may have more than one thread at a time accessing it, we'll have to take extra precautions to make sure the state of the pool is not corrupted. We will protect the pools by creating synchronization objects for the express purpose of locking down the pool by ensuring only one thread at a time is allowed which guarantees the state is not corrupted while reading the data.
private static Object m_groupPoolSync = new Object();
Every time we read or write information to the group pool we will lock on the m_groupPoolSync object. This is preferable to locking the whole class because we have more granular control of the critical section and we only lock what is absolutely necessary for the shortest amount of time. Also, we will have a flag that tells us whether the pool has been initialized so we can skip the AD query if we already have the data we need.
private static String[] GetAdGroups(){
List<String> results = new List<string>();
lock (m_groupPoolSync) { if (!m_groupPoolInitialized) { foreach (String result in GetAdGroupsFromAD()) m_groupPool.Add(result);
m_groupPoolInitialized = true; }
results.AddRange(m_groupPool); }
return results.ToArray();}
It may be necessasry to clear the pool at some point, so we should expose this functionality which is just a matter of setting the flag. This is locked because there may be a thread in the GetAdGroups() method above that is busy querying AD. If we did not lock the code below, the ClearPools() could execute during the AD query and the flag would first be set as m_groupPoolInitialized = false and then when the AD query completed in the above method, the flag would be reset to m_groupPoolInitialized = true which would cause our application to behave in unexpected ways. I could see a valid argument being made for not locking the pool clearing as long as the behavior is obvious to other developers working with the code.
public static void ClearPools(){ lock (m_groupPoolSync) m_groupPoolInitialized = false;}
Part II. Exposing the Long Running Process Asynchronously.
Now we want to provide access to our long running process asynchronously. This will be accomplished through a delegate that will call our GetAdGroups() method.
private delegate String[] GetAdGroupsDelegate();
To make the async call using our delegate we create a new instance of the delegate by assigning it to the method we want to hit. Next we use the BeginInvoke() method from the delegate to do the async call. We'll pass the Delegate to the BeginInvoke() method in order to retrieve the results later:
public static IAsyncResult BeginGetAdGroups(AsyncCallback callback, Object state){ GetAdGroupsDelegate mthd = GetAdGroups; return mthd.BeginInvoke(callback, new Object[] { mthd, state });}
To get the results we'll first need to assert that the async call has completed. Because we'll reuse this quite a bit we can encapsulate the functionality in a single utility method.
private static void AssertCompleted(IAsyncResult result){ if (!result.IsCompleted) throw new InvalidOperationException("result has not completed");}
We'll also have to have a way to retrieve the delegate object that we passed in the BeginInvoke() method. We can use a generic method to do create a second utility method that will be reusable.
private static T GetStateMethodItem<T>(Object value){ Object[] state = value as Object[];
if (null == state) throw new InvalidOperationException("Invalid AsyncState: Expecting Object[]");
if (state.Length < 1) throw new InvalidOperationException("Invalid AsyncState: Object[] has no items");
if (state[0].GetType() != typeof(T)) throw new InvalidOperationException("Invalid AsyncState: Object[] is not of type " + typeof(T).ToString());
return (T)state[0];}
Finally, we'll use our two utility methods to retrieve the results of the async call. Notice we are using the standard method signatures to wrap our original call asynchronously by prefacing the original method name [GetAdGroups()] with "Begin" [BeginGetAdGroups()] and "End" [EndGetAdGroups()].
public static String[] EndGetAdGroups(IAsyncResult result){ AssertCompleted(result); GetAdGroupsDelegate mthd = GetStateMethodItem<GetAdGroupsDelegate>(result.AsyncState); return mthd.EndInvoke(result);}
Part III. Consuming the Async Helper Class with a Win Form
First, we'll need a form to show wile our async process is running. The code for this form is attached to this article.
Next, we'll need to launch our form whenever there is a call to an async process. We will also need to update the main form when the async call is complete. With win forms, only the thread that created the window will be allowed to update it. In order to accomplish this, we can use a delegate for a method to show the results of our async query and call it safely with the following utility method:
private delegate void ShowResults();
private void SafeInvoke(ShowResults rslts) { if (InvokeRequired) Invoke(rslts); else rslts.Invoke(); }
Now to call the method we'll create an instance of the working form and use an anonymous method to handle the async result. If you want more details on async programming you can read my articles on the subject Part I, Part II, Part III , Part IV, Part V, Part VI.
After the async call is launched, we'll show the working form as a dialog. In the async response, we'll pass an anonymous method to the SafeInvoke() method to ensure the main window's thread updates the windows controls and closes the working form.
private void m_btnSearch_Click(object sender, EventArgs e){ WorkingForm frm = new WorkingForm(); String searchString = m_txtSearch.Text;
ActiveDirectory.AdHelper.BeginGetAdGroups(delegate(IAsyncResult result) { SafeInvoke(delegate() { String[] values = Array.FindAll(AdHelper.EndGetAdGroups(result), delegate(String value) { return value.Contains(searchString); });
Array.Sort(values);
m_lstUsers.DataSource = new String[0]; m_lstGroups.DataSource = values; frm.Hide(); }); }, null);
frm.ShowDialog();}
I hope you found this article useful. I'm by no means an expert with active directory and I imagine there are probably much more efficient queries that could be run against AD but the idea I wanted to get across here is the async approach and how to implement it in a windows project. The accompanying code includes finding all the ad users and user and group membership in addition to finding the ad groups.
Until next time,Happy coding
View All | http://www.c-sharpcorner.com/article/C-Sharp-asynchronous-multi-threaded-active-directory-usergroup-b/ | CC-MAIN-2017-22 | refinedweb | 1,181 | 54.73 |
I recently had a problem with jsf+hibernate, with another control from the selectOneXXX family
(see and later)
My problem was that I was comparing "real" objects and "hibernate proxy" objects. The standard
java equals function just fails in this case. I do not see how you fetch your objects, but
this might be the case.
Your problem might also be simplier. I am also a bit surprised that you return a list of SelectItem
as value for your f:selectItems.
Let say that you have a Student type.
You will then have a
List<Student> getStudentList()
method and a custom Converter to propertly manage the String <-> Object mapping.
Your selectedItem property should in this case also be of Student type.
------------------------
Thanks for sharing your thoughts.
I tried the backing bean to use String objects and List<String> for the list box, since
the studentId is a varchar(xx) type in the backend db. The same problem exists, even now.
That is, when only an entry is selected from the list and the <Details> button pressed,
the list empties in the jsf page, the jsf page is refresed, and the "Detail1" function for
the <Detail> button is not being called. This function (Detail1) is called when the
list is empty or when no entry is selected from the list and the when the <Detail> button
is pressed.
Everything works correctly when Jpa is used for data access in the backing bean. Why is there
the problem in the hibernate-jsf interaction?
*********************************************************
// Jsf
<h:outputLabel
<h:inputText
</h:inputText>
<h:selectOneListbox
<f:selectItems
</h:selectOneListbox>
<h:commandButton
<h:commandButton
*********************************************************
// Backing bean
@ManagedBean
@SessionScoped
public class StudBean implements Serializable {
private String teacherName;
private List<String> studentList;
private String selectedItem = null;
private String studentId;
// Getter and setter methods omitted
//
public String studSel() {
studentList = new ArrayList<String>();
List<String> cList = getStudentDetailForTeacher();
if(cList.isEmpty())
return null;
for (int i = 0; i < cList.size(); i++) {
String studentid = cList.get(i);
studentList.add(courseid);
}
return null;
}
public List<String[]> getStudentDetailForTeacher() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
List<String[]> studentlist = null;
String strQuery = "select c.id.studentId "
+ "from TeacherStudent c WHERE c.id.teacherId = :teachid1";
org.hibernate.Transaction tx = session.beginTransaction();
Query cQuery = session.createQuery(strQuery);
// teacherName is in the jsf page tied to this backing bean member variable
cQuery.setParameter("teachid1", teacherName);
studentlist = (List<String[]>) cQuery.list();
return studentlist;
}
public void studentCodeChanged(ValueChangeEvent e){
studentId = e.getNewValue().toString();
System.out.println("studentId = "+studentId);
}
public Boolean Details1() {
System.out.println("studentId id = "+studentId);
return null;
}
} | http://mail-archives.apache.org/mod_mbox/myfaces-users/201301.mbox/%3C1359644739.46118.YahooMailNeo@web192702.mail.sg3.yahoo.com%3E | CC-MAIN-2018-51 | refinedweb | 417 | 50.23 |
This idea came from Ziran Lin's article Pinnable ControlBar and Iuri Apollonio's article An Outlook98 bar-like control. I think that a dockable OutlookBar is very cool, so I wrote this article.
#include "pinoutbar\pinoutbar.h"
PinDockBar
OnCreate
m_MyBar.m_wndOutlookBar.SetOwner(this);
then add the message handler:
afx_msg LRESULT OnOutbarNotify(WPARAM wParam, LPARAM lParam);
ON_MESSAGE(WM_OUTBAR_NOTIFY, OnOutbarNotify)
long CMainFrame::OnOutbarNotify(WPARAM wParam, LPARAM lParam)
{
...
}
OK, your project can receive the messages from OutlookBar now.
I used a free UI library - AppFace to skin this OutlookBar. You may delete appface.dll simply if you do not need it.
Thanks for Ziran Lin and his article Pinnable ControlBar, Iuri Apollonio and his article An Outlook98 bar-like control. Thanks for the help of the AppFace Support. | https://www.codeproject.com/Articles/10556/A-dockable-pinnable-and-skinnable-OutlookBar | CC-MAIN-2018-47 | refinedweb | 126 | 51.65 |
PMADDPROFILE(3) Library Functions Manual PMADDPROFILE(3)
pmAddProfile - add instance(s) to the current PMAPI instance profile
#include <pcp/pmapi.h> int pmAdd(3)), and each instance profile may include instances from one or more instance domains (see pmLookupDesc(3)). pmAddProfile may be used to add new instance specifications to the instance profile of the current PMAPI context. In the simplest variant, the list of instances identified by the instlist argument for the indom instance domain are added). To select all instances in all instance domains, use pmAddProfile(PM_INDOM_NULL, 0, (int *)0) This is the only case where indom may be equal to PM_INDOM_NULL. If numinst is zero, or instlist is NULL, then all instances in indom are selected.
PMAPI(3), pmDelProfile add non-existent instance domains and non-existent instancesADDPROFILE(3)
Pages that refer to this page: pcpintro(3), pmapi(3), pmdelprofile(3), pmfetch(3), pmnewcontext(3) | http://man7.org/linux/man-pages/man3/pmaddprofile.3.html | CC-MAIN-2019-26 | refinedweb | 148 | 52.49 |
by Jeffrey Kantor (jeff at nd.edu). The latest version of this notebook is available at.
This Jupyter notebook shows how to use Antoine's equation and Raoult's law to compute flammability limits for methanol.
from IPython.display import YouTubeVideo YouTubeVideo("8gFqzbnUO-Y")
The flammability limits of methanol in air at 1 atmosphere pressure correspond to vapor phase mole fractions in the range
$$ 6.7 \mbox{ mol%} \leq y_{MeOH} \leq 36 \mbox{ mol%} $$
Assuming the pure methanol located in the wick of this fire starter reaches a vapor-liquid with air in the device, find the lower and upper operating temperatures for this device.
The first thing we'll do is define a simple python function to calculate the saturation pressure of methanol at a given temperature using Antoine's equation
$$\log_{10} P^{sat} = A - \frac{B}{T + C}$$
Constants for methanol can be found in the back of the course textbook for the case where pressure is given in units of mmHg and temperature in degrees centigrade.
# Pressure in mmHg, Temperature in degrees C A = 7.89750 B = 1474.08 C = 229.13 def Psat(T): return 10**(A - B/(T+C))
To test the function, we'll plot the saturation pressure of methanol for a limited range of temperatures.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline T = np.linspace(-14.0, 65.0, 200) plt.plot(T,Psat(T)) plt.xlabel('Temperature [deg C]') plt.ylabel('Pressure [mmHg]') plt.title('Saturation Pressure of Methanol') plt.grid()
print("Methanol Vapor Pressure at 25 deg C =",round(Psat(25.0),2),"mmHg")
Methanol Vapor Pressure at 25 deg C = 125.03 mmHg
At atmospheric pressure of 760 mmHg, the mole fraction of methanol is given by
print("Mole Fraction Methanol at 25 deg C and 1 atmosphere =",round(Psat(25.0)/760.0,3))
Mole Fraction Methanol at 25 deg C and 1 atmosphere = 0.165
Since this is within the flammability limits of methanol, the fire starter should work at room temperatures.
P_MeOH = 0.067*760 print(P_MeOH, "mm Hg")
50.92 mm Hg
Next we need to solve for the temperature at which the partial pressure of methanol is at the lower flammability limit.
$$P^{sat}_{MeOH}(T) = P_{MeOH}$$
We'll first attempt a solution by trial and error, then we'll use an equation solve to get an accurate solution. Let's start with a guess of 15 deg C.
print(Psat(15.0), "mmHg")
72.3445037835956 mmHg
That's too high. Let's try some more values
print(Psat(10.0), "mmHg")
54.09464146182495 mmHg
print(Psat(5.0), "mmHg")
39.94943048219959 mmHg
print(Psat(7.5), "mmHg")
46.56159278041358 mmHg
print(Psat(8.75), "mmHg")
50.20675457715808 mmHg
print(Psat(9.0), "mmHg")
50.96450071477327 mmHg
So $T = 9$ deg C is pretty close. To get a precise answer, use the
brentq equation solving function from
scipy.optimize.
from scipy.optimize import brentq def f(T): return Psat(T) - P_MeOH Tlow = brentq(f,5,15) print("Lower Flammability Temperature = ", Tlow, "deg C") print("Lower Flammability Temperature = ", 32.0 + 9.0*Tlow/5.0, "deg F")
Lower Flammability Temperature = 8.98540669181148 deg C Lower Flammability Temperature = 48.173732045260664 deg F | http://nbviewer.jupyter.org/github/jckantor/CBE20255/blob/master/notebooks/Operating%20Temperature%20Limits%20for%20a%20Methanol%20Fueled%20Lighter.ipynb | CC-MAIN-2018-26 | refinedweb | 543 | 69.68 |
#include "l_bitmap.h"
L_LTIVW_API L_INT EXT_FUNCTION L_DispContainerSetCellScaleMode(hCellWnd, nSubCellIndex,, uScaleMode,uFlags)
Sets the current scale mode for the specified cell or sub-cell.
A handle to the window that represents the cell on which the function's effect will be applied.
A zero-based index into the image list attached to the cell specified in nCellIndex. The sub-cell with nSubCellIndex, will have its scale mode set. Pass -2 to set the scale mode of the selected sub-cell.
Flag that indicates the type of the scale. L_DispContainerSetCellProperties. The other method is by using L_DispContainerGetCellScale and L_DispContainerSetCellScale. In order to be able to use these functions make sure that bIsFit is set to FALSE.
To get the scale of cell or sub-cell use the L_DispContainerGetCellScale function.
To set the scale of cell or sub-cell use the L_DispContainerSetCellScale function.
To set the properties of the scale action use the L_DispContainerSetActionProperties function.
To get the properties of the scale action use the L_DispContainerGetActionProperties function.
To set the scale mode of cell or sub-cell use the L_DispContainerSetCellScaleMode function.BeginUpdate.
Direct Show .NET | C API | Filters
Media Foundation .NET | C API | Transforms
Media Streaming .NET | C API | https://www.leadtools.com/help/sdk/v22/imageviewer/api/l-dispcontainersetcellscalemode.html | CC-MAIN-2022-05 | refinedweb | 196 | 51.34 |
Building an Enterprise CSS Framework
Early in my career as a front-end developer, I was very idealistic. It seemed things were black or white. That there was a right or wrong way to do everything. Of course, idealism can be a fabulous thing. Lofty goals are important.
At some point as I matured as a developer, pragmatism and practicality entered my world — I started to perceive the shades of gray. For any given challenge, there might be several different but equally viable solutions. But pragmatism and idealism don’t have to be in opposition to each other. Both are important to our craft when analyzing a situation and determining the most practical solution. They are the key to building a solid and maintainable structure.
After 16 years in the business, I was given the opportunity to join the Salesforce UX team, leading the effort to build an enterprise CSS framework for the new Salesforce Lightning Design System. The first thing I’ll tell you is, “Building an enterprise framework is hard.” I wasn’t naive enough to think it would be easy, but enterprise has considerations that most frameworks don’t need to take into account.
Our CSS framework will be consumed by a variety of disparate Salesforce users — engineers building on our platform, rapid prototypers building different views for testing, the various Salesforce clouds, and partners building apps on our platform using a variety of methods. The Design System framework has to be platform-agnostic and meet the needs of users on a variety of different technology stacks.
You have a Living Style Guide, why do you need a CSS Framework?
far enough.
How do I get my app to look like this?
Can I use your CSS in my app?
Salesforce partners wanted their apps to have a Salesforce look, but many didn’t have the resources or developers needed to make it happen, and those that did were inspecting in the browser to reverse engineer our code. A version of Bootstrap with a Salesforce look was created, though not by us, and it quickly fell out of step with our changing designs.
Internally, we also had a few needs not yet being met by our style guide. We want to empower our designers to code and iterate more efficiently in the browser. We want to enable our developers creating prototypes to build more quickly. But our style guide was static and didn’t provide an easy, maintainable way to grab or use the code.
On top of all of that, we were finally creating a completely reimagined Lightning Experience to replace the Salesforce classic UI. You can imagine how large a task it is to keep all our designers, along with hundreds of engineers, on the same page.
What we needed was a robust, powerful, living design system.
To meet this variety of needs, we wanted to build a Design System comprised of Salesforce design patterns, CSS and markup for components, icons, a custom font, color swatches, and other resources that both internal developers and partners could take advantage of. We wanted it to grow and evolve as Salesforce matured, bringing developer’s code along with it. We wanted our UI components to take the place of redline specs, allowing developers to reference actual code.
At Salesforce UX, we are guided by four design principles. In order of importance, they are — clarity, efficiency, consistency, and beauty . These principles assisted us in prioritizing competing goals and helped us make tough calls.
I’d like to share some of the decisions we made while architecting the framework. Some of these choices may be unexpected. And there have been times when our ideas have morphed while building, as we discovered yet another platform or situation we needed to solve for.
Clarity
Eliminate ambiguity. Enable people to see, understand, and act with confidence.
I realize, anyone who’s worked with CSS may already be struggling with the idea of “clarity in CSS”. What does this even mean?
We chose clarity and understandability in class names. Our classes are explicit. We use few abbreviations. And yes, it is verbose. But with our wide range of users, and their varied expertise with CSS, we opted for clarity over brevity. For us it’s worth the few extra characters.
We also opted for BEM naming. No matter what you believe about BEM (and the variants people have created), it makes it easier for different developers on the same project to understand a class more quickly. A class name like .house__door — wood immediately tells you that you have a component called house, with a door made of wood. Single classes also keep your code base flatter, virtually eliminating specificity issues, and helps to keep it more maintainable.
Another area where clarity played heavily into our decisions was our documentation. We love documentation. Well, to be perfectly honest, we don’t necessarily love writing it. Who does? But we love what it does for our users.
Let’s look at an example component, buttons. At the top of each component is the basic description of the component itself. That is followed by information you might need to be sure that component is accessible. From there, we move to the base style — which is the core structure of the component. The HTML and Sass for the base style are displayed in tabs. You can continue scrolling down the page to see each variant, or on the right side of each component page, you can click a link to the variant you’d like to see.
Each component variant has information specific to it, a living example you can interact with (you can hover or click the button to see its different states). It also displays the HTML and additional Sass needed for that variant. Variants are marked as either prototype or dev-ready. Prototype means that there may be changes coming for that component as we work with it further.
At the bottom of each component section, we have a component overview. It shows all the classes used for that component, what happens when it’s applied, whether it’s required or not, the DOM element it should be placed on, and sometimes, comments and caveats.
Efficiency
Streamline and optimize workflows. Intelligently anticipate needs to help people work better, smarter, and faster.
We started this process by doing an audit and inventory of all the components in our designer’s Lightning Experience Comps. (Wanna guess at how many font sizes we found?) Within our design system, design patterns were established to standardize all these designs. A sizing rhythm was established for fonts and spacing. Border-radius properties were aligned. Colors were minimized and aligned. This exercise let our designers align all their comps and allowed us to build lighter-weight, more efficient CSS.
As we inventoried each component, we were able to identify the objects and patterns which made up the component itself. We began by building the smallest objects, which were then combined to create the larger components.
One of those small objects is the media object. If you’re familiar with OOCSS, you know that the media object is simply an image, icon or other figure sitting next to text. It’s a very common pattern — especially in our applications. Since our browser target for the framework is “all modern browsers including Internet Explorer 11,” we had the latitude to utilize flexbox. This means we were able to combine the media object and a similar abstraction, the flag object, into a single object (the .media — centered variant displays like the flag object).
This basic object is combined with other small abstractions to create larger components. Tiles are a good example of a small component that uses even smaller abstractions. The Activity Timeline is a larger component created from many smaller abstractions, including the media object, form elements, various lists, etc.
Enterprise applications have unique traits and we made unique decisions.
Our design audit showed us other interesting things. Enterprise applications demand content and data-rich interfaces. They lack vertical rhythm. In our design audits, we found that headings and paragraphs rarely have margins. So we removed them by default.
Semantically, lists are used a great deal in enterprise applications — ul, ol and dl. But they rarely need list markers and certainly don’t need their default indentation. By default, we removed the default list-style, margin, and padding. Then we created several utility classes to add the behavior back in if needed.
Though this might sound strange, it solves the majority of our use cases. We have a number of padding and margin utilities if users need to opt back in to spacing. We also have a wrapper class to put around a whole section of content if you need the default element styling in a whole area.
In a framework, we can’t know how and where users plan to use headings. So another rather unique choice we made was to equalize all headings to a default of 1rem. This removes the temptation to use an h3 because it’s the size a developer needs. They should use the proper semantic heading level and add the proper text utility to create the heading style.
Working in the enterprise means that accessibility is a directive. Accessibility for all people and devices is a high priority at Salesforce. I love this since accessibility has always been near and dear to my development heart. For this reason, we bake accessibility into our framework.
- Where semantics matter, we use the proper elements.
- Our components receive the proper ARIA roles.
- We have accessibility documentation for components so that when you’re adding javascript, you can be sure not to miss anything.
- Sizing is defined in REM units, so the whole component scales when text size increases. While I understand that people with younger eyes and good vision may say, “But the browser can zoom! What’s the point?” There actually is a point. Many users with low vision change the default text size for their browser. When they surf onto your site with large text, if you’ve defined your components in pixels, the component will remain the default pixel size. But the text could be very large making it unsightly and possibly breaking out of the component bounds. With REM units, the component scales with the text and though larger, the user sees exactly what you designed.
Consistency
Create familiarity and strengthen intuition by applying the same solution to the same problem.
Design tokens are the basic atoms of the design system. Design tokens are simply variables or constants that represent a value. During the design audit I previously mentioned, we were able to identify common values which we then created as tokens. By using these tokens, or variables, our user’s applications will remain in sync if there’s a change in the design system value. You can find tokens inside the resources section of the site.
We provide tokens for a large number of properties:
- Fonts
- Font Sizes
- Font Weights
- Line Heights
- Background Colors
- Text Colors
- Border Colors
- Shadows
- Spacing
- Sizing
- Animation Durations
- Media Queries
- Z-indexes
Using Sass and our token variables will also allow users to give their application custom branding if desired. Tokens are also great for our designers when specing their designs. They are able to use these tokens instead of absolute values.
We play well with others.
Whether you’re using Sass or not, every developer writing CSS knows that the most frustrating part of CSS is — the C. Cascading and specificity wars are just awesome! Not. Since some of the class names used in our framework are common, and could exist in our user’s personal CSS (or another framework), causing conflicts, we chose to namespace all our class names. Rather than using .button we use .slds-button. As long as users can use normalize.css and our base element styles in their application, this is all that’s needed.
But what if a user is in an environment where they don’t control all of the DOM? They might be creating a Visualforce page or a Lightning component that includes their app in another environment. They might be transitioning off the out-of-date Bootstrap version created years ago. In that case, we offer scoping. This simply means they will wrap their design system components in an .slds wrapper. Essentially, this keeps our base element defaults from clashing with those in the other system.
So for example, an h1 becomes .slds h1 so that, within our components, our element styles trump any other base element styling.
Beauty
Demonstrate respect for people’s time and attention through thoughtful and elegant craftsmanship.
Those of you building for a variety of form factors and devices know that making everything look great can be challenging. We chose SVG icons for beauty at every size. They allow you to have a consistent, crisp look no matter the resolution. We created sprites of our SVGs using the symbol element. Though we could have put all the accessibility requirements directly on the symbol element, we chose to only include the viewbox in the symbol. We allow the developer to add the accessibility text since it may vary with a specific usage. Note: Since <symbol> is a replaced element, it has an inherent size in the browser. You must give the icons a width and height to override that default.
Most of our components are built so that the width is controlled by the parent container. They can be included in a wide, main page area or in a narrow sidebar. This makes it easier to keep both mobile and desktop applications attractive. Also, heights are rarely used. We’ve opted instead to use line-height, min/max-height and flexbox to control heights where needed. This is important for localization and accessibility as well.
How did we make these decisions?
Though we were guided by the four defining principles, my teammates Jina Anne, Brandon Ferrua and I also had numerous, and wide-ranging, discussions and debates about literally ALL THE THINGS. In my opinion, debate is a seriously healthy sanity check for all of us. Sometimes in making your case, you hear what you’re missing. Other times you sway someone else. Two or three brains are always better than one.
As you’ve probably found when debating and discussing with colleagues, sometimes after you each make your point, you still don’t come to an agreement. What to do? For us, we move to Cap Watkins Sliding Scale. It’s an awesome idea that might help your team make decisions as well (though feel free to use whatever verbiage works in your team). In a nutshell, the person who’s still the most passionate after the discussion wins!
We’ve just reached beta. We still have some things to clean up, changes to make and probably a good bit to add. It’s a process. We’re open source now, so we hope to get some great community feedback and assistance from you. While it was hard, with the team we have working on this, hard has been the most fun I’ve ever had!
Want to work with us? Contact uxcareers@salesforce.com | https://medium.com/salesforce-ux/building-an-enterprise-framework-is-hard-1e8d8b33e082?utm_source=CSS-Weekly&utm_campaign=Issue-181&utm_medium=web | CC-MAIN-2017-17 | refinedweb | 2,550 | 65.52 |
Is there an equivalent of C's "?:" ternary operator?
Yes. In Python 2.5 and later, you can use:
<true-value> if <condition> else <false-value>
Note that the condition is in the middle of the expression, not at the front. This syntax is similar to the list comprehension syntax.
In earlier versions, you can often.
Tim Peters (who wishes it was Steve Majewski) ‘if’.
The best course is usually to write a simple if…else statement. Another solution is to implement the “?:” operator as a function:
def q(cond,on_true,on_false): if cond: result = on_true else: result = on_false if callable(result): return result() return result
In most cases you’ll pass b and c directly: q(a,b,c). To avoid evaluating b or c when they shouldn’t be, encapsulate them within a lambda function, e.g.: q(a,lambda: b, lambda: c).
History
It has been asked why Python didn’t have an if-then-else expression. There are several answers: many languages do just fine without one; it can easily lead to less readable code; no sufficiently “Pythonic” syntax had. | http://effbot.org/pyfaq/is-there-an-equivalent-of-c-s-ternary-operator.htm | CC-MAIN-2013-48 | refinedweb | 184 | 58.69 |
This rule in a userstylesheet I use seem to affect it:
*[id*='related'], *[id*='side'], *[role*="complementary"], *[id*='Panel'], *[id*='Layout'] {
visibility:hidden !important;
}
Before:
After:
So, is there any documentation of its HTML?
Edit:: And can I exclude it by @-moz-document regexp()?
@-moz-document regexp()
Workaround:: prefix body on all selectors (body [id*='related'],...) to restrict applying only on webpages. (apparently sidebar doesn't live inside a <body> tag) demo
body
body [id*='related'],
<body>
Firefox's interface is written in XUL which is a form of XML. It's markup is almost identical to HTML with some other advantages, particularly for add-on devs.
To view the code that constructs the user interface, open a new tab and go to chrome://browser/content/browser.xul. This will display your web browser's interface inside the web browser. Then, use Firefox's built-in web dev tools to inspect the markup or press Ctrl+U to view the source.
chrome://browser/content/browser.xul
It's so damn easy to edit, even for someone with little to no programming knowledge. This is why I love Firefox. You can live-edit the CSS and when you're happy with the changes, use Stylish to make a new style (blank style, using the XUL namespace) and save it.
asked
3 years ago
viewed
86 times
active
2 years ago | http://superuser.com/questions/503758/the-bookmarks-sidebar-in-firefox-seems-to-be-rendered-in-html | CC-MAIN-2016-30 | refinedweb | 229 | 65.42 |
Hi there,
I started working with a terasIC DE0-Nano-SoC about 4 months ago.
I was both new to FPGA and also Linux at the beginning of my programm.
Recently I wanted to implement more accurate timing of my C-code. SO I
added following code to try to see how long my programm takes for a
loop:
#include <time.h>
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
printf("%d seconds and %ld nanoseconds\n", ts.tv_sec, ts.tv_nsec);
When I tried to execute the file I got the following error:
/lib/libc.co.6: version 'GLIBC_2.17' not found
Upon further investigation I found out that my linux runs on EGLIBC
2.15.
My Systems runs on the Linux supplied by terasIC at:
It is Linux version 3.13.0-00298-g3c7cbb9-dirty.
The Toolchain for the cross compiler is also delivered straight from the
DE0-Nano-SoC_v.1.1.0_SystemCD. This toolchain has GLIBC
Is there anything I can do to resolve this problem: i.E. change the
GLIBC for either the the Cross compiler or the Linux?
I did read about someone building their own Angstrom system and using
its instead of the Linux provided by terasIC.
But there was no explanation on how they did it and I am not experienced
enought to something like that myself. - this
is where I found this.
If there is no easy fix for my situation. Is there a way to have my
programm execute every 20 us without the time.h header?
Thanks a lot,
Alex
Better install debian and deal with the end | https://embdev.net/topic/414384 | CC-MAIN-2019-26 | refinedweb | 265 | 74.9 |
The QGraphicsGridLayout class provides a grid layout for managing widgets in Graphics View. More...
#include <QGraphicsGridLayout>
Inherits QGraphicsLayout.
This class was introduced in Qt 4.4.
The QGraphicsGridLayout class provides a grid layout for managing widgets in Graphics View.
The most common way to use QGraphicsGridLayout is to construct an object on the heap with no parent, add widgets and layouts by calling addItem(), and finally assign the layout to a widget by calling QGraphicsWidget::setLayout(). QGraphicsGridLayout automatically computes the dimensions of the grid as you add items.
QGraphicsScene scene; QGraphicsWidget *textEdit = scene.addWidget(new QTextEdit); QGraphicsWidget *pushButton = scene.addWidget(new QPushButton); QGraphicsGridLayout *layout = new QGraphicsGridLayout; layout->addItem(textEdit, 0, 0); layout->addItem(pushButton, 0, 1); QGraphicsWidget *form = new QGraphicsWidget; form->setLayout(layout); scene.addItem(form);() will remove an item from the layout, without destroying it.
See also QGraphicsLinearLayout and QGraphicsWidget.
Constructs a QGraphicsGridLayout instance. parent is passed to QGraphicsLayout's constructor.
Destroys the QGraphicsGridLayout object.
Adds item to the grid on row and column. You can specify a rowSpan and columnSpan and an optional alignment.
Adds item to the grid on row and column. You can specify an optional alignment for item.
Returns the alignment for item.
See also setAlignment().
Returns the alignment for column.
See also setColumnAlignment().
Returns the number of columns in the grid layout. This is always one more than the index of the last column that is occupied by a layout item (empty columns are counted except for those at the end).
Returns the maximum width for column.
See also setColumnMaximumWidth().
Returns the minimum width for column.
See also setColumnMinimumWidth().
Returns the preferred width for column.
See also setColumnPreferredWidth().
Returns the column spacing for column.
See also setColumnSpacing().
Returns the stretch factor for column.
See also setColumnStretchFactor().
Returns the number of layout items in this grid layout.
Reimplemented from QGraphicsLayout.
Returns the default horizontal spacing for the grid layout.
See also setHorizontalSpacing().
Returns a pointer to the layout item at (row, column).
Returns the layout item at index, or 0 if there is no layout item at this index.
Reimplemented from QGraphicsLayout.
Removes the layout item at index without destroying it. Ownership of the item is transferred to the caller.
Reimplemented from QGraphicsLayout.
See also addItem().
Returns the alignment of row.
See also setRowAlignment().
Returns the number of rows in the grid layout. This is always one more than the index of the last row that is occupied by a layout item (empty rows are counted except for those at the end).
Returns the maximum height for row, row.
See also setRowMaximumHeight().
Returns the minimum height for row, row.
See also setRowMinimumHeight().
Returns the preferred height for row, row.
See also setRowPreferredHeight().
Returns the row spacing for row.
See also setRowSpacing().
Returns the stretch factor for row.
See also setRowStretchFactor().
Sets the alignment for item to alignment.
See also alignment().
Sets the alignment for column to alignment.
See also columnAlignment().
Sets the fixed width of column to width.
Sets the maximum width of column to width.
See also columnMaximumWidth().
Sets the minimum width for column to width.
See also columnMinimumWidth().
Sets the preferred width for column to width.
See also columnPreferredWidth().
Sets the spacing for column to spacing.
See also columnSpacing().
Sets the stretch factor for column to stretch.
See also columnStretchFactor().
Sets the bounding geometry of the grid layout to rect.
Reimplemented from QGraphicsLayoutItem.
Sets the default horizontal spacing for the grid layout to spacing.
See also horizontalSpacing().
Sets the alignment of row to alignment.
See also rowAlignment().
Sets the fixed height for row, row, to height.
Sets the maximum height for row, row, to height.
See also rowMaximumHeight().
Sets the minimum height for row, row, to height.
See also rowMinimumHeight().
Sets the preferred height for row, row, to height.
See also rowPreferredHeight().
Sets the spacing for row to spacing.
See also rowSpacing().
Sets the stretch factor for row to stretch.
See also rowStretchFactor().
Sets the grid layout's default spacing, both vertical and horizontal, to spacing.
See also rowSpacing() and columnSpacing().
Sets the default vertical spacing for the grid layout to spacing.
See also verticalSpacing().
Returns the default vertical spacing for the grid layout.
See also setVerticalSpacing(). | http://doc.trolltech.com/4.5-snapshot/qgraphicsgridlayout.html | crawl-003 | refinedweb | 694 | 55.91 |
Created on 2016-06-04 19:54 by Oren Milman, last changed 2017-03-31 16:36 by dstufft. This issue is now closed.
------------ current state ------------
1. long_rshift first checks whether a is a negative int. If it is, it does (edited for brevity) 'z = long_invert(long_rshift(long_invert(a), b));'.
Otherwise, it calculates the result of the shift and stores it in z. In this block, there is a check whether a is a negative int.
The second check was always there - since revision 443, in which long_rshift was first added. However, in revision 590, the first aforementioned check (whether a is a negative int), along with a (edited for brevity) 'return long_invert(long_rshift(long_invert(a), b));' were added, but the second check whether a is a negative int wasn't removed, and remained there to this day.
2. Ultimately, long_rshift does 'return (PyObject *) maybe_small_long(z);' for both cases (whether a is a negative int or not).
Calling maybe_small_long in case a is a negative int is redundant, as long_invert returns (in case it doesn't fail) by either doing 'return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));' or 'return (PyObject *)maybe_small_long(x);'. In both cases, long_invert would return a reference to an element of small_ints if it should.
Calls to maybe_small_long were added both to long_rshift and long_invert in revision 48567, as part of an effort to wipe out different places in the code where small_ints could be used (to save up memory), but was not. I am not sure why maybe_small_long was added to long_rshift where it would be redundant in case a is a negative int.
3. In different cases of failure, long_rshift does 'goto rshift_error;'.
The destination of these goto statements is actually a return statement that would also be reached in almost any case of success (except for a certain case in which the result of the shift is obviously zero).
That goto was added in revision 15725. Back then, CONVERT_BINOP was added, and calling it in long_rshift required calling Py_DECREF for a and b before returning.
Later on, in revision 43313, CONVERT_BINOP was removed, along with the calls to Py_DECREF it required, but the goto was left untouched, and remained there to this day.
------------ proposed changes ------------
All of the proposed changes are in Objects/longobject.c in long_rshift:
1. Remove the check whether a is a negative int in the block that gets executed in case a is not a negative int.
2. Move the call to maybe_small_long inside the block that runs in case a is not a negative int.
3. Replace every 'goto rshift_error;' with a 'return NULL;', and remove the rshift_error label.
I could have kept the goto statements, with 'return (PyObject *)z;' as their destination, but I believe it would have been less clear. Also, there are many similar places in longobject.c where 'return NULL;' is done on failure.
------------ diff ------------
The proposed patches diff file is attached.
------------ tests ------------
I built the patched CPython for x86, and played with it a little. Everything seemed to work as usual.
Specifically, I did:
for i in range(10000):
if not all(smallInt is ((smallInt << i) >> i) for (
smallInt) in range(-5, 257)):
break
print(i)
And indeed 9999 was printed.
In addition, I ran 'python_d.exe -m test -j3' (on my 64-bit Windows 10) with and without the patches, and got quite the same output.
the outputs of both runs are attached.
Sorry, this fell off my list of things to look at.
New changeset 21b70c835b5b by Mark Dickinson in branch 'default':
Issue #27222: various cleanups in long_rshift. Thanks Oren Milman.
Thanks for the patch and the thorough analysis! | https://bugs.python.org/issue27222 | CC-MAIN-2021-49 | refinedweb | 605 | 64.51 |
CodePlexProject Hosting for Open Source Software
Unfortunately I had a serious issue yesterday and lost a TON of code while trying to push to my repository, including something really simple I had working in the editor shape for one of my parts.
I had some if/else logic that determined if I was creating a new item or updating an existing item and displayed text based on which one it was.
I cannot recall how it was written and have now spent a good hour trying different things in an attempt to duplicate the code.
Does anyone know how I can tell if the Model is a published item or not in the editor shape?
I could really use a memory jog (and more coffee). Thanks.
EDIT
-------
I think I may have gotten it. Is it simply?
Model.HasPublished()
Almost: use the .IsPublished() extension method of IContent
(import the Orchard.ContentManagement namespace, if not already done so).
Correction: looking at the implementation of .HasPublished, that would work as well. I think it will see if there's at least a published version. Not sure what the difference would be in practice though as I have not used it before.
Thanks...I'll play around with both to see if there's any noticeable difference. .HasPublished() appears to be working good for now.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/373966 | CC-MAIN-2017-30 | refinedweb | 258 | 75.61 |
SMB/CIFS file migration engine
For the last 9 months, I’ve been working on a SMB/CIFS virtualization product at Brocade. We announced this product to the world yesterday.
FME lets sysadmins migrate open files (holding rangelocks and oplocks) that are being used by client applications in a DFS namespace, from one filer to another without disruption. Hence the name virtualization. Client applications don’t know that files are being moved at the remote end. My work has been in the CIFS datapath, tracking and restoring open file metadata such as rangelocks and oplocks, and also helping migration processes track changes in a file’s data while it’s being migrated. It’d be very cool to a network filesystem developer or even a sysadmin, to see a Wireshark packet capture of the orchestrated steps.
This work was, for various reasons, done in Windows land, as a driver. Yes, I know.. ugh yuck bleh, but I got to explore a bit of Windows land :).
Syndicated 2008-03-19 23:38:41 from Mukund's adventures | http://www.advogato.org/person/muks/diary.html?start=12 | CC-MAIN-2014-10 | refinedweb | 176 | 64.81 |
49114/numpy-all-differing-from-builtin-all
What is the reason for this weirdness in numpy's all?
>>> import numpy as np
>>> np.all(xrange(10))
False
>>> np.all(i for i in xrange(10))
True
Numpy.all does not understands generator expressions.
From the documentation
numpy.all(a, axis=None, out=None)
Test whether all array elements along a given axis evaluate to True.
Parameters :
a : array_like
Input array or object that can be converted to an array.
Hi, it is pretty simple, to be ...READ MORE
You can use the code below:
lis = ...READ MORE
Hi. Refer to the below command:
import pandas ...READ MORE
Use the following code:
import numpy as np
a=np.array([1,2,3,4])
b=np.delete(a,2)
OUTPUT:
array([1, ...READ MORE
just index it as you normally would. ...READ MORE
Use the .shape to print the dimensions ...READ MORE
Slicing is basically extracting particular set of ...READ MORE
numpy.set_printoptions(threshold='nan')
READ MORE
You can use the following :
y = ...READ MORE
You can use cdist -
In [1]: from scipy.spatial.distance import ...READ MORE
OR | https://www.edureka.co/community/49114/numpy-all-differing-from-builtin-all?show=49146 | CC-MAIN-2019-30 | refinedweb | 187 | 64.37 |
3 Ways to Render Large Lists in Angular
Giancarlo Buomprisco
・6 min read
An overview of the available techniques to render large lists of items with Angular
This article was originally published on Bits and Pieces by Giancarlo Buomprisco
Frameworks in 2020 got better, more efficient and faster. With that said, rendering large lists of items on the Web without causing the Browser to freeze can still be hard even for the fastest frameworks available.
This is one of the many cases where “the framework is fast, your code is slow”.
There are many different techniques that make rendering a large number of items in a non-blocking way for the users. In this article, I want to explore the current techniques available, and which ones are best to use based on particular use-cases.
Although this article focuses on how to optimize rendering with Angular, these techniques are actually applicable to other frameworks or simply Vanilla Javascript.
The framework is fast, your code is slow
This article goes in detail about an aspect I talked about in one of my previous articles: rendering too much data.
Top Reasons Why Your Angular App Is Slow and performance-optimized code across your Angular projects.
You can read more about it in my previous post:
Sharing Components with Angular and Bit
*An Introduction to Bit: Building and sharing Angular components*blog.bitsrc.io
1. Virtual Scrolling
Virtual Scrolling is probably the most efficient way of handling large lists, with a catch. Thanks to the Angular CDK and other plugins it is very easy to implement in any component.
The concept is simple, but the implementation is not always the easiest:
- given a container and a list of items, an item is only rendered if it’s within the visible boundaries of the container
To use the CDK’s Scrolling module, we first need to install the module:
npm i @angular/cdk
Then, we import the module:
import { ScrollingModule } from '@angular/cdk/scrolling'; @NgModule({ ... imports: [ ScrollingModule, ...] }) export class AppModule {}
We can now use the components to use virtual scrolling in our components:
<cdk-virtual-scroll-viewport <div * {{ item }} </div> </cdk-virtual-scroll-viewport>
As you can see, this is extremely easy to use and the results are impressive. The component renders thousands and thousands of items without any problem.
If Virtual Scrolling is so good and easy to achieve, why bother exploring other techniques? This is something I’ve been wondering too — and actually there’s more than one reason as to why.
The way it’s going to work is very dependent on implementation: it’s hard to be able to manage all the possible scenarios with one single implementation.
For example, my component depended on the Autocomplete field (built by the same team) and unfortunately, it didn’t work as expected. The more complex your items, the more difficult it’s going to be.
Another module, another big chunk of code added to your app.
Accessibility and Usability: the hidden items are not rendered, and therefore won’t be searchable.
Virtual Scrolling is ideal (when it works) in a number of situations:
an undefined and possibly enormous list of items (approximately greater than 5k, but it’s highly dependent on the complexity of each item)
infinite scrolling of items
2. Manual Rendering
One of the options I’ve tried to speed up a large list of items is manual rendering using Angular’s API rather than relying on *ngFor.
We have a simple ngFor loop template:
<tr * <td> <span class="py-2 px-4">{{ item.id }}</span> </td> <td> <span>{{ item.label }}</span> </td> <td> <a> <button class="py-2 px-4 rounded (click)="remove(item)">x</button> </a> </td> </tr>
I’m using a benchmark inspired by js-frameworks-benchmark to calculate the rendering of 10000 simple items.
The first benchmark run was done with a simple, regular *ngFor. Here are the results: scripting took 1099ms and rendering took 1553ms, 3ms painting.
By using Angular’s API, we can manually render the items.
<tbody> <ng-container #itemsContainer></ng-container> </tbody> <ng-template #item <tr class="h-12" [class.bg-gray-400]="isEven" [class.bg-gray-500]="!isEven" > <td> <span class="py-2 px-4">{{ item.id }}</span> </td> <td> <span>{{ item.label }}</span> </td> <td> <a> <button class="py-2 px-4 rounded" (click)="remove(item)">x</button> </a> </td> </tr> </ng-template>
The controller’s code changes in the following way:
- we declare our template and our container
@ViewChild('itemsContainer', { read: ViewContainerRef }) container: ViewContainerRef; @ViewChild('item', { read: TemplateRef }) template: TemplateRef<*any*>;
- when we build the data, we also render it using the ViewContainerRef createEmbeddedView method
private buildData(length: number) { const start = this.data.length; const end = start + length; for (let n = start; n <= end; n++) { this.container.createEmbeddedView(this.template, { item: { id: n, label: Math.random() }, isEven: n % 2 === 0 }); } }
Results show a modest improvement:
- 734ms time spent scripting, 1443 rendering, and 2ms painting
In practical terms, though, it’s still super slow! The browser freezes for a few seconds when the button is clicked, delivering a poor user experience to the user.
This is how it looks like (I’m moving the mouse to simulate a loading indicator 😅):
Let’s now try Progressive Rendering combined with Manual Rendering.
3. Progressive Rendering
The concept of progressive rendering is simply to render a subset of items progressively and postpone the rendering of other items in the event loop. This allows the browser to smoothly and progressively render all the items.
The code below is simply:
we create an interval running every 10ms and render 500 items at once
when all items have been rendered, based on the index, we stop the interval and break the loop
private buildData(length: number) { const ITEMS_RENDERED_AT_ONCE = 500; const INTERVAL_IN_MS = 10; let currentIndex = 0; const interval = setInterval(() => { const nextIndex = currentIndex + ITEMS_RENDERED_AT_ONCE; for (let n = currentIndex; n <= nextIndex ; n++) { if (n >= length) { clearInterval(interval); break; } const context = { item: { id: n, label: Math.random() }, isEven: n % 2 === 0 }; this.container.createEmbeddedView(this.template, context); } currentIndex += ITEMS_RENDERED_AT_ONCE; }, INTERVAL_IN_MS);
Notice that the number of items rendered and the interval time is totally dependent on your circumstances. For example, if your items are very complex, rendering 500 items at once is certainly going to be very slow.
As you can see below, the stats look certainly worse:
What’s not worse though is the user experience. Even though the time it takes to render the list is longer than before, the user can’t tell. We’re rendering 500 items at once, and the rendering happens outside of the container boundaries.
Some issues may arise with the container changing its size or scroll position while that happens, so these issues need to be mitigated in a few cases.
Let’s see how it looks like:
Final Words
The above techniques are certainly useful in some situations and I’ve used them whenever virtual scrolling was not the best option.
With that said, for the most part, virtual scrolling using a great library like Angular’s CDK is definitely the best way to tackle large lists.
If you need any clarifications, or if you think something is unclear or wrong, do please leave a comment!
I hope you enjoyed this article! If you did, follow me on Medium, Twitter or Dev for more articles about Software Development, Front End, RxJS, Typescript and more!
Join DEV Now
Open source
Free forever
Level up every day
🔥
🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained
In the next post we are going to explore CSS @apply to supercharge what we talk about here....
Hey @gc_psk , Great article!
I had doubt in one thing, in your code for Progressive Rendering, somewhere around line 10, you have this condition:
if (n >= length) {
but I couldn't see any variable with name of
length. Can you please check?
Hi Dharmen,
lengthis passed as an argument. It represents the length of the list being rendered :)
Oh, Gothcha... 😅
One other way:
Don't render 1000 items.
Render only first 100 and add a load more button. If the user wants to load more then they need to click on the button and render the next 100. Simple and easy.
Pagination or your solution are definitely other viable ways - but present the same usability limitations as virtual scrolling.
In my case, this was not an option: I have to render thousands of fonts within a dropdown. No other solution has a "click here to load more fonts" button - so I'd be at a disadvantage. This would definitely be a UX limitation for my users.
At the end of the day:
You can replace the load more button with a Visibility trigger or a component that calls a callback when the element is in view port, Then, you will trigger a load more action automatically.
Great post! I'd add that you can improve performance (especially when filtering / search) is involved by providing a
trackByfunction. This way you don't need to rerender DOM nodes which have not been changed. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/angular/3-ways-to-render-large-lists-in-angular-10nl | CC-MAIN-2020-24 | refinedweb | 1,508 | 51.38 |
RE: Import picture into Excel cell
- From: Joel <Joel@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sun, 15 Mar 2009 11:26:05 -0700
I hate excel also because it makes it so difficult to do some obvious simple
taskw. I'vew been doing a lot of programming in excel VBA using the internet
explorer. I put a sample of my code below. I don't know if there is a way
with the internet explorer to copy a picture and place it on the worksheet.
I still think the way is to use the Insert Picture.
You can use this line to import a picture fro a file
ActiveSheet.Pictures.Insert( _
set MyPicture = "C:\Documents and Settings\Joel\" & _
"My Documents\MyPictures\lincoln.bmp")
Here is a JPG file I added to my worksheet from microsoft.com using the same
command
Sub AddPicture()
MyPicture = "" & _
"Windowsce/007LOGO.JPG"
Set MyPict = ActiveSheet.Pictures.Insert(MyPicture)
End Sub
Here is an example of using internet explorer from Excel VBA
Sub GetZipCodes()
ZIPCODE = InputBox("Enter 5 digit zipcode : ")
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
URL = ""
'get web page
IE.Navigate2 URL
Do While IE.readyState <> 4
DoEvents
Loop
Do While IE.busy = True
DoEvents
Loop
Set Form = IE.document.getElementsByTagname("Form")
Set zip5 = IE.document.getElementById("zip5")
zip5.Value = ZIPCODE
Set ZipCodebutton = Form(0).onsubmit
Form(0).submit
Do While IE.busy = True
DoEvents
Loop
Set Table = IE.document.getElementsByTagname("Table")
Location = Table(0).Rows(2).innertext
IE.Quit
MsgBox ("Zip code = " & ZIPCODE & " City/State = " & Location)
End Sub
"Joel" wrote:
I usually right click the picture and trhen save to a local drive. Then.
import the picture into excel using menu option Insert - Picture - From file.
I think if you want to emiminate a step you can use menu Insert - Picture -
Frimn file and put the url address into the picture address. The Picture
isn't sored at the URL of the webpage put in a folder associated with the URL
address.
"Gandalf the White" wrote:
I am trying to import a picture off of the web, not data, into an Excel
cell.
When I do a New Web Query, while the table visually includes the image, the
image is not downloaded.
I think that is because the image is stored at a different URL.
When I enter the URL of the image into the cell, all I get is the URL
address.
If I double click on the cell, IE shows me the image.
So, I know the address is correct.
How do I tell Excel that I want it to download the image?
All assistance gratefully appreciated.
Gandalf
- Follow-Ups:
- Re: Import picture into Excel cell
- From: Gandalf the White
- References:
- Import picture into Excel cell
- From: Gandalf the White
- RE: Import picture into Excel cell
- From: Joel
- Prev by Date: MsgBox
- Next by Date: Form temporary variables
- Previous by thread: Re: Import picture into Excel cell
- Next by thread: Re: Import picture into Excel cell
- Index(es): | http://www.tech-archive.net/Archive/Excel/microsoft.public.excel.programming/2009-03/msg03045.html | CC-MAIN-2015-22 | refinedweb | 496 | 57.77 |
- Training Classes
- Schedule
- Pricing & Savings
- Training Options
- Resources
In this lesson, you will learn about basic syntax, data types, and various writing methods.
Stringclass.
Java; }
Variables store data that your code can use.
There are two fundamental categories of variables, primitive data and references:
In the diagram below, the boxes are areas in memory:
Variables must be declared before they are used.
A declaration informs the compiler that you wish to:
Java uses many specific data types; each has different properties in terms of size required and handling by the compiler:
Note that different languages have different rules regarding variables that have not been initialized:
Local variables, fields, methods, and classes may be given additional modifiers; keywords that determine special characteristics.
Any modifiers must appear first in any declaration, but multiple modifiers may appear in any order.
Objects can be data, which can be stored in variables, passed to methods, or returned from methods.
As we will see later, objects are stored differently than primitives. An object variable stores a reference to the object (the object is located at some other memory location, and the reference is something like a memory address).
A sequence of text, such as a name, an error message, etc., is known as a string.
In Java, the
String class is used to hold a sequence of text characters.
A
String object:
Stringobject at any time).
A value typed into your code is called a literal value.
The compiler makes certain assumptions about literals:
trueand
falseare literal
booleanvalues.
nullis a literal reference to nothing (for objects).
int, unless it is immediately assigned into a variable of a smaller type and falls within the valid range for that type.
double.
You can add modifiers to values to instruct the compiler what type of value to create (note that all the modifiers described below can use either uppercase or lowercase letters).
Modifying prefixes enable you to use a different number base:
0x7Ffor a
bytewould be OK, but
0x80would not, since the latter would have a value of 128, outside the range of
byte).
longvalue would need the
Lmodifier as discussed below.
Modifying suffixes create a value of a different type than the default:
There are a number of escape sequences that are used for special characters:
The escape sequences can either be used for single characters or within strings of text:
char c = '\u1234'; System.out.println("\t\tHello\n\t\tWorld");
finalKeyword
Java has a means for defining contants, which are like variables in that they have names, but are not changeable once set.
If a variable is declared as
final, it cannot be changed:
final.
final.
Fields of a class may be declared as
public static final - that way they are available to other classes, but cannot be changed by those other classes. An example is
Math.PI.
Classes and methods may also be marked as
final. We will cover this later.
public class FinalValues { // a constant final int scale = 100; // value below is dynamically created, // but cannot change afterward final int answer = (int)(Math.random() * scale); public static void main(String[] args) { FinalValues fv = new FinalValues(); System.out.println(fv.answer); // line below would not compile: // fv.answer = 44; } }
The class has two final fields,
scale and
answer. The
scale is fixed at 100, while the
answer is initialized dynamically, but, once established, the value cannot be changed. Try removing the comment from the line that attempts to set it to 44, and you will see the compiler error message that results.
Looks.
The method is the basic complete unit of code to perform one task within an object:
Using a method in your code, causing it to run, is known as calling the method.
A method call is an expression, so it may result in a value (the method call is evaluated like any other expression).
z = Math.sin(Math.PI / Math.sqrt(x));
Methods must be called with arguments that matching their specified form, known as the function signature:
All methods in Java must be defined within a class definition. They have complete access to all other elements of the class (fields and other methods, regardless of the access modifier used for that element).
public class UseMethodsExample { public static void main(String[] args) { int x = 16; double y = Math.sqrt(x); System.out.println("Square root of " + x + " is " + y); double z = Math.sin(Math.PI / 2); System.out.println("Sine of pi/2 is " + z); } }
This class calls two methods from the
Math class:
sqrt and
sin, both of which expect one parameter which is a
double.
When we call
sqrt and pass an integer, the compiler converts that to a
double to provide the type of data that
sqrt expects
Note that even if your program does not call any methods, it has one method that will be called:
main(). Things to note:
main()is that it provides a start point and end point for your program.
main().
main()is executed, the program ends.
main()does have arguments (any other words typed on the command line).
There are three things you need to decide for any method:
[modifiers] dataType methodName(parameterList) { methodBody return result; }
modifiersinclude the accessibility of this method from outside the class (
public,
private,
protected, or left blank) as well as other possibilities listed earlier in this section.
dataTypeis a type of data, like
int.
methodNameis the name of your method.
parameterListis a comma-separated list of parameters; each parameter is listed with its data type first, then its name.
methodBodyis the set of statements that perform the task of the method.
returnis a keyword that says to use the
resultexpression value as the result of calling the method, and send that value back to the code that called the method (as an expression, a call to a method evaluates to the returned value; i.e., calling
Math.sqrt(4)evaluates to the value that
sqrtreturned).
public void sayHello() { System.out.println("Hello"); }
publicmethods are accessible to any other class.
voidis a keyword for a returned data type that means no data at all - this method does not calculate a result.
sayHello.
public void showNumber(int number) { System.out.println("The number is: " + number); }
>public int calculateSum(int num1, int num2) { int answer = num1 + num2; return answer; }
int.
intdata types.
Note that the listing of a data type word in front of a name is something we have seen before, in declaring variables. The purpose is the same - to state what type of data this element provides when used in an expression.
The first statement below states that the value of
a is an
int, so that the compiler knows what memory size to allocate and what type of processing to use with it when it evaluates the second statement.
int a; int b = a / 2;
The effect is no different using a method; recall the function signature (the first line) of our
calculateSum method:
public int calculateSum(int num1, int num2)
It states that the result of evaluating
calculateSum is an
int, so that the compiler knows what memory size to allocate for the result, and what type of processing to use with it when it evaluates a statement like:
int b = calculateSum(4, 6) / 2;
When this statement gets processed, the
calculateSum method will run and return its result (which will be the value 10 as an
int).
Thus the statement in effect is reduced to:
int b = 10 / 2;
Method parameters are also declarations. They declare a type of data received by the method, and also provide a name for each value so it can be used within the method.
Back to our method:
public int calculateSum(int num1, int num2) { int answer = num1 + num2; return answer; }
num1and
num2.
num1will be the first value given to the method,
num2will be the second.
The variable scope rules are similar to those in C++.
Variables can be declared at any point in your code, not just at the top of a block:
Variables declared within a set of curly braces cease to exist after the closing brace has been reached (it is said that they go out of scope); therefore, local variables exist only within that method.
Variables can be declared in the control portion of a
for loop, and will exist for the duration of the loop
Parameters to a method are local variables within that method
It is legal to use the same variable name in different scopes, as long as the two scopes have no irresolvable conflicts. Some explanation:
public class MethodExample { public static void sayHello() { System.out.println("Hello"); } public static void showNumber(int number) { System.out.println("The number is: " + number); } public static int calculateSum(int num1, int num2) { int answer = num1 + num2; return answer; } public static void main(String[] args) { sayHello(); showNumber(5); int b = calculateSum(4, 6); System.out.println("The sum of 4 and 6 is:" + b); b = calculateSum(4, 6) / 2; System.out.println("That divided by 2 is: " + b); } }
We will cover the concept of
static elements later, but, for now, since
main is
static, the methods it calls must be
static as well
Calculator.
addthat accepts two
doubleparameters, adds them together, and returns the result - mark it as
publicand
static, and returning a
double.
subtract,
multiply, and
divide.
main, create three
doublevariables
a, and
b, initialized with values of your choice, and
c, which we can leave uninitialized.
aand
b, and accepting the returned value into
c, and printing all three values.
public class Calculator { public static void main(String[] args) { double a = 10.0, b = 20.0, c; c = add(a, b); System.out.println(a + " + " + b + " = " + c); c = subtract(a, b); System.out.println(a + " - " + b + " = " + c); c = multiply(a, b); System.out.println(a + " * " + b + " = " + c); c = divide(a, b); System.out.println(a + " / " + b + " = " + c); } public static double add(double x, double y) { return x + y; } public static double subtract(double x, double y) { return x - y; } public static double multiply(double x, double y) { return x * y; } public static double divide(double x, double y) { return x / y; } }
Java Objects → ← Java Introduction | https://www.webucator.com/tutorial/learn-java/java-basics.cfm | CC-MAIN-2015-18 | refinedweb | 1,690 | 51.99 |
#include <Asynch_IO.h>
#include <Asynch_IO.h>
Inheritance diagram for ACE_Asynch_Transmit_File::Result:
This class has all the information necessary for the <handler> to uniquiely identify the completion of the asynchronous transmit file.
[protected]
Constructor.
[protected, virtual]
Destructor.
Number of bytes per send requested at the start of the transmit file.
The number of bytes which were requested at the start of the asynchronous transmit file.
File from which the data is read.
Flags which were passed into transmit file.
Header and trailer data associated with this transmit file.
Get the implementation class.
Reimplemented from ACE_Asynch_Result.
Socket used for transmitting the file.
[friend]
The concrete implementation result classes only construct this class.
The implementation class. | http://www.theaceorb.com/1.4a/doxygen/ace/classACE__Asynch__Transmit__File_1_1Result.html | CC-MAIN-2017-51 | refinedweb | 113 | 54.39 |
Updated 21 July 2021
Important notice concerning The Open Group Exam testing impacted by COVID-19 (coronavirus):
In response to the COVID-19 (coronavirus) outbreak, Pearson VUE, who provides The Open Group testing service, is adjusting its test center operations in accordance with advice from government and local authorities. Please check below to view the country-by-country information in advance of your appointment to prepare for your exam experience. Please note that as an alternative you can take your exam remotely using OnVUE online proctored delivery.
Country-by-country testing guidance
Visit for full details of country-by-country information.
Advice for Impacted Candidates
Testing candidates with cancelled exams will either receive a refund (if paid to Pearson VUE) or if booked with an exam voucher please contact The Open Group for assistance.
As an alternative to traveling to a test center, most of The Open Group certification exams are available to take remotely with OnVUE Online Proctoring from Pearson VUE (more details...)
- Q: Why has my exam been moved by Pearson VUE to a location saying in country but "No city available" ?
- A. Due to the continued concern around the COVID-19 outbreak, Pearson VUE has had to suspend exam deliveries at the test centre where you are currently scheduled in accordance with guidance from health and government organizations. They have moved your exam. If you booked your exam using an exam voucher and that has expired please contact The Open Group for assistance.
- Q: How will I know if my exam is canceled?
- A: You will receive an email cancellation notice from Pearson VUE and you will either receive a refund (if paid to Pearson VUE) or if booked with an exam voucher you can contact The Open Group for a voucher replacement. You can also log in to your Pearson VUE account to see if you can still see your upcoming exam appointment. According to Pearson VUE, if you are still able to see your upcoming exam appointment, please expect your exam to go ahead as planned, but with additional health and safety measures in place.
See also the Pearson VUE FAQs about exam cancellations due to Covid-19.
- Q: Can I reschedule my exam at this time?
- A: Yes. You should attempt to reschedule your exam through your online Pearson VUE account. The Pearson VUE system will only allow you to book exams on dates that will be available for testing. If you have an exam voucher that is due to expire soon, then you should contact The Open Group for assistance.
- Q: How can I contact The Open Group for assistance?
- Please raise a helpdesk ticket in The Open Group Help Center - login using your account with The Open Group that was used for your exam registration, select the Certification and Accreditation Category, and the specific program. Our team will need details of the exam name, voucher code, and expiry date. Please note that rescheduling and cancelations are managed through your Pearson VUE account.
Things you can do if you are taking an exam at a test center:
Please note: Face masks may be required while testing at a Pearson VUE-owned test center. More information»
- Wash your hands upon arrival to the test center.
- Utilize hand sanitizer upon entering the testing room.
- Tissues will be offered as you enter the testing room. Per the World Health Organization, please cover your nose and mouth in case of sneezing or coughing.
- Reschedule your testing appointment if you are unwell and exhibiting symptoms such as fever and/or respiratory difficulties.
As efforts to control the COVID-19 outbreak carry on, we will continue to monitor the global situation and will act upon any new guidance provided by local authorities and government agencies as they develop.
Courses delivered virtually and e-learning courses may be a good solution during the COVID-19 restrictions; the delivery methods applicable to a course are listed on the conformance declaration included on the register.. It may take longer if the results have been flagged for audit. You will not be visible in the Directory of Certified Individuals until you receive this email from The Open Group AND log in to the certification system to complete the steps to be certified.
- Q: My score report is pending, what does this mean?
- A: If you are attending a test center you will receive notification of your pass or fail status within a few minutes of completing your exam in the form of a printed score report. For all delivery methods, you can obtain your score reports from within your Pearson VUE testing account.
Occasionally at a test center,: My score report says Delivery Successful, what does this mean?
- A: With OnVUE delivery it can take some time for the full status to reach the systems so this status may appear. If the score report is available you will be able to see whether you passed or failed, and the status will be reflected in the summary usually within 24 hours.
- Q: What are the exam requirements?
- A: The requirements depend on the program. See the Examinations page for more information.
- Q: What exams are available at Pearson VUE?
- A:All of The Open Group examinations are available at Pearson VUE test centers (*):
- ArchiMate® 2 Part 1 Exam
- ArchiMate® 2 Part 2 Exam
- ArchiMate® 2 Combined Part 1 and Part 2 Exam
- ArchiMate® 3 Part 1 Exam
- ArchiMate® 3 Part 2 Exam
- DPBoK™ Part 1 Exam
- IT4IT™ Part 1 Exam
- Open FAIR™ Part 1 Exam
- TOGAF® 9 Part 1 Exam (all languages: English, Brazilian Portuguese, French, Latin American Spanish, Simplified Chinese)
- TOGAF® 9 Part 2 Exam (all languages: English, Brazilian Portuguese, French, Latin American Spanish, Simplified Chinese)
- TOGAF® 9 Combined Part 1 and Part 2 Exam (English and Simplified Chinese)
- TOGAF Business Architecture Part 1
(*) Most examinations are also available to take at home. See here.
- Q. What are the examination fees?
- A. See the Examination fees information page.
- Q. Can I take my exam remotely without traveling to a test center?
- A. Yes, the most popular exams can be taken remotely at home or at the office with OnVUE Online Proctoring from Pearson VUE.
- THE.
- Q: Why is the exam appointment time longer than the exam time?
- A: The appointment time includes the time needed to complete registration and check-in procedures,. You should attempt to reschedule your exam through your online Pearson VUE account. The system will only allow you to book exams on dates that will be available for testing..
- Q: I took my examination and when I look at status it says "We’re sorry but you missed your check-in window making this exam unavailable for delivery.". What does this mean?
- A: This appears to be an issue with the Pearson VUE booking system, when viewing status after the appointment time. If you examine the detail under Status, it should give you the status. If it says Delivery Successful, you can view your score report for more information (available from the top level in the Pearson VUE login, on the right under My Account).. See also the tutorial here (pdf).
- Q. My credit card is being declined, what should I do?
- A. It is .
It is also possible you are in a country where Pearson VUE does not accept payment by credit card:
Pearson VUE does not accept credit card payments in the following countries: Afghanistan, Bangladesh, Benin, Cameroon, Gambia, Ghana, Lebanon, Nigeria, Pakistan, Senegal, Tanzania, Togo, and Uganda. Candidates in these countries may arrange for payment directly with the Test Center where they plan to test.. Connecting to your Pearson VUE will refresh your profile details if you have updated them.
If you take no action, then you will fail the ID requirements, and have your online exam be revoked, or be turned away from the test center. The ID requirements are clearly stated and provided to you in the email confirmation. In brief the test will not be delivered without the appropriate forms of identification and the Pearson VUE Administrators have the right to refuse admission to the exam if they are unable to properly identify you. Your exam slot will then be classified as a no-show, and you would need to make a new booking for which payment would be required.
- Q. I have an accented character in my name. When transferred to Pearson VUE this appears as a question mark. What can I do?
- A.There is a mismatch with character handling in the Pearson VUE side. As a workaround you should update your profile in The Open Group system to put the closest non-accented characters. To update your profile please visit. If you need assistance you can contact The Open Group helpdesk for assistance.
-.
- Q. I am trying to register for two consecutive exams for an OnVUE (online proctored) exam, but get returned to The Open Group site with an error return (ERROR) before the available dates page is displayed. What should I do?
- A. This is a known issue with the Pearson VUE registration system, that has been reported to them. The workaround is to book the exams separately.
For additional registration information see the Pearson VUE Specific Q&As below.
OnVUE Delivery (Remote exams)
When booking for OnVUE delivery, please check your appointment time, noting that in the online booking system 12:00 AM is midnight
- Q. What is OnVUE delivery?
- A. OnVUE online proctored exams allow you to conveniently take an exam in the comfort of your home or office while being monitored by an offsite proctor. All communication with the proctor is done in English.
- Q. Will OnVUE delivery work for me?
- A. OnVUE delivery is not available in China, and South Korea. To check your connection and device are suitable, you can run the system test available here.
- Q. What do I need to know about OnVUE delivery?
- Your computer needs a webcam, microphone, and sufficient internet speed to satisfy system requirements
- These exams are taken seriously, so please prepare your room as if it was a live test center
- The exam must be taken in a walled room, with a closed door and without distractions; this also means that if there are others in your home/office, they must not interrupt you during your exam
- Do not leave the room during your exam; your exam will be terminated
- To secure the integrity of these exams, no breaks will be allowed during the entirety of your exam
- Q. What exams are available to take with OnVUE delivery?
- A. See for the list of available exams.
- Q. How do I find my Purchased Online Exams screen?
- To find to the Purchased Online Exams screen , the simplest route is from:
Select option 2 - login. This will take you to
Click on the Goto Pearson VUE link (login). Click proceed to Pearson VUE. This will take you to your home screen at Pearson VUE where you will find the screen.
- Q. How do I register to take an OnVUE Online Proctored exam?
- A. See the registration tutorial (pdf).
- Q. How do I get started with registering for an OnVUE delivered exam?
- A. Visit the Pearson VUE OnVUE page
- Q. How do I find out the systems requirements for registering for an OnVUE delivered exam?
- A. Visit the Pearson VUE OnVUE page for detailed system requirements. These include the ability to run a system test to check suitability.
- Q. What are the policies for taking an OnVUE delivered exam?
- A. Visit the Pearson VUE OnVUE page for details on requirements related to your workspace where you will be taking the exam, the type of identification you will be required to present, etc.
- Q. Can I register for two consecutive exams for OnVUE delivery?
- A. No, OnVUE does not support consecutive delivery and you may get an error when trying to register. If you want to book more than one exam, they must be booked separately.
- Q. Is OnVUE delivery available worldwide?
- A. No, OnVUE delivered exams are not available in the following countries: China, Japan, Slovenia, South Korea.
- Q. If I have an exam booked for a test center, how can I change it to an OnVUE Online Proctored exam?
- A. You will need to first cancel the existing appointment and then rebook. This can be done through your online account or by contacting Pearson VUE Support.
- Q. I am failing the OnVUE system test. How can I get help?
- A. Pearson VUE provide and support the OnVUE service and can be contacted at.
- Q. I had a problem during delivery of the OnVUE exam, how can I get help?
- Pearson VUE provide and support the OnVUE service and should be contacted first for all matters related to the service — see. If your problem could not be resolved then you can also contact The Open Group helpdesk see here, please note that The Open Group are unable to resolve matters related to running exams via OnVUE delivery.
- Q. How do I reschedule an OnVUE examination and/or change the delivery mode to take the examination at a test center?
- A. You will need to cancel the examination through your account at Pearson VUE (login here), and then register for another exam. Please note you need to cancel at least 48 hours in advance of the exam booking. Please note that all registrations, cancellations, and rescheduling are managed by The Open Group examination provider, Pearson VUE.
For additional information on OnVUE delivery see here.
Completing Certification
For certification credentials, such as TOGAF Business Architecture Level 1, see here.
- Q: What do I need to do after passing an exam to receive a certificate and Open Badge?
- A: The next steps depend on the program type. For certification credentials, such as TOGAF Business Architecture Level 1, you complete certification by accepting an Open Badge, see here. For other certifications you must first enter into a trademark license agreement to complete the certification (see The Open Group Certification for People: Certification Policy for Examination-Based Programs), and an Open Badge follows within 10 working days after completing. This may take longer if thhere is need to include an audit of the results. a.
- Q: How can I share my certification on my LinkedIn profile and other social media platforms?
- A: The simplest way is via the Open Badge that issued with each certification. See here.
Completing a Certification Credential
This applies to certification credentials, such as TOGAF Business Architecture Level 1
- Q: Why is completing certification credentials different to other certifications?
- A: Certification credentials, such as TOGAF Business Architecture Level 1, are issued directly by The Open Group Partner— Credly Acclaim as a digitally verifiable credential. See the Open Badges FAQs here.
- Q: How do I complete my certification and get a certificate?
- A: After your exam result is received at The Open Group, if you have not opted into The Open Group Badges program you will be invited to opt-in. Once opted in an Open Badge will be issued to you. You will need to create an account with Credly Acclaim in order to receive the badge and certification. You are able to download a pdf of the certificate from your Credly Acclaim account
- Q: How do I download my certificate?
- A: To complete certification and print your certificate, you need to: 1. Login to the Acclaim account, select the badge , then click on Share, then 2. Select the print icon, and that will let you download the certificate as a pdf. See this video.
- Q: How do I create a Credly Acclaim account?
- A: Visit and select Create Account.See this video to learn how to create an Acclaim account, accept and share your certification badges.. What is an Open Badge?
- A. It is a digitally verifiable credential. It is a way for you to share information about your certifications in a digitally secure and verifiable manner, including options to respect your privacy. The Open Group badging partner is Credly Acclaim.
- Q. How do I manage and share my Open Badge for my certification?
- The Credly Acclaim platform is designed to allow you to easily and efficiently manage and share your professional achievements, including certifications from The Open Group. See this video to learn how to create an Acclaim account, accept and share your certification badges.
- Q: Will I get an Open Badge with my certification?
- A. If you choose to opt-in to The Open Group Open Badges program then you can receive one. See for details. If you have completed a certification credential, such as TOGAF Business Architecture Level 1, then the certification is issued directly via The Open Group badging partner — Credly Acclaim.
-. This depends on the program. For exam-based certifications, badges are typically issued within 1 business day of certification being completed. For Open Professions certifications it can take up to 10 business days. See for details.
- Q. Can I print a certificate with my Open Badge?
- A. Yes from within your Credly Acclaim account, the option to share includes a print to pdf function.
- Q. How can I share my certification on my LinkedIn profile?
- From within your Credly Acclaim account, go to the Share Badge page, click the LinkedIn icon, and follow the instructions. See also this video.
- Q. Can i attach my certification to my email signature?
- A. Yes, adding a hyperlinked certification badge image to your email signature is a great way to make sure your professional network is aware of your certification. 1. Login to your Credly Acclaim account, select the badge you want. 2.Select the share button at the top of the page. 3. Select the tab with the download icon, and use the sliding scale to select the appropriate size for your image download. (We recommend around 150x150 pixels, in this case.) Click the "Download Image" button. 4. Select the tab with the link icon, and click the "Copy" button to copy the Badge URL your clipboard. You'll need this to hyperlink your downloaded image.
Certification Credentials
- Q. What is a certification credential?
- A. The Open Group Certification program includes certification credentials for small amounts of learning (3 hours upwards), effectively micro-certifications. They lead to the award of a digitally verifiable credential for the certification, known as an Open Badge. Certification credentials are being developed for a number of topic areas. Initially, knowledge-based credentials are being developed. In the future it will be possible to earn additional certifications for collections of related sets of certification credentials.
- Q. What types of certification credentials are there?
- A. There are currently two types:
- Refreshed Knowledge (e.g., TOGAF Essentials 2018)
- Specializations (e.g., TOGAF Business Architecture Level 1)
- Q. How long will it be before I receive my certification and an Open Badge for a certification credential?
- A. Certification is awared and an Open Badge issued within 6 business days of the pass result for a credential being received. See for details.
- Q. Do I receive a certificate.
- Q: Are there any job postings for certified individuals?
- A: Yes Credly, our badging partner, has Labor Market Insights and job postings both for Certified Individuals, as well as specific skills such as Enterprise Architecture and job openings mentioning the TOGAF framework. to reduce the cost to the same as the TOGAF 9 Combined Part 1 and Part 2 exam. changed to 3.1 in May 2020..
- Q: How do the new 2020 versions of the O-RA and O-RT standard relate to the current Open FAIR certification program?
- A. The current version of the certification program aligns with the 2014 versions of the standard. A revised version of the program is expected to be developed in 2021. Further details will be announced at that time. exam appointment. / ArchiMate / IT4IT / DPBoK / Open FAIR Certification need to be renewed?
- A. There is no renewal required once you have obtained TOGAF 9, ArchiMate 2, ArchiMate 3, IT4IT, TOGAF Business Architecture, DPB with Pearson VUE ?
- A. Visit the Available Exams page to learn which exams are available with Pearson VUE.
- Q. How do I locate a Pearson VUE test center?
- A. You may search for Pearson VUE test centers near you by specifying an address, city, or postal code.
- Q. Can I take an exam remotely at home or in my office ?
- A. Most of The Open Group Certification exams are also. After a successful reschedule you will receive an email confirmation and also it will show in your account.
-. After a successful cancellation you will receive an email confirmation and also it will show in your account.
-?
- A. Visit the Take Exam page to learn how to register and login to schedule an exam.
- Q. What do I need to know about taking an exam at Pearson VUE?
- A. Admission Policy (for test centers)
We ask that you arrive at the test center.
Identification (ID) Requirements
You will need to bring two forms of identification to the test center. Carefully review the ID requirements prior to your exam appointment using this link. The test will not be delivered without the appropriate forms of identification. In addition to the current identification and admission policy, candidates who are taking a proctored exam will be photographed. with Pearson VUE?
- A. For all exams see the generic advice sheet: Advice for Candidates taking Exams with Pearson VUE
For more help, see The Open Group Help Center. | https://www.opengroup.org/certifications/faqs | CC-MAIN-2021-31 | refinedweb | 3,571 | 63.39 |
Here are the steps I recommend for getting started with python on a Mac (OS X), particularly if you are fairly new to the language.
- The Mac comes with python installed, and you can run this directly from the terminal application with the command “python”. However there is a very nice python interpreter called the “ipython notebook” which I strongly recommend using too. Installation instructions are available here - specifically, I downloaded Enpackage Canopy and typed two commands into the terminal. You should now be able to get an ipython notebook running in your internet browser with the terminal command:
cd somewhere/sensible/ ipython notebook --pylab=inline
The last part of this means that plots get drawn inside the notebook, which is handy. If you forget to add that, you can type into the notebook itself:
%pylab inline.
Note you use shift-Enter to run all the python commands in a cell.
- Install pip. This lets you easily download python packages and will be very handy later. This is easy – from the terminal type:
sudo easy_install pip
- More advanced users may want to install virtualenv, so that different projects you work on can use different versions of packages. If you’re planning on putting any of your code in production, this is a must. But if you’re just getting started, ignore it for now.
- Advanced users will also want to install git so you can incrementally save your own versions of code. If you’re just starting out, leave this for later too.
OK, now let’s dive in the deep end by loading some financial data from Quandl, then manipulating it with Pandas and plotting it with matplotlib. You’ll need Pandas and the Quandl package, which you can get by typing into the terminal:
pip install pandas pip install Quandl
Now in your ipython notebook type (I recommend doing each group of statements in its own cell, so that you can run them separately; remember it’s shift-enter to run the statements):
import numpy import pandas import Quandl assets = ['OFDP.ALUMINIUM_21.3', 'OFDP.COPPER_6.3', 'OFDP.LEAD_31.3', 'OFDP.GOLD_2.3', 'OFDP.ZINC_26.3'] data = Quandl.get(assets) data.head() data['2012':].plot()
This link gives ways you can develop the plot further.
To give an example of how to manipulate the data, you could try:
# show recent daily returns, normalised by asset volatility (ie. z-scores) data = data.sort_index() # ensure oldest comes first returns = (data/data.shift(1)) log_returns = numpy.log(returns) vols = pandas.ewmstd(log_returns,span=180) # daily vol, exp weighted moving avg z = (returns-1)/vols # calc z-scores z[z>50] = numpy.nan # remove very bad data z[z<-50] = numpy.nan z.tail() # take a look at the most recent z-scores
That’s a very quick introduction to installing and using python on the Mac. I hope it’s helpful!
If you want more info about writing in Python itself, this link looks like a comprehensive site.
Let me know if you have any comments or improvements. | http://racingtadpole.com/blog/get-started-python-on-mac/ | CC-MAIN-2019-43 | refinedweb | 506 | 63.39 |
Related link:
My friend Marco emailed this link to “Nifty Javascript….”
Related link:
My friend Marco emailed this link to “Nifty Javascript….”
Trey?
Related).
Related link:
Where does your unit test go?
Test Driven Development and Test First Development have a number of benefits. It is more of an act of design than an act of verification as I have discussed in a three part series at.
Where should the tests go? While writing test cases, you may have to access not only the public members, but also internal or package friendly members as well. In Java, you would want to write your test cases in the same package. In the case of .NET, you would put them in the same project. If you do not want to deploy the test cases, you can exclude them from your release build.
What if you need to test a private method or property of a class? First question to ask is, why would you want to test such methods or properties? Generally speaking, may be not. However, say I am writing an Order class and as part of its checkout method, I need to charge a credit card. The method to charge the credit card most likely is going to be private as it is an implementation and not something that the Order class would expose as public.
Why test it? You would certainly want to make sure you have handled the failure cases well. What if the card was invalid, or the charge did not go though or even you could not communicate with the service that authorized the credit card.
How do you test private methods in this case? Before I get into that, let me say that I am not suggesting that you write all your test cases like this. I would use this as an exception than a norm.
Why not write your test case that needs to test your private methods as an inner class in Java and nested class in .NET. Let’s try that.
Here is the .NET example:
public class Order { private string Charge(Card theCard, double amount) { //... return "chargeCode..."; } [TestFixture] public class OrderChargeTest { private Order theOrder; private Card theCard; private double AMOUNT1 = 121.12; [SetUp] public void SetUp() { theOrder = new Order(); theCard = new Card(...); } public void TestCharge() { theOrder.Charge(theCard, AMOUNT1); } } }
You can write more test to make sure the code behaves well for failure of the Charge.
Here is the Java code that does the same thing as above:
public class Order { private String Charge(Card theCard, double amount) { //... return "chargeCode..."; } public class OrderChargeTest extends TestCase { private Order theOrder; private Card theCard; private double AMOUNT1 = 121.12; public void setUp() { theOrder = new Order(); theCard = new Card(...); } public void TestCharge() { theOrder.Charge(theCard, AMOUNT1); } } }
In addition, I have a TestIt class as shown below:
public class TestIt { public static void main(String[] args) { junit.swingui.TestRunner.run(Order.OrderChargeTest.class); } }
When I run JUnit, I get the following error:
junit.framework.AssertionFailedError: Class Order$OrderChargeTest has no public constructor TestCase(String name) or TestCase()
The reason for this error is inner classes in Java are special. The constructor of the inner class is synthesized with a reference to the host class (the class in which it is contained). As a result, JUnit is complaining that it could not find a constructor which takes no arguments. Of the four types of inner classes (regular, local, anonymous and static) only the static inner class’ constructor is not synthesized with a reference to the host class. In Java, we should use static inner class instead of regular inner class here.
Modifying the code as
public class Order { private String Charge(Card theCard, double amount) { //... return "chargeCode..."; } public static class OrderChargeTest extends TestCase { private Order theOrder; private Card theCard; private double AMOUNT1 = 121.12; public void setUp() { theOrder = new Order(); theCard = new Card(...); } public void TestCharge() { theOrder.Charge(theCard, AMOUNT1); } } }
takes care of the problem.
On rare occasions, writing your test cases as nested classes in .NET or static inner classes in Java may come in handy. One down side is it is hard to exclude these from the release build. In the next version of .NET, with the introduction of partial classes, that should not be a problem.
What are your thoughts on TDD/TFC and where tests should go
Related link:
I can’t believe I’m linking to a Washington Times story (this wouldn’t be my paper of choice), but Former CIA Director George Tenet sounded off on the internet. Read the article, especially this excerpt:.
Mr. Tenet called for industry to lead the way by “establishing and enforcing” security standards. Products need to be delivered to government and private-sector customers “with a new level of security and risk management already built in.”
Well, the last paragraph is a nobrainer, sure, everything should be “secure by default”. Although, I have the feeling by “risk-management” he means, “Big Brother”-ish Digital Rights Management hardware. Those first two statements - I couldn’t disagree more. First, openness and transparency is the last thing this country has going for it. Second, the Internet has just started, and the WWW is nothing compared to what we’ll be doing in 20 years. Stifling innovation with government intervention at this point in the development of technology would be a huge mistake.
Start talking about regulating “who” can be “on the World Wide Web”? To me this is code for, “require all software publishers to be licensed by the federal government”. Say…..wouldn’t Microsoft love it if the Apache Software Foundation, or the Free Software Foundation had to work with some outrageous federal regulatory agency. Maybe we could name it something like, “Federal Information Security Office”. I’m thinking they would do something like making the lower levels of the TCP/IP stack classified and only hand out the specs to huge corporations with lobbyist. I can’t wait.
Also notice how Tenet boils the internet’s open architecture down to Web surfing. As if, “Web surfing” is the apex of this technology. Don’t let the dramatic changes we’ve all experienced during the past three decades fool you. All we’ve gained from telecommunications and computing is the ability to “surf” to the “Web”. The WWW may be the most visible benefit of the “Internet”, but the web alone didn’t do the trick. Without open access to the internet, the web would have been an overregulated, underused mess. No one has to ask the government to set up a web site. No one needs to talk to the authorities to publish a book, and no one needs to give a librarian a good reason why they want to read a Chemistry book.
I’ve got to say that the facts are in direct opposition to his remarks. Openness isn’t the problem. If anything is the problem, it is the danger posed to our security by proprietary software and closed standards. There is no public scrutiny for closed source software. If we reduce the transparency of our standards and software, we will reduce our security tenfold. Open source welcomes public scrutiny - “Find the bugs and we’ll fix them”.
Tenet is no stranger to being wrong. Or, has the Ministry of Truth started revising the past yet? Anyone read Orwell’s 1984 lately? That is a book we all need to read - again.
Lastly, Tenet misses the real danger - unresricted access to Gopher servers will destroy us. Gopher is like the Wild West. Being able to hyperlink to any other Gopher site in the world is our Achilles Heel.
Do you think “access to networks like the World Wide Web might need to be limited to those who can show they take security seriously”?
Related link:
Ken Coar (author of Apache Cookbook) assembled some mailing list statistics for every list hosted by the Apache Software Foundation.
One thing I noticed was that Jakarta’s commons-dev
is the second busiest mailing list at apache (second to tomcat-user). The health of a community has a lot to do with the activity (or more accurately the persistence of activity) on both a development and user mailing list. These stats are interesting because they show mailing list stats for healthy communities like the httpd project and commons-dev as well as stats for unhealthy communities like xindice.
From this page, you can see that commons-dev has 428 subscribers and averages 62 messages per day - cvs commits, bugzilla, jira, gump, and human messages. The commons-user list has 829 subscribers and averages around 12 messages a day. This is healthy, but it could be better.
On the other hand, the xindice-dev list has 284 subscribers (I am one of them), but only averages 0.63 messages per day. This means that of 284 people someone gets the itch to commit to cvs or send an email only once every two days. If you’ve been following xindice you will know that it is practically lifeless. But, the user mailing has almost twice the number of subscribers 492, and an even smaller average messages per day of 0.55. I brought this up once, only to have someone chide me for thinking that mailing list activity had anything to do with interest. But, the truth is, it does. If there isn’t a lively discussion on either the user or dev list, bugs are not being fixed and brainpower is not being spent on the project. That community is gone, and the people left are less than interested. Lot’s of people are watching xindice, but few are contributing. | http://www.oreillynet.com/onjava/blog/2004/12/ | crawl-001 | refinedweb | 1,613 | 65.01 |
I'm new at Java and I have a question.
I wrote this code.
{string isim = "Ali";boolean özne == true;if ( özne ){ System.out.println("Merhaba" + isim); }}}
Muz.java:5: error: ';' expected
boolean özne == true;
^
1 error
Use
= instead of
== to affect
true to your
boolean variable, and the correct spelling for the class string is
String.
You will also need to declare your class, I don't see it in your code snippet but in your case it should be something like that knowing that the name of your file is
Muz.java
public class Muz { public static void main(String[] args) { String isim = "Ali"; boolean özne = true; if ( özne ){ System.out.println("Merhaba" + isim); } } } | https://codedump.io/share/B5wRd35qlOW1/1/i-javac-my-program-on-console-but-it-didn39t-worklinux | CC-MAIN-2017-13 | refinedweb | 116 | 73.58 |
In my last article, Security in Angular: Part 1, you learned to create a set of Angular classes to support user authentication and authorization. You used these classes to log in a user and make menus and buttons visible and invisible. In this article, you’ll use a .NET Core Web API project to authenticate a user against a SQL Server table. You’ll return an authorization object by reading claim information from a claim table. You’ll also secure your Web API methods using the JSON Web Token (JWT) standard.
Part 1: Security in Angular: Part 1
Part 3: Security in Angular: Part 3
There are several steps you need to perform to secure your Web API methods. You’ll be guided through each of the following steps in this article:
- Download and set up a sample application and database.
- Create Entity Framework security classes.
- Create a class to authenticate users and return an authorization object.
- Create a security controller.
- Modify the Angular application to call a security controller.
- Add JSON Web Tokens to secure Web API calls.
- Create an HTTP interceptor.
Download the Starting Application
In the last article, all the data for users, products, and categories were in mock classes. For this article, I’ve provided you with a starting application that contains an ASP.NET Core Web API project to retrieve product and category data from Web API method calls. In this article, you build the Web API security classes to authenticate a user and return an authorization object to your Angular application.
Download the starting sample for this article from the CODE Magazine website, or from. Select "PDSA/Fairway Articles" from the Category drop-down, and then choose Security in Angular - Part 2. After you’ve downloaded the ZIP file, there are two folders within the ZIP entitled Start and End. Extract all of the files and folders within the Start folder to a folder somewhere on your hard drive. You can then follow along with this article to build all of the Web APIs to secure your Angular application.
Load the Visual Studio Code Workspace
After extracting the Start folder from the ZIP file, double-click on the PTCApp.code-workspace file to load the two projects in this application. If you double-click on this workspace file, the solution in addition to purpose of this article, I’ve simplified this table to only a unique ID (UserId), the name for the log in (UserName), and the Password for the user, as shown in Figure 3. Please note that I’m using a plain-text password in the sample for this application. In a production application, this password would be either encrypted or hashed.
User Claim Table
In the UserClaim table, there are four fields: ClaimId, UserId, ClaimType, and ClaimValue, (as shown in Figure 4). The ClaimId is a unique identifier for the claim record. The UserId is a foreign key relation to the User table. The value in the ClaimType field needs to match the exact property name you create in the AppUserAuth class from Angular, and the one you’re going to create in C# in the next section of this article. The value in the ClaimValue should be a true value for any ClaimType you enter for that user.
Don’t enter a record for a specific user and claim type if you don’t wish to give the user that claim. For example, the CanAddProduct property in the authorization object should be set to false for the user BJones. Therefore, don’t enter a record in the UserClaim table for BJones with a ClaimType equal to CanAddProduct. Later in this article, you’ll learn how this process works.
Create C# Security Classes
In the Security in Angular - Part 1 article, you created Angular classes to represent a user and a user authorization object with properties to bind to. Create these same classes using C# within the PtcApi project. You’re going to build the C# classes with the same class and property names as those you created in TypeScript.
AppUser Class
The AppUser class is an Entity Framework class that represents a single record you retrieve from the User table. For each property in the User table, create a corresponding property with the appropriate data annotations. Right mouse-click on the Model folder and add a new file named AppUser.cs. Add the code shown in Listing 1 into this new file.
The Using statements in this file are used to supply the appropriate data annotations for the Entity Framework. The [Table] attribute specifies the name of the table this class maps to: User. The User table is located in the database schema named Security, so pass the Schema property to this attribute as well.
The [Required] attribute should be added to all fields, because all fields in the User table are marked as not allowing null values. The [StringLength] attribute can be added to the UserName and Password fields in case you want to perform some validation on the data prior to inserting or updating. This article won't cover this, but I like adding appropriate data annotations to my properties.
Create AppUserClaim Class
The AppUserClaim class is an Entity Framework class that represents a single record you retrieve from the UserClaim table. For each property in the UserClaim table, create a corresponding property with the appropriate data annotations. Right mouse-click on the Model folder and add a new file named AppUserClaim.cs. Add the code shown in Listing 2.
The Using statements and attributes used are similar to what you used in the AppUser class. The [Table] attribute specifies the UserClaim table, located in the Security schema. All of the other attributes attached to the properties are self-explanatory.
Modify PtcDbContext Class
When using the Entity Framework, you typically create a class that inherits from the Entity Framework's DbContext class. In the PtcApi project, this class is named PtcDbContext. For each of the EF classes you create, add a collection property of the type DbSet<T> to this DbContext class. Open the PtcDbContext.cs file in the Model folder and add two new properties for the AppUser and AppUserClaim classes, as shown in the code snippet below.
public DbSet<AppUser> Users { get; set; } public DbSet<AppUserClaim> Claims { get; set; }
Once you have these two properties created, you can retrieve users and claims from them. You may also use these properties to add, edit, and delete records from each table.
Create Authorization Class
If you remember from Part 1 of this article series, you created a user authorization class in TypeScript that contained properties to make menus and buttons visible and invisible. You need to create this same class in C# so it may be returned from a Web API method call and mapped to the TypeScript class in Angular. Right mouse-click on the Model folder and add a new file named AppUserAuth.cs. Add the code shown in Listing 3 into this file.
Create Security Manager Class
There are several steps that must be accomplished to authenticate a user and create an authorization object to send back to Angular. Instead of writing all of that code within a controller, build a class named SecurityManager for that logic. The controller may then create an instance of that class and call one method to authenticate the user and to retrieve an authorization object. Right mouse-click on the Model folder and add a new file named SecurityManager.cs. Add the code shown in Listing 4 into this file.
The AuthenticateUser() Method
The AuthenticateUser() method is the only method exposed from the SecurityManager class. The security controller you’re going to create in the next section of this article accepts an AppUser object from the Angular application via a Web API call. You’re going to pass this AppUser object to the AuthenticateUser() method.
The AuthenticateUser() method creates an instance of a PtcDbContext class. Once this object is created, the Users property is accessed and a where filter is applied to locate a user in the User table where the UserName field matches the UserName property passed in from the Angular application. In addition, the password must match the value in the User table as well.
If a valid user is located in the User table, the AppUser object retrieved from the Entity Framework is passed on to the BuildUserAuthObject() method. It’s in this method that the user authorization object is created.
The BuildUserAuth() Method
This method is responsible for building the user authorization object that’s sent back to Angular with all the appropriate Boolean properties set. The first thing this method does is create a new AppUserAuth object. The UserName property is set with the authenticated user name passed in. The IsAuthenticated property is set to true to signify that the user is valid. The BearerToken property is going to be set to a random GUID for now. Later in this article, you’ll fill this in with a real bearer token generated using the JSON Web Token system.
Next, all the claims in the UserClaim table for this user are gathered by calling a method named GetUserClaims(). Once you have that list of claims, you loop through each claim one-by-one. Each time through the loop, use reflection on the AppUserAuth object to attempt to access the property name that’s in the ClaimType property read in from the UserClaim table. This is why I mentioned earlier that the names you add to the UserClaim table must match the properties in the AppUserAuth class, as it allows you to use .NET reflection to set each property value to the value contained in the ClaimValue field.
Once this method has looped through all claims for the authenticated user, the AppUserAuth properties have either been set to a true value, or, if the property didn’t exist in the UserClaim table, then the default value of false is in the other properties.
NOTE: This method of setting properties is fine when you don’t have a lot of security in your Angular application. For an application with many security claims, you should return the list of claims as part of the user authorization object. Of course, once you have a list of claims, and not individual properties, you can't take advantage of binding properties to a menu or a button. Instead, you‘ll have to create a custom structural directive in Angular to make menus and buttons visible and invisible. Creating this type of security will be the topic of discussion in the third part of this series on Angular security.
The GetUserClaims() Method
The GetUserClaims() method is where you retrieve a list of claims for the user who’s been authenticated. In this method, you create a new instance of the PtcDbContext class. Access the Claims property and apply a Where filter to only retrieve those claims that match the UserId property from the authenticated user to those records in the UserClaim table that have that same UserId value. The list of claims is returned from this method and used in the BuildUserAuth() method to set the appropriate properties in the user authorization object.
Add Security Controller
It’s now time to build the security controller that the Angular application calls. Angular passes the user credentials in an AppUser object to the Web API method. The method returns an AppUserAuth object with the appropriate properties set by calling the AuthenticateUser() method. Right mouse-click on the Controllers folder and add a new file named SecurityController.cs. Add the code shown in Listing 5 into this file.
The Login() Method
The Login() method accepts an AppUser object from the Angular application. Next, it creates an instance of the SecurityManager and passes the AppUser object to the AuthenticateUser() method. The AppUserAuth object returned from the AuthenticateUser() method has the IsAuthenticated property set to a true value if the user has been validated in the User table, and the security properties have been set.
If the user is authenticated, call the StatusCode() method passing in an enumeration to specify a status code of 200 (OK), and passing in the user authorization object. This method generates an IActionResult object to tell Angular that the call to the Login() method succeeded and that the resulting data is in the payload passed back.
If the user isn’t authenticated, pass in an enumeration of 404 (NotFound) to the StatusCode() method, and a string specifying that the user name and password combination wasn’t valid. When this code is returned to Angular, it signifies an error condition, and your Angular code needs to handle this, as appropriate.
Call the Web API from Angular
It’s now time to replace the mock calls for authentication and authorization in Angular with calls to the new Web API Login() method. You need to add the HttpClient, HttpHeaders, and the tap classes to your SecurityService class. Go back to the PTC project and open the security.service.ts file located in the \src\app\security folder and add the following import statements.
import {HttpClient, HttpHeaders} from '@angular/common/http'; import { tap } from 'rxjs/operators/tap';
Add two constants just under the import statements. The first constant is the location of the Web API controller. The second constant holds header options required by the HttpClient when POSTing data to a Web API call. You’re going to use an HTTP POST to send the AppUser object containing the user name and password to the Login() method.
const API_URL = ""; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
Have Angular inject the HttpClient service into your security service class so you can make the HTTP call to the Login() method. Dependency injection is used extensively throughout Angular to provide services such as HttpClient to different components. The HttpClientModule has already been imported in the AppModule class. This module must always be imported to allow components to use the HttpClient service.
constructor(private http: HttpClient) { }
Modify the Login() Method
Within the security service class, you need to remove the hard-coded logic in the login() method. Modify the login() method as shown in Listing 6 to call the Login() method in the SecurityController class. If valid data is returned from this call, the pipe() method is used to pass that data to the tap() method. Within the tap() method, assign the data returned to the securityObject property.
It’s very important that you don't use the equal sign to assign to the securityObject property. If you do, bound references to the securityObject are wiped out, and your menus and other UI elements bound to properties on the securityObject no longer work. Instead, use the Object.assign() method to copy the data from one object to another.
It’s very important that you don't use the equal sign to assign to the securityObject property.
Within the tap() method, store the bearer token into local storage. The reason for storing this token is used when building an HTTP Interceptor class. You’ll learn to create this class a little later in this article.
Modify the Login Component
Because it’s possible that the Web API may return a status code of 404 (not found), be sure to handle this code so you can display the Invalid User Name/Password error message to your user. Open thelogin.component.ts file and add the error block in the subscribe() method. The login HTML contains a Bootstrap alert that has the words Invalid User Name/Password. in a <p> tag. This alert only shows up if the securityObject is not null and the isAuthenticated property is set to false. In the error block, assign a new instance of the AppUserAuth class to the securityObject property.
login() { this.securityService.login(this.user) .subscribe(resp => { this.securityObject = resp; if (this.returnUrl) { this.router .navigateByUrl(this.returnUrl); } }, () => { // Display error message this.securityObject = new AppUserAuth(); }); }
Try It Out
Save all of your changes and make sure that the Web API project and the Angular project is running. Go to the browser and attempt to log in using either "psheriff" or "bjones" with a password of "P@ssw0rd". If you’ve done everything correctly, the Web API is now being called for authenticating the user name and password. Try logging in with an invalid login ID and password to make sure the error handling is working.
Remove Mock Login File
Now that you’re retrieving data from a Web API call and not the mock data, you can remove \security\login-mocks.ts file. Once this file is removed, open the \security\security.service.ts file and remove the import statement for the login-mocks file.
Authorizing Access to the Web API Call
Now that you’ve created these Web API calls, you need to ensure that only those applications authorized to call your APIs can do so. In .NET, use the [Authorize] attribute to secure a controller class, or individual methods within Token (JWT), just to mention a few. In this article, you’re going to use JSON Web Token.
Secure the Product Get() Method
To show you what happens when you apply the [Authorize] attribute to a method, open the ProductController.cs file and add the [Authorize] attribute to the Get() method, as shown in the code snippet below. You need to add a Using statement to use the [Authorize] attribute. The Using statement is using Microsoft.AspNetCore.Authorization.
[HttpGet] [Authorize] public IActionResult Get() { // REST OF THE CODE }
Try It Out
If you haven’t already done so, stop the PtcApi Web API project from running. Save your changes and run the PtcApi project again. Log in as "psheriff" and click on the Products menu. No product data is displayed because you attempted to call a method that was secured with the [Authorize] attribute. Press the F12 key to bring up the developer tools and you should see something that looks like Figure 5.
Notice that you’re getting a status code of 500 instead of a 401 (Unauthorized) or 403 (Forbidden). The reason is that you haven’t registered an authentication service with .NET Core so the [Authorize] attribute doesn’t get any data and throws a generic exception. You must register and configure an authentication system such as Microsoft Identity, OAuth, or JWT to return a 401 instead of a 500.
Add the JWT Configuration
JSON Web Token (JWT) is a standard method to securely transmit data between your client and your server as a JSON object. The data contained within the object is digitally signed, which means that it can be verified and trusted. You can read more about JWT at. To use the JSON Web Token system in .NET Core and Angular, there are a few steps you must perform.
- Add the JWT package to .NET Core.
- Add JWT bearer token checking package to .NET Core.
- Store default JWT settings in a configuration file.
- Read JWT settings from the configuration file and place into a singleton class.
- Register JWT as the authentication service.
- Add bearer token options to validate incoming tokens.
- Build a JWT token and add it to the user security object.
- Pass the JWT token back to Angular.
Add JWT Package
The first thing you must do in your .NET Core Web API project is to add some packages to use the JSON Web Token system. Open a terminal window in your PtcApi project and enter the following command all on one line.
dotnet add package System.IdentityModel.Tokens.Jwt
After running this command, you’ll be prompted to execute the restore command. Click on the Restore button to execute this command.
Add Bearer Token Check
After running this command, you’ll be prompted to execute the restore command. Click on the Restore button to execute this command.
Store JWT Information in appsettings.json
For the bearer token to be verifiable and trusted, you’re going to need to generate a JSON Web Token object. There are four key pieces of information needed to create this object.
- A secret key used for hashing data sent to the client
- The name of the issuer of the token
- The intended audience of the token
- How many minutes to allow the token to be valid
You’re going to need all of the listed items in two places in your code: once when you configure JWT in the .NET Core Startup class, and once when you generate a new token specifically for a user. You don and add a new literal object, as shown in Listing 7.
Add JwtSettings Class
You need a way to get the settings read in from the appsettings.json file. An instance of a Configuration object can be injected into any class to allow you to read settings from a JSON file. However, I prefer to use my own class with real properties for each property I create in the JSON file. Right mouse-click on the Model folder and add a new file named JwtSettings.cs and add the following code.
public class JwtSettings { public string Key { get; set; } public string Issuer { get; set; } public string Audience { get; set; } public int MinutesToExpiration { get; set; } }
Read the Settings
Open the Startup.cs file and add a new method named GetJwtSettings(). In this method, create a new instance of the JwtSettings class and use the Configuration object, injected into the Startup class, to set each property from the corresponding JSON property in the appsettings.json file. After adding this method, you must add a using statement for the System namespace.; }
Create a Singleton for the JWT Settings
Locate the ConfigureServices() method and create an instance of the JwtSettings class near the top of the method. Call the GetJwtSettings() method to read all of the settings into the JwtSettings object. Add the instance of the JwtSettings object as a singleton to the .NET core services so you can inject the JwtSettings object into any controller.
public void ConfigureServices( IServiceCollection services) { // Get JWT Settings from JSON file JwtSettings settings; settings = GetJwtSettings(); services.AddSingleton<JwtSettings>(settings); // REST OF THE CODE HERE }
Register JWT as the Authentication Provider
Below the code you just added, add the code shown in Listing 8 to register JWT as an authentication provider. Call the AddAuthentication() method on the services object and set the two properties on the options, DefaultAuthenticateScheme and DefaultChallengeScheme, to the value "JwtBearer".
Next, call the AddJwtBearer() method and set options for the bearer token using a TokenValidationParmeters object. It’s in this object that you set properties using the values read in from the appsettings.json file. Most of these properties are self-explanatory. For additional information on what each one does, you can do a Google search on JWT and read one of any several articles on how to configure JWT.
After adding this code, you’re going to have to add a couple more Using statements. Namely; using Microsoft.IdentityModel.Tokens and using System.Text.
The last thing to do in the Startup class is to modify the Configure() method and tell it to use authentication, as shown in the following code snippet.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // REST OF THE CODE HERE app.UseAuthentication(); app.UseMvc(); }
Inject Settings into SecurityController
Besides using the settings from the JSON file in the startup file, you also need them in the SecurityManager class to build the bearer token. Because you create an instance of the SecurityManager in the SecurityController class, inject the JwtSettings class into the SecurityController class, as shown in Listing 9.
Create a private field named _settings in this class and set this field from the value injected in the constructor. Pass the _settings value to the SecurityManager constructor in the Login() method. You haven’t modified the constructor of the SecurityManager to accept this yet, so VS Code will display an error, but you’re going to add that code in the next section.
Accept Settings in SecurityManager
Open the SecurityManager.cs file and add a private field and a constructor just like you did in the SecurityController class. You’re going to learn what you do with these settings in the next section of this article.
private JwtSettings _settings; public SecurityManager(JwtSettings settings) { _settings = settings; }
Build a JSON Web Token
You’re finally ready to build a bearer token you can add to the BearerToken property in the user security object. Add a new method to the SecurityManager class named BuildJwtToken(). The first thing this method does is create a new SymmetricSecurityKey object using the key you placed into the appsettings.json file. Next, add two claims that are needed when generating a JSON Web Token; Subject (Sub) and JSON Token ID (Jti). Into the Sub claim, place the user name, and into the Jti claim, you just need a unique identifier, so generate a GUID.
Next, add the custom claims you need for your application. In this simple example, create one claim for each property in the AppUserAuth class. Notice the use of the ToLower() method to convert the True and False values to lower case. JavaScript and TypeScript always use lower case for the values true and false.
A new JwtSecurityToken object is created and set with the properties from the JwtSettings class. You must use the same values from the JwtSettings class, just like you used in the Startup class. If you don't, the token generated here won't match when it’s passed back by Angular and is attempted to be verified by the code you wrote in the Startup class.
The WriteToken() method of the JwtSecurityTokenHandler class is called to Base64 to encode the resulting string. It’s this Base64 encoded string that’s placed into the BearerToken property in your user security object that’s passed to your Angular application.
After typing in all this code, you must add the following using statements at the top of the SecurityManager class.
using Microsoft.IdentityModel.Tokens; using System.Text; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt;
Call the BuildJwtToken() Method
Locate the BuildUserAuthObject() method and add code to call this BuildJwtToken() method and assign the string result to the BearerToken property.
protected AppUserAuth BuildUserAuthObject(AppUser authUser) { AppUserAuth ret = new AppUserAuth(); List<AppUserClaim> claims = new List<AppUserClaim>(); // Set User Properties ret.UserName = authUser.UserName; ret.IsAuthenticated = true; ret.BearerToken = BuildJwtToken(ret); // Rest of the code here
Try It Out
If you haven’t already done so, stop the PtcApi Web API project from running. Save your changes and run the PtcApi project again. If you’re logged into the Angular application, click the Logout menu. Enter either "psheriff" or "bjones" and a password of "P@ssw0rd" and you should see a screen that looks like Figure 6.
If you wish to see what makes up the bearerToken property, you can decode the value at the website. Copy the bearer token displayed on the log in page to the clipboard. Open a browser window and go to. Scroll down on the page until you see a box labeled Encoded. Delete what’s in there and paste in your bearer token. You should immediately see the payload data with all your data, as shown in Figure 7.
Try It Out
Click on the Products menu and you should now see a generic 401 Unauthorized message in the developer tools console window that looks like Figure 8. The reason for this error is that the server doesn’t know that you’re the same person that just logged in. You must pass back the bearer token on each Web API call to prove to the server that you have permission to call the API.
Add Headers to Product Service
To avoid receiving the status code 401, pass the bearer token each time you make a Web API call from your Angular code. You’re going to learn how to automatically add the token to every call in the next section of this article, but’ve }); }
Try It Out
Save your changes, go to the browser and login as "psheriff", and click on the Products menu. You should see the product data displayed. This is because the server has authenticated your token and knows who you are. Thus, you’re granted access to the Get() method in the ProductController.
HTTP Interceptor
You’re going to have many Web API calls in a typical Angular application. Instead of having to write the code you just wrote into every method call, Angular allows you to create an HTTP Interceptor class to place custom headers into each Web API call. Open a command prompt in the PTC project and enter the following command to create a module, and have it registered in the app.module.
ng g m security/httpInterceptor -m app.module --flat
Open the newly created file, http-interceptor.module.ts, and replace all of the code with the code shown in Listing 11. All requests that are sent to a Web API method using the HttpClient are now routed through this interceptor class.
In the intercept() method, you retrieve the bearer token from local storage, and if the token exists, you clone the existing request that’s being sent. You then create a new header on this request setting the headers property with the Authorization header followed by the word "Bearer " and the token after this word. This is the new Web request that’s returned from this method. If the token doesn’t exist in local storage, the original Web request is returned. You can read more about HTTP Interceptors at.
You now finally see the reason why you stored the bearer token in local storage in the login() method of the SecurityService class. You might be wondering why you don't just inject a SecurityService object into this class and retrieve it from the SecurityService object like you do in all the other components. The reason is that you can't have an HTTP interceptor injected with any class that uses HttpClient as this causes a recursion error.
Open the product.service.ts file and change the getProducts() method back to what you had originally. Remove the code that creates the HttpHeaders, and pass this as a second parameter to the get() method. The getProducts() method should now look like the following.
getProducts(): Observable<Product[]> { return this.http.get<Product[]>(API_URL); }
Try It Out
Save your changes, go to your browser, log in as "psheriff", and try accessing the Products menu. You should still be getting data from the product controller. This verifies that the HTTP Interceptor class is working.
Add Security Policy
The [Authorize] attribute ensures that a user is authenticated. However, for some Web API methods, you may wish to restrict access based on the claims you created..
[Authorize(Policy = "CanAccessProducts")]
Try It Out
Open SQL Server and open an Edit window for the UserClaim table. Modify the claim CanAccessProducts to a false value for the "PSheriff" user. Open the app-routing.module.ts file and remove the route guard for the products path. Your route for the products path should now look like the following code snippet.
{ path: 'products', component: ProductListComponent },
Save your changes, go back to the browser, and login as "psheriff". Type directly into the address bar and you should now get a 401-Unauthorized error. Put the route guard back and reset the CanAccessProducts claim to a true value in the UserClaim table.
Summaryor class. In the next article, you’ll learn to use an array of claims to secure your Angular application. To accomplish this, you build a custom structural directive in Angular. | https://www.codemag.com/Article/1809031/Security-in-Angular-Part-2 | CC-MAIN-2019-47 | refinedweb | 5,279 | 54.42 |
From AS3 to C#, Part 19: SQL-Style Queries With LINQ
The series continues today by looking at C#’s SQL-style queries called LINQ. These don’t run on a database, but rather query in-memory objects like arrays. Read on to learn about this powerful tool for writing extremely concise, readable
LINQ can be thought of as a more general version of the E4X support in AS3. Instead of querying only relatively-rare XML objects, it queries extremely-common objects like arrays, lists, dictionaries, and so forth. As a reminder, here’s how E4X looks in AS3:
function findAdultSmiths(xml:XML): XMLList { // E4X expression here return xml.(@lastName == "Smith" && Number(@age) >= 18); } // Data to query var xml:XML = <people> <person lastName="Jones" age="11" /> <person lastName="Adams" age="22" /> <person lastName="Smith" age="40" /> <person lastName="Smith" age="5" /> </people>; // Loop over results of the query var adultSmiths:XMLList = findAdultSmiths(people.person) for each (var person:XML in adultSmiths) { trace("LastName: " + person.@lastName + ", Age: " + person.@age); } // Output: // LastName: Smith, Age: 40
But what if you had a simple
Array or
Vector of
Person objects? E4X would be of no use unless you first converted it to an XML document. That’d be extremely slow and messy. C#’s LINQ queries provide an answer to that scenario. Here’s how the above E4X expression would look as a LINQ query:
public class Person { public string LastName { get; private set; } public int Age{ get; private set; } public Person(string lastName, int age) { LastName = lastName; Age = age; } } public IEnumerable<Person> FindAdultSmiths(Person[] people) { // LINQ query here return from p in people where p.LastName == "Smith" && p.Age >= 18 select p; } // Data to query var people = new Person[]{ new Person("Jones", 11), new Person("Adams", 22), new Person("Smith", 40), new Person("Smith", 5) }; // Loop over results of the query var adultSmiths = FindAdultSmiths(people) foreach (var person in adultSmiths) { Debug.Log("LastName: " + person.LastName + ", Age: " + person.Age); } // Output: // LastName: Smith, Age: 40
You might have noticed that LINQ queries return an
IEnumerable of some type, just like iterators. This is because they basically are iterators that have not yet gone through the data source evaluating the query expressions. LINQ queries are “lazy” evaluated during the
foreach loop or as you manually go through the
IEnumerable‘s values.
If you want, you can force the query to complete right away with some extension methods found in the
System.Linq namespace. Here’s an example:
using System.Linq; public Person[] FindAdultSmiths(Person[] people) { var e = from p in people where p.LastName == "Smith" && p.Age >= 18 select p; return e.ToArray(); // force it }
Other ways of forcing the LINQ query to execute include
ToList() that returns a
System.Collections.Generic.List<T>> (similar to
Vector in AS3) and
FirstOrDefault that returns the first result or the default value (usually
null) if not found. These are all just convenience methods that replace boilerplate code like this
FirstOrDefault sample implementation:
public static class IEnumerableExtensions { public static T MyFirstOrDefault<T>(this IEnumerable<T> e) { var e2 = e.GetEnumerator(); return e2.MoveNext() ? e2.Current : default(T); } } var e = from p in people where p.LastName == "Smith" && p.Age >= 18 select p; var first = e.MyFirstOrDefault(); Debug.Log("LastName: " + first.LastName + ", Age: " + first.Age);
Now let’s delve more deeply into what you can do inside LINQ queries. Here is the same query as above but broken onto multiple lines:
from p in people where p.LastName == "Smith" && p.Age >= 18 select p
The
from part always comes first and specifies the data source to query:
people. It also names a loop iterator variable
p that will represent the current
Person the query is being run on.
Next is the
where part that acts like a filter. This has access to the iterator variable
p and must return a
bool based on that. You can write arbitrarily-complex expressions here, including function calls or even nested LINQ queries.
Lastly there is the
select part. This determines the type of
IEnumerable<T> that the LINQ query will evaluate to. For example, if you wanted it to evaluate to an
IEnumerable<int> of ages, you could have written
select p.Age instead. Like the
where part, this expression can also be arbitrarily complex and can return any type.
These are three basic parts of simple LINQ queries and they already replace quite a lot of code:
public Person[] FindAdultSmiths(Person[] people) { var list = new List<People>(); foreach (var p in people) { if (p.LastName == "Smith" && p.Age >= 18) { list.Add(p); } } return list.ToArray(); }
However, LINQ queries can be much more complex. Let’s start exploring their features by looking at
orderby clauses. These allow you to sort the results either ascending or descending:
from p in people where p.LastName == "Smith" && p.Age >= 18 orderby p.Age // sort ascending by age select p
The default is an ascending sort, but you can specify explicitly if you want:
from p in people where p.LastName == "Smith" && p.Age >= 18 orderby p.Age descending select p
You can also add more than one sorting criteria to allow for tie-breaking:
from p in people where p.LastName == "Smith" && p.Age >= 18 orderby p.Age ascending, p.LastName descending select p
There is also the
group clause that allows you to group results together into an
IGrouping<T> instead of an
IEnumerable<T>. Here’s a query that would group
people by the first letter of their last name:
var grouping = from p in people group p by p.LastName[0]; foreach (var group in grouping) { Debug.Log("Group: " + group.Key); foreach (var person in group) { Debug.Log(" LastName: " + person.LastName + ", Age: " + person.Age); } } /* Output: Group: J LastName: Jones, Age: 11 Group: A LastName: Adams, Age: 22 Group: S LastName: Smith, Age: 40 LastName: Smith, Age: 5 */
The
by sub-clause allows for an arbitrary expression and can return whatever it wants to.
You can also nest LINQ queries. The following example shows an outer query that goes over sentences and an inner query that goes over the words in those sentences:
var sentences = new string[] { "Once upon a time", "They lived happily ever after" }; var query = from sentence in sentences from word in sentence.Split(' ') where word.ToLower()[0] == 'a' || word.ToLower()[0] == 'e' || word.ToLower()[0] == 'i' || word.ToLower()[0] == 'o' || word.ToLower()[0] == 'u' select word; foreach (var word in query) { Debug.Log(word); } /* Output: Once upon a ever after */
One problem with this query is that it does a lot of redundant work by calling
ToLower over and over. This is where the
let clause comes in. It’s useful for defining a constant variable so it’s not evaluated over and over in the
where clause. Here’s how that looks:
var query = from sentence in sentences from word in sentence.Split(' ') let firstLetter = word.ToLower()[0] where firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u' select word;
Lastly, there is the concept of a “join”. The simplest type of join is called an “inner join” and it’s where you take two lists and join them together based on something they have in common. For example, we could join the list of people with a list of houses that have people that own them:
public class House { public string Address { get; private set; } public Person Owner { get; private set; } public House(string address, Person owner) { Address = address; Owner = owner; } } var jones11 = new Person("Jones", 11); var adams22 = new Person("Adams", 22); var smith40 = new Person("Smith", 40); var smith05 = new Person("Smith", 5); var people = new Person[]{ jones11, adams22, smith40, smith05 }; var houses = new House[]{ new House("123 Main St", adams22), new House("211 Flower Blvd", smith40) } var query = from p in people join h in houses on p equals h.Owner select new { Person=p, House=h }; foreach (var result in query) { Debug.Log( "LastName: " + result.Person.LastName + " lives at: " + result.House.Address ); } /* Output: LastName: Adams lives at: 123 Main St LastName: Smith lives at: 211 Flower Blvd */
Notice that the
join declares a new iterator variable as it essentially is doing a nested search to find what the
equals sub-clause is searching for. The
select clause here is returning an anonymous type since there’s rarely a class for “person and house” available.
If you add an
into sub-clause at the end of the
join clause, you get what’s called a “group join”. Just with the
group clause we used before, this will produce groups as a result:
var query = from p in people join h in houses on p equals h.Owner into g select new { Person=p, Group=g }; foreach (var result in query) { var person = result.Person; Debug.Log(person.LastName + "(Age=" + person.Age + ") lives at:"); foreach (var house in result.Group) { Debug.Log(" " + house.Address); } } /* Output: Jones(Age=11) lives at: Adams(Age=22) lives at: 123 Main St Smith(Age=40) lives at: 211 Flower Blvd Smith(Age=5) lives at: */
Here the results are a little different. Rather than just return the matches, an empty group is returned if there is no match. The children (Jones, 11 and Smith, 5) don’t own any houses, so they have an empty group.
The final kind of join is called a “left outer join” and can help address this issue. It’ll allow you to specify an alternate value to return if there is an empty group. You do this by nesting a
from clause and using the
DefaultIfEmpty helper function:
var query = from p in people join h in houses on p equals h.Owner into g from h2 in g.DefaultIfEmpty() select new { Person = p, Residence = (h2 == null ? "is homeless" : "lives at " + h2.Address) }; foreach (var result in query) { var person = result.Person; Debug.Log(person.LastName + " (Age=" + person.Age + ") " + result.Residence); } /* Output: Jones (Age=11) is homeless Adams (Age=22) lives at 123 Main St Smith (Age=40) lives at 211 Flower Blvd Smith (Age=5) is homeless */
Notice that the results are once again a single-dimensional list, not a list of groups.
To summarize the conciseness of LINQ queries compared to the code we’d have to manually write without them, the following table will show the C# LINQ query and the equivalent in AS3 where they’re not available (aside from XML). Which would you rather write, read, and maintain?
//////// // C# // //////// var query = from p in people join h in houses on p equals h.Owner into g orderby p.Age descending, p.LastName ascending select new { Person=p, Group=g }; foreach (var result in query) { var person = result.Person; Debug.Log(person.LastName + "(Age=" + person.Age + ") lives at:"); foreach (var house in result.Group) { Debug.Log(" " + house.Address); } } //
///////// // AS3 // ///////// class PersonAndHouses { var person:Person; var houses:Vector.<House> = new <House>[]; } private function RunQuery( people:Vector.<Person>, houses:Vector.<House> ): Vector.<PersonAndHouses> { var results:Vector.<PersonAndHouses> = new <PersonAndHouses>[]; for each (var p:Person in people) { var result:PersonAndHouses = new PersonAndHouses(); result.person = p; results.push(result); for each (var h:House in houses) { if (h.owner == p) { result.houses.push(h); } } } results.sort( function(a:PersonAndHouses, b:PersonAndHouses): Number { var primary:int = b.person.age - a.person.age; if (primary == 0) { return a.person.lastName < b.person.lastName ? -1 : 1; } else { return Number(primary); } } ); return results; } for each (var result:PersonAndHouses in RunQuery(people, houses)) { var person:Person = result.person; trace(person.lastName + "(Age=" + person.age + ") lives at:"); for each (var house:House in result.houses) { trace(" " + house.address); } }
That’s all for today. Stay tuned for next week when we’ll continue the series with even more exciting new features in C#!
Spot a bug? Have a question or suggestion? Post a comment!
#1 by henke37 on November 24th, 2014 · | Quote
Are you sure that it isn’t “order by”, with the space?
#2 by jackson on November 24th, 2014 · | Quote
Yep, it’s really orderby. | https://jacksondunstan.com/articles/2872 | CC-MAIN-2019-09 | refinedweb | 1,997 | 66.54 |
2015-10-15 03:20 AM
Hi,
for several months now I have a running installation of WFA3.1 successfully aquiring data from my OCUM6.3RC1.
Now, out of a sudden I get the following error when aquiring data from that OCUM server:
Table 'ocum_data_collector.lun_import_ext' doesn't exist
I reset the scheme and also deleted and recreated the OCUM data source - still no change.
Is this error caused by WFA or OCUM? And any idea how to remediate?
Thanks and regards, Niels
Solved! SEE THE SOLUTION
2015-10-15 03:51 AM
In OCUM, there is a module named Data Collector.
It collects attribute data whatever is specified in a config file.
There can be 3 issues:
1. That config file has gone missing.
2. OCUM has not created the table via Data Collector.
3. The config file has got corrupted.
WFA is unable to find the table when fetching the data from Data Collector.
Regards
Abhi
2015-10-15 04:38 AM
Hi,
2015-10-27 04:02 AM
This is a customer-facing demo environment used by several perople.
I assume somebody installed the pack to demonstrate the WFA Workflow Store.
Installing the data-collector file into OCUM worked out as described.
Thanks!
Kind regards, Niels
2016-01-20 12:50 PM
I see something similar. A few weeks ago my OCUM 6.3 data source quit working. The error I get (even if I delete and recreate the Data Source) is
"Data truncation: Column set to default value; NULL supplied to NOT NULL column 'raid_status' at row 1". I don't remember loading any Foreign LUN
import pack. Is there some other way to troubleshoot this data source aquisition error?
2016-01-20 09:22 PM
It may be because, in WFA for Clustered data ONTAP (cm_storage scheme) the aggregate dictionary entry has a 'raid_status' attribute, which cannot be NULL.
However it is getting NULL value from OCUM.
That is why the error is being thrown. Please check if 'raid_staus' of any aggregate in OCUM6.3 is NULL.
Regards
Abhi | http://community.netapp.com/t5/OnCommand-Storage-Management-Software-Discussions/aquisition-fails-from-OCUM-6-3/td-p/111164 | CC-MAIN-2018-17 | refinedweb | 344 | 68.47 |
Learning Python and tasked with returning the index location of the first letter in the lists. But it has to be to the left uppermost part on any given list. For example 'a' would return as index (0,2).
When I run my code though, it says the letter isn't found. Assuming Value represents the letters and '.' is already defined in the tester. It should return none if its a '.'
area1 = [['.', 'a', 'a', 'D', 'D'],
['.', '.', 'a', '.', '.'],
['A', 'A', '.', 'z', '.'],
['.', '.', '.', 'z', '.'],
['.', '.', 'C', 'C', 'C']]
def find_spot_values(value,area):
for row in area:# Looks at rows in order
for letter in row:# Looks at letter strings
if value == letter in area: #If strings are equal to one another
area.index(value)# Identifies index?
find_spot_values('D',area1)
With minimal changes to your code
def find_spot_values(value, area): for row in area: # Looks at rows in order for letter in row: # Looks at letter strings if value == letter: # If strings are equal to one another return area.index(row), row.index(letter) # Identifies indices | https://codedump.io/share/Ov1XcFDRDYA0/1/how-to-return-the-first-index-occurence-of-item-in-lists | CC-MAIN-2018-09 | refinedweb | 171 | 75 |
Containers—Not Virtual Machines—Are the Future Cloud
_1<<.
The Problem with VMs
Here are the penalties we currently pay for VMs:
Running a whole separate operating system to get a resource and security isolation.
Slow startup time while waiting for the OS to boot.
The OS often consumes more memory and more disk than the actual application it hosts. The Rackspace Cloud recently discontinued 256MB instances because it didn't see them as practical. Yet, 256MB is a very practical size for an application if it doesn't need to share that memory with a full operating system.
As for slow startup time, many cloud infrastructure users keep spare virtual machines around to accelerate provisioning. Virtual machines have taken the window from requesting to receiving resources down to minutes, but having to keep spare resources around is a sign that it's still either too slow or not reliable enough.
So What's the Difference?
VMs are fairly standardized; a system image running on one expects mostly the same things as if it had its own bare-metal computer. Containers are not very standardized in the industry as a whole. They're very OS- and kernel-specific (BSD jails, Solaris Zones, Linux namespaces/cgroups). Even on the same kernel and OS, options may range from security sandboxes for individual processes to nearly complete systems.
VMs don't have to run the same kernel or OS as the host and they obtain access to resources from the host over virtualized devices—like network cards—and network protocols. However, VMs are fairly opaque to the host system; the hypervisor has poor insight into what's been written but freed in block storage and memory. They usually leverage hardware/CPU-based facilities for isolating their access to memory and appear as a handful of hypervisor processes on the host system.. Some implementations even support handing sockets from the host to the container of standard UNIX facilities.
VMs are also heavyweight. They require a full OS and system image, such as EC2's AMIs. The hypervisor runs a boot process for the VM, often even emulating BIOS. They usually appear as a handful of hypervisor processes on the host system. Containers, on the other hand, are lightweight. There may not be any persistent files or state, and the host system usually starts the containerized application directly or runs a container-friendly init dæmon, like systemd. They appear as normal processes on the host system.
Figure 3. Virtualization decoupled provisioning from hardware deployment. Containers decouple provisioning from OS deployment and boot-up.
Containers Now Offer the Same Features as VMS, but with Minimal Overhead
Compared to a virtual machine, the overhead of a container is disruptively low. They start so fast that many configurations can launch on-demand as requests come in, resulting in zero idle memory and CPU overhead. A container running systemd or Upstart to manage its services has less than 5MB of system memory overhead and nearly zero CPU consumption. With copy-on-write for disk, provisioning new containers can happen in seconds.
Containers are how we at Pantheon maintain a consistent system architecture that spans free accounts up to clustered, highly available enterprise users. We manage an internal supply of containers that we provision using an API.
We're not alone here; virtually every large PaaS system—including Heroku, OpenShift, dotCloud and Cloud Foundry—has a container foundation for running their platform tools. PaaS providers that do rely on full virtual machines have inflexibly high infrastructure costs that get passed onto their customers (which is the case for our biggest competitors in our market).
The easiest way to play with containers and experience the difference is by using a modern Linux OS—whether locally, on a server or even on a VM. There is a great tutorial on Fedora by Dan Walsh and another one with systemd's nspawn tool that includes the UNIX socket handoff.
Evolving Containers in Open Source
While Pantheon isn't in the business of providing raw containers as a service, we're working toward the open-source technical foundations. It's in the same spirit as why Facebook and Yahoo incubated Hadoop; it's part of the foundation we need to build the product we want. We directly contribute as co-maintainers to systemd, much of which will be available in the next Red Hat Enterprise Linux release. We also send patches upstream to enable better service "activation" support so containers can run only when needed.
We have a goal that new installations of Fedora and other major distributions, like Ubuntu, provide out-of-the-box, standard API and command-line tools for managing containers, binding them to ports or IP addresses and viewing the resource reservation and utilization levels. This capability should enable other companies eventual access to a large pool of container hosts and flavors, much as Xen opened the door to today's IaaS services.
One way we'll measure progress toward this goal is how "vanilla" our container host machines are. If we can prepare a container host system by just installing some packages and a certificate (or other PKI integration), we'll have achieved it. The free, open-source software (FOSS) world will be stronger for it, and Pantheon will also benefit by having less code to maintain and broader adoption of container-centric computing.
There's also an advantage to this sort of FOSS contribution versus Cloud Foundry, OpenShift or OpenStack, which are open-source PaaS and LaaS stacks. What Pantheon is doing with projects like systemd redefines how users manage applications and resources even on single machines. The number of potential users—and, since it's FOSS, contributors—is orders of magnitude larger than for tools that require multi-machine deployments to be useful. It's also more sustainable in FOSS to have projects where 99% of the value reaches 99% of a large, existing user base.
Efficiency demands a future of containers running on bare-metal hardware. Virtual machines have had their decade. | https://www.linuxjournal.com/content/containers%E2%80%94not-virtual-machines%E2%80%94are-future-cloud?page=0,0 | CC-MAIN-2018-30 | refinedweb | 1,006 | 52.49 |
I'm working with PyCrypto in Django and I need to encrypt a string using the user's secret key they made themselves. I successfully wrote an encryption method as follows:
from Crypto.Cipher import AES
from Crypto.Random import get_random_string
def encrypt(value, key):
"""
Return an encryption of value under key, as well as IV.
Pads value with extra bytes to make it multiple of 16.
"""
extra = 16 - (len(value) % 16)
data = value + chr(extra) * extra
iv = get_random_bytes(16)
encryption_suite = AES.new(key, AES.MODE_CBC, iv)
cipher_text = encryption_suite.encrypt(data)
return cipher_text, iv
user = User.objects.get(id=user_id)
cipher, iv = encrypt(user_value, user_key)
user.secret_value = cipher
user.iv = iv
user.save()
Warning: Incorrect string value: '\xE7\xAA\x13\x036\xC8...' for column 'iv' at row 1
I guess you're trying to save binary data into
CharFields. Either change field types of
user.iv and
user.secret_value to
BinaryField, or encode these values using for example base64 encoder. | https://codedump.io/share/6FH1AOsQoSBr/1/django-pycrypto---save-encrypted-string-to-database-bad-unicode-data | CC-MAIN-2017-13 | refinedweb | 160 | 54.59 |
erf, erff, erfl, − error function
#include <math.h>
double
erf(double x);
float erff(float x);
long double erfl(long double x);
Link with −lm.
erf(x) = 2/sqrt(pi)* integral from 0 to x of exp(−t*t) dt
On success, these functions return the error function of x, a value in the range [−1, 1].
If x is a NaN, a NaN is returned.
If x is +0 (−0), +0 (−0) is returned.
If x is positive infinity (negative infinity), +1 (−1) is returned.
If x is subnormal, a range error occurs, and the return value is 2*x/sqrt(pi)..
For an explanation of the terms used in this section, see attributes(7).
C99, POSIX.1-2001. The variant returning double also conforms to SVr4, 4.3BSD.
cerf(3), erfc(3), exp(3)
This page is part of release 3.53 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at−pages/. | http://man.linuxtool.net/centos7/u3/man/3_erf.html | CC-MAIN-2019-35 | refinedweb | 165 | 67.86 |
[EMAIL PROTECTED] wrote: > Hi Philipp > >>> IMO it would be great to solve this properly, because one point of >>> using views is to have a fine control over what to publish >> and what not. >>> And this is a bit broken at this point, currently. >> Right, that's why page templates that just provide macros >> should be registered unpublishable browser views and not >> browser pages. >> >> You see how far into the confusion the <browser:page /> >> directive has brought us? > > Yes, > but this is only a problem how we lookup views/pages > via /@@ in templates.
Advertising
That's how we lookup views. @@ is short for ++view++. Traversal namespaces are the way to lookup things that are not direct attributes. >. Philipp _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg05163.html | CC-MAIN-2016-44 | refinedweb | 127 | 75 |
Design Guidelines, Managed code and the .NET Framework
Well, glad to see many of you got it right, I think FxCop is doing its job! Google helped me find a couple of posts on this already out there:
Here is the full text I will add to the API Design Guidelines document. Let me know what you think.
Consider the example below which prints out “value != 42, what is wrong” when a new instance of Derived is created. The implementer of the derived class assumes that the value will be set to 42 before anyone can call Method1(). But that is not true because the base class’s constructor is called before the Derived class’s constructor finishes, so any calls it makes to Method1() causes the problem.
public class Base
{
public Base()
{
Method1();
}
public virtual void Method1() {
Console.WriteLine("In Base's Method1()");
}
public class Derived: Base
private int value;
public Derived()
{
value = 42;
public override void Method1()
if (value == 42) Console.WriteLine("value == 42, all is good");
else Console.WriteLine("value != 42, what is wrong?");
PingBack from
PingBack from | http://blogs.msdn.com/brada/archive/2004/08/10/212461.aspx | crawl-002 | refinedweb | 181 | 75 |
I am working on implementing a small online survey using the google app engine. I've already made the survey itself. What I need now is the possibility to store all the inputs from a person participating in this survey in the database.
The straight forward way to achieve this would be to create an entity with a property for each of the inputs and to create such an entity each time a person submits a filled out survey.
As I have about 30 inputs in my survey, I would like to know whether there is a more elegant or at least a less tedious way to turn the data in the post request into a datastore entity.
Thank you.
WTForms has a GAE extension that can be used to generate forms from models and models from forms..
wtforms.ext.appengine.db.model_form(model, base_class=Form, only=None, exclude=None, field_args=None, converter=None).
Creating a model based on a form involves creating a form object then passing the POST data to it.
formdata– Used to pass data coming from the enduser, usually request.POST or equivalent. formdata should be some sort of request-data wrapper which can get multiple parameters from the form input, and values are unicode strings, e.g. a Werkzeug/Django/WebOb MultiDict
And there is a similar question here: WTForms error:TypeError: formdata should be a multidict-type wrapper
e.g.
def post(self): form = model_form(Ticket) form_object = form(formdata=self.request.POST)
from some random example I just found. | https://codedump.io/share/LgPHsu0d8w6j/1/google-app-engine-creating-datastore-entity-from-the-post-data | CC-MAIN-2018-05 | refinedweb | 255 | 54.83 |
What's Happening
Oil prices continue to fall, and big oil and gas stocks are taking a hit. Oil and gas giant Chevron recently hit a 52-week low in reaction to falling oil prices and the stock is currently down 16% on the year.
Technical Analysis
CVX was recently trading at $104.98 down $28.9 from its 12-month high and $0.79 above its 12-month low. InvestorsObserver's Stock Score Report gives CVX a 37 long-term technical score and a 29 short-term technical score. The stock has recent support above $105.5 and recent resistance below $114. Of the 16 analysts who cover the stock 10 rate it Strong Buy, 1 rate it Buy, 5 rate it Hold, 0 rate it Sell, and 0 rate it Strong Sell, CVX gets a score of 43 from InvestorsObserver's Stock Score Report.
Analyst's Thoughts
As oil prices continue to fall big oil and gas stocks extend their recent losses. CVX recently hit a new 52-week low in reaction to the drop in crude prices, but the stock's valuation has fallen into oversold territory and should enjoy a nice bounce if and when crude prices start to stabilize. As recently as October Brent Crude was trading at $87 a barrel, but since that time prices have fallen to their current level of $54.50, for a 37% pullback. Not only is there a fear of oversupply, but now concerns are also mounting over slowing global growth which will impact demand for the supply. Russia recently announced its daily production had risen to a new record 11.4 million barrels a day, and Saudi Arabia is also producing oil at a 22-month high of 7.7 million barrels a day. The U.S. is also producing a lot of oil, around 11.6 million barrels a day which is up 1 million barrels from the same time last year. Oil has taken a beating and until the market sees more firm commitments on production reductions crude will remain under pressure and oil and gas stocks like CVX will struggle to find their footing. Analysts have an average price target of $142.80 on the stock.
Stock Only Trade
Bullish Trade
If you want a bullish hedged trade on the stock, consider a 2/15/19 80/85 bull-put credit spread for a $0.25 credit. That's a potential 5.3% return (34% annualized*) and the stock would have to fall 19.3% to cause a problem.
Bearish Trade
If you want to take a bearish stance on the stock at this time, consider an 2/15/19 120/125 bear-call credit spread for a $0.40 credit. That's a potential 8.7% return (56 annualized*) and the stock would have to rise 14. | https://www.nasdaq.com/articles/chevron-near-52-week-low-oil-continues-fall-2018-12-22 | CC-MAIN-2020-45 | refinedweb | 473 | 73.68 |
Root Finding, Again
March 21, 2014
We give our solution in Python, starting with the secant method. This method is not very useful in practice, because going outside the original bounds means that some steps actually retreat from the root instead of advancing toward it:
def secant(fun, x1, x2, args=(), xtol=1e-12, maxiter=1000):
"""the fastest (superlinear), but will often fail"""
a, b = float(x1), float(x2)
fa, fb = fun(a, *args), fun(b, *args)
for i in xrange(maxiter):
if fa == fb:
raise ZeroDivisionError("fa == fb in secant")
dx = -(a - b) / (1 - fb / fa)
x = a + dx
y = fun(x, *args)
if abs(dx) < xtol or y == 0.0:
return x
a, fa, b, fb = b, fb, x, y
raise ValueError("too many iterations")
This is essentially the same as the regula falsi method, but after every iteration the last two points are kept for the next iteration, instead of trying to keep a bracket on the root.
Now the Dekker method. Points x1 and x2 should bracket a root. If
disp=True the iterates are printed and one can see if a bisection or a secant step is taking place.
def dekker(fun, x1, x2, args=(), xtol=1e-8, disp=False):
"""see wiki Brent
c is last iterate of b
a, b bracket solution abs(fb)
if f(s) has same sign as fa, then old b beomes new contrapoint
the solution is within 6*EPS + 2 * xtol
"""
a, b = float(x1), float(x2)
fa, fb = fun(a, *args), fun(b, *args)
if fa * fb > 0.0: raise RootNotBracketedException(a, b, fa, fb)
c, fc = a, fa
feval = 2
while 1:
if abs(fa) < abs(fb):
a, fa, b, fb, c, fc = b, fb, a, fa, b, fb
xm = (a - b) / 2 # bisection step
tol1 = 2 * EPS * abs(b) + xtol
if abs(xm) 0:
q = -q
p = abs(p)
d = p / q if p tol1 else __sign(tol1, xm))
fb = fun(b, *args)
feval += 1
if disp:
msg = "b" if abs(d) == abs(xm) else "s"
fmt = "{:3d} a={:7.4g} b={:12.9g} c={:7.4g} fb={:10.3g} xm={:8.2g} {:s}"
print fmt.format(feval, a, b, c, fb, xm, msg)
if fa * fb > 0: # if new iterate has same sign as a - old b take s place of a
a, fa = c, fc
The
__sign function returns x if y > 0, −x if y < 0, and 0 otherwise:
def __sign(x, y):
if y > 0.0 :
return x
elif y < 0.0:
return -x
else:
return 0.0
As a test, we compare the secant, regula falsi and dekker methods finding roots of the function
cos(x) - x in the interval 0 to 1; the left column is the result and the right column is the time taken:
Secant 0.739085133215 0.000127772968474
Regula Falsi 0.739085133215 0.00897438331583
Dekker 0.739085133215 0.00184064914826
The secant method is very good when it works. Here are the intermediate steps of the Dekker algorithm:
3 a= 0 b= 0.685073357 c= 1 fb= 0.0893 xm= -0.5 s
4 a= 1 b= 0.736298998 c= 0.6851 fb= 0.00466 xm= 0.16 s
5 a= 1 b= 0.739119362 c= 0.7363 fb= -5.73e-05 xm= 0.13 s
6 a= 0.7363 b= 0.739085112 c= 0.7391 fb= 3.53e-08 xm= -0.0014 s
7 a= 0.7391 b= 0.739085133 c= 0.7391 fb= 2.67e-13 xm= 1.7e-05 s
8 a= 0.7391 b= 0.739085133 c= 0.7391 fb= 0 xm= 1.7e-05 s
By comparison, here are the results when the three methods are run on a “dirty function” that has the value -1e-10 in (0,0.99) and then rises steeply to 1 at x=1:
Secant fa == fb in secant
Regula Falsi too many iterations
Dekker 0.990000100000 0.000124694101764
The secant method fails because the two points have the same value, and regula falsi takes too long, but the Dekker method finds the root without difficulty.
You can run the program at. | https://programmingpraxis.com/2014/03/21/root-finding-again/2/ | CC-MAIN-2017-04 | refinedweb | 685 | 83.56 |
Read in a number of characters from a previously opened file.
FileRead ( "filehandle/filename" [, count] )
A negative or not defined count, reads the whole file from the current position.
If a filename is given rather than a file handle - the file will be opened and closed during the function call - for parsing large - See FileOpen() for details.
A file can be read as binary (byte) data by using FileOpen() with the binary flag - in this case count is in bytes rather than characters. A count value that is too large can lead to AutoIt stopping with a memory allocation failure.
FileGetPos, FileOpen, FileReadLine, FileSetPos, FileWrite, FileWriteLine, String
#include <FileConstants.au3> FileRead.") | https://www.autoitscript.com/autoit3/docs/functions/FileRead.htm | CC-MAIN-2016-22 | refinedweb | 111 | 61.46 |
An example of using the dynamic keyword in C# .NET
December 20, 2016 Leave a comment
The dynamic keyword in C# is similar to Reflection. It helps you deal with cases where you’re not sure of the concrete type of an object. However, you may expect the object to have a certain method that you can invoke at runtime. E.g. you have a framework that external users can write plugins for. You may set up a list of rules for the plugin to be valid, e.g. it must have a method called “Execute” and a property called “Visible”.
There are various ways you can solve this problem and one of them is dynamic objects. Using the dynamic keyword will turn off the automatic type checking when C# code is compiled. The validity of the code will only be checked at runtime.
Let’s model the problem outlined in the first paragraph in code. Say an external user wrote a plugin which implements the required elements as follows:
public class MyBrilliantPlugin { public void Execute() { Console.WriteLine("The plugin is executing..."); } public bool Visible { get { return true; } } }
Then the plugin is loaded to your framework but you won’t of course know in advance its exact type. However, you’ll be able to see its name therefore you can load it to the assembly. Say that all plugins need to be saved in a certain folder called Plugins and the full file path to MyBrilliantPlugin.dll is c:\plugins\MyBrilliantPlugin.dll:
Type pluginType = Assembly.LoadFrom(@"c:\plugins\MyBrilliantPlugin.dll").GetType("MyBrilliantPlugin.MyBrilliantPlugin"); dynamic plugin = Activator.CreateInstance(pluginType);
MyBrilliantPlugin.MyBrilliantPlugin is the fully qualified name of the plugin. In this case I put a class called MyBrilliantPlugin within a C# class library called MyBrilliantPlugin hence the full name of MyBrilliantPlugin.MyBrilliantPlugin.
GetType will return a Type. We’ll call Activator to create an instance of that type. However, CreateInstance returns an object and not the statically typed object MyBrilliantPlugin. Note how you can declare it as “dynamic”. You can in fact declare any type of object as dynamic. It essentially means that we don’t know the exact type of the plugin but we ask the compiler not to care.
You can then call any expected method on it but you won’t of course get compile time checking or intellisense to find the members of the invoked object. Here’s an example how you can invoke the plugin:
try { Console.WriteLine("About to execute plugin..."); plugin.Execute(); Console.WriteLine("Is plugin visible: {0}", plugin.Visible); } catch (Exception ex) { Console.WriteLine("Ooops...: {0}", ex.Message); }
Just to repeat: the compiler won’t check for you at compile time whether there’s a method called Execute() and a property called Visible on the dynamic object. You type “plugin.” there won’t be any IntelliSense helping you out. You’ll get an exception if the invoked elements are not found at runtime.
View all posts on Reflection here. | https://dotnetcodr.com/2016/12/20/an-example-of-using-the-dynamic-keyword-in-c-net-2/ | CC-MAIN-2022-40 | refinedweb | 496 | 58.99 |
I’ve reinstated my travel/ mobile working/ camping blog, using the latest version of eatStatic blog software.
I’ve reinstated my travel/ mobile working/ camping blog, using the latest version of eatStatic blog software.
So, one of my goals for this year was to learn to touch type. I pretty much ignored this goal until last week, when I opened up my copy of Mavis Beacon Typing Tutor. Right now I can type with the correct fingering, without looking, but it is painfully slow – i’m still waiting for the magic moment where I don’t have to pre-calculate every key, and remember which finger to press it with! This is the first blog post I have ever written using the correct technique and it has taken ages, but am determined to stick with it until I am fluent, so expect lots of short blog posts with minimal punctuation until I have this thing nailed!
I:
I’ve written a post about the current plans for the eatStatic blog software (that this blog runs on), on the demo/ documentation blog.
I’ve worked at a fair few agencies in my time, and despite most agencies now using content management systems as standard, the content population and revision workflow is usually sub-optimal:-
Yes, I think we can all see a flaw with this workflow – no need to point out how things could be done differently in the comments!
* I don’t care if your CMS has a really good WYSIWYG editor – it’s either too limited or too powerful, so an untrained editor at best will never really get the result that they want, at worst do some real damage!
Often I create a git repo locally, but then want to push it to a remotely hosted repo.
On the server, create a folder and move into it, then:-
git init --bare
Then in your local git repo:-
git remote add origin ssh://username@yourserver/path/to/repo.git
git push --all origin
(this assumes your remote repo is accessible via ssh)
Over the last couple of years i’ve tried to rationalise the way I use various social media sites, and I realised that how I use a service has evolved over time.
I think flickr was the first social network (of sorts) that I signed up to, in 2005. It was the instagram of it’s day, but with an important difference in that people uploaded whole galleries at a time. It made a real feature of the use of tags, so that you could follow an event, or add contacts and follow their streams. I even signed up for a pro account to allow me to create more galleries. I’d also use it as a blog/ diary – frequently posting pictures of the coffee or beer I was drinking (like I say – the instagram of it’s time). I kept twitter for personal/ creative use, rather than posting family pics, baby photos etc., but the fact that it had a permissions system meant that I could restrict content to people marked as friends if I wanted to. I’m not really using flickr now, and am shortly to let my pro membership expire – it doesn’t offer me enough as a paid service, it’s hardly changed over the last few years, it feels clunky to use. Also, alarmingly it also seems to be full of really good photographers, which doesn’t fit in with my desire to post grainy camera phone pics of my food, like I now do on instagram.
I also dived into facebook in 2005 (I think), and pre-twitter, most of my friends were from the web industry, and I used it mostly like I do with twitter now, for joining in conversations mainly about building web things. As it became more mainstream, I started using it to keep in contact with old friends and current non-techie friends, and it became a strange mix. I was also getting friend requests from people i’d never met, and as facebook became more.. err… social, I started to trim my contacts down to only people I had met in real life. When twitter took off, many people had their twitter and facebook status updates synchronised, and this started to drive me mad, seeing the same things over and over, so one night I deleted pretty much all my web industry friends (all of them were on twitter anyway), stopped posting anything techie to my status updates and embraced it as a way of keeping up with non-techie/ web industry friends (old and current) and family.
My twitter use hasn’t evolved that much – I post less pictures of my food and coffee than I once did (as i’ve already mentioned, I have instagram for that now), but due to it only having basic privacy settings, I tend not to post any family pictures, and am pretty guarded about posting anything personal. It’s mostly for technical discussion, but is also social, as of course some of my web industry friends have become good friends out of work (but still tend to talk shop down the pub). The thing I still really hate about twitter is that there is no native “mute” function (although it exists in some twitter clients), which means that I tend to unfollow people if they get a bit noisy tweeting from a conference or something, then by the time you go back to follow them again, they’ve been offended and decided to unfollow you back! I have to say facebook is much better for dealing with this kind of thing – you can anonymously mute people, and it’s much easier to group people and select who sees what. Twitter has lists, and i’ve tried grouping people into lists, so I can choose to only see tweets from certain groups of people, but it has no prominence as a feature in the native twitter UI, and people feel sidelined if they are only on a list and not on your main timeline.
I was late to the party on this, only starting to actively use it in the last few months, but just like flickr back in 2005, I use it to explore my creative side (mediocre pictures of clouds, coffee and food), and as a kind of diary, to remind myself what I was up to, and where I had been. Instagram public profiles have just arrived, and this has made me feel unsure about how I want to use instagram. Even though initially my pictures were set to public, it still felt like a fairly private personal thing, that I just shared with a few friends and web industry aquaintances, so i’ve set it to private for the time being. I don’t really want or need to showcase my instagram pictures to the general public, but occasionally I will post them over to facebook or twitter. So not sure which way i’ll go on that – if I do choose to make it public, i’ll be less likely to post any family or personal stuff, and there’s only so many cloud pictures my instagram followers can take!
I recently added image uploading to Too Old To Skate, and not having set up a “normal” django site for a while, hit about every stumbling block possible, so here are a few notes. Please bear in mind there may be other, better ways to achieve this – i’d love to hear them.
Adding an Image field
This is achieved simply by adding an ImageField to your model, e.g.:-
photo = models.ImageField(upload_to='image_uploads', blank=True)
Separate static and media directories
The static folder is where your local site assets go e.g. CSS and Javascript. Locally these are served up from /static/ by the django dev server, and on a live site this should be set up as aliases to serve by your web server (in my case Apache).
The media folder is where user-uploaded files go, in subdirectories specified in ‘upload_to’ in your image field in the model. The root is configured in settings.py, but unlike the static folder you will need to do some configuration to get the local dev server serving files up from this directory (and its sub-directories). The location of the media root needs to be different to static root, which threw me slightly, though I guess it makes sense to keep your own static assets and uploaded media entirely separate.
To get the local dev server serving up files from /media and its subdirectories, add this to urls.py:-
# you'll need to add this if you aren't already importing settings
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Permissions
Permissions need to be set on your media folder to allow uploaded files to be saved. This depends on your set-up, but for me adding write permissions for group allowed apache + wsgi + python (whichever one of those it appears as?) to save files and create directories.
PIL and libjpeg
As usual this caused me massive headaches to get running both locally and on my web server, and as usual I tried so many things i’m not 100% sure which steps actually made a difference in the end!
On Wednesday, the day after my lightning talk at the Django meetup, I gave a talk “An introduction to Backbone.js“, at a newly formed javascript meetup, loosely based around the locality of southville in Bristol. This was an interesting experience as other than using Backbone.js on one project (largely written by other people, so I only really dipped into it to add stuff), when I was volunteered to do the talk by Andy Mcgregor, I didn’t actually know a great deal about Backbone!
When it came to the crunch, i.e. pretty much the day before the talk, I started searching for online tutorials that might demonstrate what I wanted to cover in the talk, and the first one that I found was Hello Backbone.js by Artur Adib, which provides a fantastic step through with a set of examples building up on the previous example. I created a little “To Do” list app based roughly on these examples.
I then found an excellent set of video tutorials called Introduction to Backbone.js, by Joe Zim, which run through some interactive examples for Models, Views, Collections, Routers and Ajax within backbone, which really helped the penny drop for me, and gave me a basis for my own live-coding examples. The audience (of about 20 people – not bad for a highly localised, highly niche meetup!), were a mixture of people who already know backbone and people who have never used it, but hopefully there was something useful there for everyone. On a personal level, being put under pressure to be able to demonstrate something, accelerated my backbone knowledge very quickly, to the point that I would confidently start my next project using backbone.
The moral of the story is – if you want to learn a new skill quickly, you don’t need to pay to go to a workshop – volunteer to do a talk instead! Even if you don’t want to do a talk, find your friendly local user groups (or friendly online user groups, if there’s none local to you), and get involved. I’m not knocking paid workshops – there’s a place for those and i’m sure some of them are good value for money, but i’ve always loved the way that the web community are happy to share their knowledge for free, and you really can find the knowledge out there without spending your hard earned cash! Being part of the web community provides valuable support too when you get stuck, something that doesn’t happen in the world of “traditional” paid training.
The next southville js talk is “An introduction to CoffeeScript” by Tom Holder on wednesday 12th July, kindly hosted again by SimpleWeb. Also keep an eye on the Bristol Web Folk calendar for upcoming web related events in Bristol – there’s loads!
Photo above nabbed from an instagram pic by Chris Mytton
On tuesday Potato Bristol hosted the Django Bristol and Bath User Group (DBBUG) lightning talks. It went really well and it was nice to have some technical content as well as the usual beer and chat. The turnout was great and so were the talks.
First up was Chris Hall – “Django from the outside in (and back again)” talking about his experience as a PHP/Drupal developer using Django on a project for the first time.
Second up was me, talking about my simple Django content management tool “Snippets” (shortly to be renamed as soon as I can think of something suitable, as googling around there are too many other similar projects under the same name). I was pleased by the response and interest in Snippets considering it is such a simple tool – mainly the result of an evenings experimentation. This gives me an incentive to develop it further, as it shows there is a demand for simple tools like these, especially if you just want to add a small amount of editable copy into a web app, but don’t want the overhead of a full CMS.
Ed Crewe then talked about “using eggs for managed release and deployment“.
Jamil Appa fron ZenoTech talked about “Using Django to front an application that makes
use of GPUs in the Cloud”.
Lastly Russ Ferriday from SponsorCraft, talked about the spray project.
Ed has kindly created a lanyrd page for the event. | https://rickhurst.co.uk/page/3/ | CC-MAIN-2018-34 | refinedweb | 2,296 | 61.9 |
Kirill Korotaev <dev@sw.ru> writes:> Additional negative sides:> - full isolation can be inconvinient from containers management point of> view. You will need to introduce new modified tools such as top/ps/kill and many> many others. You won't be able to strace/gdb processes from the host also.Ok. I have to pick a nit here. Needing all new tools top/ps/kill was an artifactof your implementation. Mine does not suffer from it.> - overhead when virtualization is off, result is not the same.> - additional args everywhere (stack usage, etc.)Agreed. When using a PID namespace the code always behaves the same.Which is with more arguments than the code used to have.However the code always behaving the same is a tremendous advantagefor maintainability.>>.> It has some other additional advantages:> - flexible: you can select full isolation or weak is required. I really believe> this is very important.I am willing to be convinced but so far there seem to be other solutionslike running gdb_stubs inside your container. To address most of the issues.In a fairly real sense mucking with a container from the outside appearsto be a sysadmin layering violation. >> The container is just an umbrella object that ties every "virtualized">> subsystem>> together.> Yep. And containers were what I wanted to start with actually. Not VPIDs.The historical linux approach is to build things out of tasks sharingresources that give the impression of containers not out containersand their children. I am still trying to understand why that modeldoes not work in this instance.Eric-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2006/2/8/248 | CC-MAIN-2017-13 | refinedweb | 286 | 51.34 |
libmawk_run_main.3libmawk - Man Page
run main parts of a script
Synopsis
#include <libmawk.h> void libmawk_run_main(mawk_state_t *m);
Description
The libmawk_run_main() attempts to take and parse the next input record and runs all main parts of the script that matches. If there are multiple full records in the input buffer, the process repeats until the buffer becomes empty or contains a partial record. If there is no full record in the buffer, the call returns with nothing done. The call itself never blocks, but the script may. The input buffer may be filled using the libmawk_append_input() call.
Argument m is a libmawk context previously returned by libmawk_initialize() or libmawk_initialize_stage3().
See Also
libmawk_initialize_stage(3libmawk), libmawk_initialize(3libmawk), libmawk_append_input(3libmawk),
Info
2009-08-10 libmawk manual | https://www.mankier.com/3/libmawk_run_main.3libmawk | CC-MAIN-2022-40 | refinedweb | 123 | 56.86 |
I'm trying to write a main method that proves the Monty Hall scenario with a for loop. The Monty Hall problem is based off of a probability riddle. You are playing a game where there are 3 closed doors, behind one is a car but behind the other two are goats. After you pick a door, the game host shows you one of the other doors that has a goat in it. He then asks if you want to change your guess. So say you first guess door 1, the host then opens door 3 to show you a goat so he asks if you want to switch your answer to door 2. Probability tells us that if you switch there is a 2/3 chance that you will win the car (not 1/2 like most people think at first). The object of my method is to prove this by using a for loop and running it a large number of times ( i used 1000000) to prove the percent of winning when switching is 66.7%. The problem is when I run my code I keep getting 50% as my output and I cannot see why.
Code Java:
import java.util.Random; public class MontySim { public static void main(String[] args) { Random ran = new Random(); int n = 1000000; int wins = 0; for (int i = 0; i < n; i++) { int winningNumber = ran.nextInt(3) + 1; int losingNumber = ran.nextInt(3) + 1; while (losingNumber == winningNumber) { losingNumber = ran.nextInt(3) + 1; } int firstSelection = ran.nextInt(3) + 1; while ((firstSelection == losingNumber)) { firstSelection = ran.nextInt(3) + 1; } int secondSelection = ran.nextInt(3) + 1; while ((secondSelection == firstSelection) || (secondSelection == losingNumber)) { secondSelection = ran.nextInt(3) + 1; } if (secondSelection == winningNumber) { wins ++; } } double percent = 100 * wins / n; System.out.print(percent + "%"); } }
Any thoughts on why I'm not getting 66.7%? I thought i set it up well. I have the random generator making 4 numbers, the door where the car is (winningNumber), the door the host shows you (losingNumber), the door your choose first (firstSelection) and the door you switch to (secondSelection). I also made while statements to make sure the that the value of losingNumber cannot be the same as winningNumber, as well as making sure the firstSelection cannot be the same as the losingNumber, as well as making sure the secondSelection cannot be the same as firstSelection or the losingNumber.
Thanks
Casey | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/7720-monty-hall-problem-simulation-printingthethread.html | CC-MAIN-2014-10 | refinedweb | 397 | 62.78 |
In this lxml Python tutorial, we will explore the lxml library. We will go through the basics of creating XML documents and then jump onto processing XML and HTML documents. Finally, we will put together all the pieces and see how to extract data using lxml. Each step of this tutorial is complete with practical Python lxml examples.
Prerequisite
This tutorial is aimed at developers who have at least a basic understanding of Python. A basic understanding of XML and HTML is also required. Simply put, if you know what an attribute is in XML, that is enough to understand this article.
This tutorial uses Python 3 code snippets but everything works on Python 2 with minimal changes as well.
Navigation:
- What is lxml in Python?
- Installation
- Creating a simple XML document
- The Element class
- The SubElement class
- Setting text and attributes
- How do you parse an XML file using LXML in Python?
- Finding elements in XML
- Handling HTML with lxml.html
- lxml web scraping tutorial
- Conclusion
What is lxml in Python?
lxml is one of the fastest and feature-rich libraries for processing XML and HTML in Python. This library is essentially a wrapper over C libraries libxml2 and libxslt. This combines the speed of the native C library and the simplicity of Python.
Using Python lxml library, XML and HTML documents can be created, parsed, and queried. It is a dependency on many of the other complex packages like Scrapy.
Installation
The best way to download and install the lxml library is from Python Package Index (PyPI). If you are on Linux (debian-based), simply run:
sudo apt-get install python3-lxml
Another way is to use the pip package manager. This works on Windows, Mac, and Linux:
pip3 install lxml
On windows, just use pip install lxml, assuming you are running Python 3.
Creating a simple XML document
Any XML or any XML compliant HTML can be visualized as a tree. A tree has a root and branches. Each branch optionally may have further branches. All these branches and the root are represented as an Element.
A very simple XML document would look like this:
<root> <branch> <branch_one> </branch_one> <branch_one> </branch_one > </branch> </root>
If an HTML is XML compliant, it will follow the same concept.
Note that HTML may or may not be XML compliant. For example, if an HTML has <br> without a corresponding closing tag, it is still valid HTML, but it will not be a valid XML. In the later part of this tutorial, we will see how these cases can be handled. For now, let’s focus on XML compliant HTML.
The Element class
To create an XML document using python lxml, the first step is to import the etree module of lxml:
>>> from lxml import etree
Every XML document begins with the root element. This can be created using the Element type. The Element type is a flexible container object which can store hierarchical data. This can be described as a cross between a dictionary and a list.
In this python lxml example, the objective is to create an HTML, which is XML compliant. It means that the root element will have its name as html:
>>> root = etree.Element("html")
Similarly, every html will have a head and a body:
>>> head = etree.Element("head") >>> body = etree.Element("body")
To create parent-child relationships, we can simply use the append() method.
>>> root.append(head) >>> root.append(body)
This document can be serialized and printed to the terminal with the help of tostring() function. This function expects one mandatory argument, which is the root of the document. We can optionally set pretty_print to True to make the output more readable. Note that tostring() serializer actually returns bytes. This can be converted to string by calling decode():
>>> print(etree.tostring(root, pretty_print=True).decode())
The SubElement class
Creating an Element object and calling the append() function can make the code messy and unreadable. The easiest way is to use the SubElement type. Its constructor takes two arguments – the parent node and the element name. Using SubElement, the following two lines of code can be replaced by just one.
body = etree.Element("body") root.append(body) # is same as body = etree.SubElement(root,"body")
Setting text and attributes
Setting text is very easy with the lxml library. Every instance of the Element and SubElement exposes two methods – text and set, the former is used to specify the text and later is used to set the attributes. Here are the examples:
para = etree.SubElement(body, "p") para.text="Hello World!"
Similarly, attributes can be set using key-value convention:
para.set("style", "font-size:20pt")
One thing to note here is that the attribute can be passed in the constructor of SubElement:
para = etree.SubElement(body, "p", style="font-size:20pt", id="firstPara") para.text = "Hello World!"
The benefit of this approach is saving lines of code and clarity. Here is the complete code. Save it in a python file and run it. It will print an HTML which is also a well-formed XML.
from lxml import etree root = etree.Element("html") head = etree.SubElement(root, "head") title = etree.SubElement(head, "title") title.text = "This is Page Title" body = etree.SubElement(root, "body") heading = etree.SubElement(body, "h1", style="font-size:20pt", id="head") heading.text = "Hello World!" para = etree.SubElement(body, "p", id="firstPara") para.text = "This HTML is XML Compliant!" para = etree.SubElement(body, "p", id="secondPara") para.text = "This is the second paragraph." etree.dump(root) # prints everything to console. Use for debug only
Note that here we used etree.dump() instead of calling etree.tostring(). The difference is that dump() simply writes everything to the console and doesn’t return anything, tostring() is used for serialization and returns a string which you can store in a variable or write to a file. dump() is good for debug only and should not be used for any other purpose.
Add the following lines at the bottom of the snippet and run it again:
with open(‘input.html’, ‘wb’) as f: f.write(etree.tostring(root, pretty_print=True)
This will save the contents to input.html in the same folder you were running the script. Again, this is a well-formed XML, which can be interpreted as XML or HTML.
How do you parse an XML file using LXML in Python?
The previous section was a Python lxml tutorial on creating XML files. In this section, we will look at traversing and manipulating an existing XML document using the lxml library.
Before we move on, save the following snippet as input.html.
<html> <head> <title>This is Page Title</title> </head> <body> <h1 style="font-size:20pt" id="head">Hello World!</h1> <p id="firstPara">This HTML is XML Compliant!</p> <p id="secondPara">This is the second paragraph.</p> </body> </html>
When an XML document is parsed, the result is an in-memory ElementTree object.
The raw XML contents can be in a file system or a string. If it is in a file system, it can be loaded using the parse method. Note that the parse method will return an object of type ElementTree. To get the root element, simply call the getroot() method.
from lxml import etree tree = etree.parse('input.html') elem = tree.getroot() etree.dump(elem) #prints file contents to console
The lxml.etree module exposes another method that can be used to parse contents from a valid xml string — fromstring()
xml = '<html><body>Hello</body></html>' root = etree.fromstring(xml) etree.dump(root)
One important difference to note here is that fromstring() method returns an object of element. There is no need to call getroot().
If you want to dig deeper into parsing, we have already written a tutorial on BeautifulSoup, a Python package used for parsing HTML and XML documents. But to quickly answer what is lxml in BeautifulSoup, lxml can use BeautifulSoup as a parser backend. Similarly, BeautifulSoup can employ lxml as a parser.
Finding elements in XML
Broadly, there are two ways of finding elements using the Python lxml library. The first is by using the Python lxml querying languages: XPath and ElementPath. For example, the following code will return the first paragraph element.
Note that the selector is very similar to XPath. Also note that the root element name was not used because elem contains the root of the XML tree.
tree = etree.parse('input.html') elem = tree.getroot() para = elem.find('body/p') etree.dump(para) # Output # <p id="firstPara">This HTML is XML Compliant!</p>
Similarly, findall() will return a list of all the elements matching the selector.
elem = tree.getroot() para = elem.findall('body/p') for e in para: etree.dump(e) # Outputs # <p id="firstPara">This HTML is XML Compliant!</p> # <p id="secondPara">This is the second paragraph.</p>
The second way of selecting the elements is by using XPath directly. This approach is easier to follow by developers who are familiar with XPath. Furthermore, XPath can be used to return the instance of the element, the text, or the value of any attribute using standard XPath syntax.
para = elem.xpath('//p/text()') for e in para: print(e) # Output # This HTML is XML Compliant! # This is the second paragraph.
Handling HTML with lxml.html
Throughout this article, we have been working with a well-formed HTML which is XML compliant. This will not be the case a lot of the time. For these scenarios, you can simply use lxml.html instead of lxml.etree.
Note that reading directly from a file is not supported. The file contents should be read in a string first. Here is the code to print all paragraphs from the same HTML file.
from lxml import html with open('input.html') as f: html_string = f.read() tree = html.fromstring(html_string) para = tree.xpath('//p/text()') for e in para: print(e) # Output # This HTML is XML Compliant! # This is the second paragraph
lxml web scraping tutorial
Now that we know how to parse and find elements in XML and HTML, the only missing piece is getting the HTML of a web page.
For this, the ‘requests’ library is a great choice. It can be installed using the pip package manager:
pip install requests
Once the requests library is installed, HTML of any web page can be retrieved using a simple get() method. Here is an example.
import requests response = requests.get('') print(response.text) # prints source HTML
This can be combined with lxml to retrieve any data that is required.
Here is a quick example that prints a list of countries from Wikipedia:
import requests from lxml import html response = requests.get('') tree = html.fromstring(response.text) countries = tree.xpath('//span[@class="flagicon"]') for country in countries: print(country.xpath('./following-sibling::a/text()')[0])
In this code, the HTML returned by response.text is parsed into the variable tree. This can be queried using standard XPath syntax. The XPaths can be concatenated. Note that the xpath() method returns a list and thus only the first item is taken in this code snippet.
This can easily be extended to read any attribute from the HTML. For example, the following modified code prints the country name and image URL of the flag.
for country in countries: flag = country.xpath('./img/@src')[0] country = country.xpath('./following-sibling::a/text()')[0] print(country, flag)
Conclusion
In this Python lxml tutorial, various aspects of XML and HTML handling using the lxml library have been introduced. Python lxml library is a light-weight, fast, and feature-rich library. This can be used to create XML documents, read existing documents, and find specific elements. This makes this library equally powerful for both XML and HTML documents. Combined with requests library, it can also be easily used for web scraping.
You can read up and learn more on web scraping using Selenium or other useful libraries like Beautiful Soup in our blog. | https://oxylabs.io/blog/lxml-tutorial | CC-MAIN-2022-05 | refinedweb | 2,001 | 68.36 |
Fighting with UNDO
On 12/11/2015 at 01:25, xxxxxxxx wrote:
Hello,
I have a lot of problems to make my UNDO work in my Scripts.
I follow the Rules in the SDK and I put UNDOTYPE_NEW after a funtion
and UNDOTYPE_CHANGE before something is changed.
Still the UNDO does not work correctly..In my current Script the Undo even
makes one Undo to much. So it undos even a change I made in the scene
before I run the Script.
Question:
I make a lot of Changes of Objects. Changing Visibility and selection in Objectmanager.
Do I need to make an Undo for any Change? Even If I change like 2 things in the Row like this:
doc.AddUndo(c4d.UNDOTYPE_CHANGE, shrinkwrapdeformer) shrinkwrapdeformer[c4d.ID_BASEOBJECT_GENERATOR_FLAG]=False doc.AddUndo(c4d.UNDOTYPE_CHANGE, shrinkwrapdeformer) shrinkwrapdeformer.SetName("HB_RetopoProjector")
I also wonder why we even have to make all this Undo stuff? It would be much better if by default any function would take care about undo. I dont see a reason why you would not want to add a Undo for any change. Maybe Instead of AddUndo we could only have a RemoveUndo. Not sure if that makes sense.
But for many of my Scripts I have more work making the Undo work than writing the Script itself.
greetings, Holger
On 12/11/2015 at 02:36, xxxxxxxx wrote:
Well, undos are a complicated thing. You don't want them to eat too many processor cycles or memory, so they must not be created arbitrarily. You also don't want the undo structure to get too complicated or too granular - the user should not need to press the Undo key twenty times after an action.
Simply spoken, functions cannot have a built-in undo because the overhead would be enormous and the granularity absurd. Remember that the API functions that you call are also the internal functions of C4D, so if every function would have some built-in undo, C4D would generate tons of undos internally, even in hierarchical calls (functions calling other functions calling more functions) because a function is not aware of the context it is called in.
That is why normally you have a structure like this (mind you, this is an abstract concept and not necessarily exactly the thing C4D does) :
User does something | | GUI responder (window, button, menu...) | | GUI-level function (takes care of undos) | | Internal functionality (multiple complex calls)
So, you have a dedicated layer for handling the GUI itself (including the abstraction Windows/Mac, as well as mutual dependencies of GUI elements), a dedicated layer for the undos (and notifications to the threads about changes, like EventAdd()), and a huge API of internal functions that don't need to worry about undos and can concentrate on providing functionality.
If you use CallCommand(), you are actually triggering functions on the GUI level, and have an Undo built-in (as far as supported).
If you write a script using the internal API, you do not have Undos, because these functions don't know what you want to achieve, where you are doing something temporary, or where it is necessary to keep data for a later restauration of an object during an undo. So, you are writing yourself a GUI-level function and are therefore responsible for setting correct undos.
On 12/11/2015 at 03:08, xxxxxxxx wrote:
Hi Holger,
I'm not sure, it would be a good idea to let C4D handle the undo-stuff automatically. While C4D could add a undo step for every change that is made, I'm pretty sure users wouldn't like that. Depending on the complexity of an operation, the user would have to do thousands of undo steps, to undo such operation.
How should C4D be able to detect the complexity of certain undo steps. The idea behind this system is, to give the developer the chance, to merge several operations into a single undo step (no automatism can do that), in the end leading to a better user experience.
Now, for your code:
I assume, you are using StartUndo() and EndUndo() correctly.
With these two functions you define one single, arbitrarily complex undo step.
But you are adding too many undo steps.
Basically with AddUndo(c4d.UNDOTYPE_CHANGE, op) you say, this object will be changed, regardless of the number of parameters you change. So in your situation, there's only one AddUndo() necessary.
On 12/11/2015 at 03:13, xxxxxxxx wrote:
Now, how to use the Undos best? First, you have the bracket calls StartUndo() and EndUndo(). These simply define what range of single changes (AddUndo()s) will be reverted when the user presses the undo key. They must match, so if your code runs over a StartUndo, it must also run over an EndUndo sometime later. That means no early exits from a function that opens a StartUndo!
Then there are many types of AddUndo()s that can be used within such a StartUndo/EndUndo bracket. Each determines the scope of the undo - the amount of data that C4D needs to remember to revert the change. For example, UNDOTYPE_BITS will create storage only for the bits of an object, which uses very little space, while UNDOTYPE_CHANGE_SMALL stores all the parameters, and UNDOTYPE_CHANGE stores even hierarchies, so it takes up more space. You call these AddUndos before you make the actual change because this way, C4D knows what state to remember.
Now I don't know the actual C4D source code, but I guess you can imagine it like this:
- C4D gets an AddUndo for a certain object
- C4D thinks "Hey, this thing here is going to be changed! I must remember it the way it used to be!"
- C4D creates a copy of that object and puts it into its Undo list
- Then you make changes to that object.
When the user presses the Undo key, C4D looks at its list, and goes through all the AddUndo nodes in reverse order from the last EndUndo to the StartUndo before it. Now it finds that AddUndo node, and restores the original object with this data. Once it reaches the StartUndo, it considers that Undo sequence to be done, and stops.
Any failure to match EndUndo and StartUndo will corrupt this list. Any use of the wrong AddUndo may cause C4D to store too little data for a complete reversal of the change. If you use an UNDOTYPE with a broader scope, you should be able to execute several changes to an object with only one AddUndo - but you need to watch out for functions that DO create undos by themselves.
Think about what you need in an undo to revert an action, and use the appropriate UNDOTYPE. Now I am not a Maxon programmer so maybe they can add to the matter (the documentation is giving some examples but more information is always welcome), but your example above should also work as
doc.AddUndo(c4d.UNDOTYPE_CHANGE_SMALL, shrinkwrapdeformer) shrinkwrapdeformer[c4d.ID_BASEOBJECT_GENERATOR_FLAG]=False shrinkwrapdeformer.SetName("HB_RetopoProjector")
But when in doubt, it may be best to test :-)
On 12/11/2015 at 03:39, xxxxxxxx wrote:
Hi Cairyn and Andreas, thanks a lot for the explanation. I think I completely misunderstood the Undo.
Of course I dont want to "store" all the operations I make in the Script. I usually want to undo the complete Script. But than from what you said I understand that I dont need to use any AddUndo.
But that does not work.
When I create an Object for example and I press undo the Object remains.
For example this Code. If I Undo the Script the Null Object remains.
import c4d
from c4d import gui
def main() : obj=doc.GetActiveObject() NullObj=c4d.BaseObject(c4d.Onull) NullObj.InsertBefore(obj) c4d.EventAdd() if __name__=='__main__': main()
On 12/11/2015 at 04:14, xxxxxxxx wrote:
Sorry, Holger,
that was probably a misunderstanding.
You need a full correct sequence of StartUndo(), one or more AddUndo() and EndUndo() for undo to work.
For your last piece of code, like so:
def main() : obj=doc.GetActiveObject() NullObj=c4d.BaseObject(c4d.Onull) doc.StartUndo() if obj is None: doc.InsertObject(NullObj) else: NullObj.InsertBefore(obj) doc.AddUndo(c4d.UNDOTYPE_NEW, NullObj) doc.EndUndo() c4d.EventAdd() if __name__=='__main__': main()
Here's one more complex example (note the comment in the beginning) :
import c4d from c4d import gui #Welcome to the world of Python # Undo examples; requires these selected objects # - a sphere # - a polygon object with some point selection # - a torus # - a video post effect # - an object named "child" and an object named "parent" def main() : objects = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_0) if len(objects) == 0: return sphere = None polyObject = None torus = None child = None parent = None for obj in objects: if obj.GetType() == c4d.Osphere: sphere = obj if obj.GetType() == c4d.Opolygon: polyObject = obj if obj.GetType() == c4d.Otorus: torus = obj if obj.GetName() == "child": child = obj if obj.GetName() == "parent": parent = obj doc.StartUndo() if sphere is not None: doc.AddUndo(c4d.UNDOTYPE_CHANGE_SMALL, sphere) sphere[c4d.PRIM_SPHERE_RAD] = 200.0 if polyObject is not None: doc.AddUndo(c4d.UNDOTYPE_CHANGE_SELECTION, polyObject) pSelect = polyObject.GetPointS() pSelect.DeselectAll() cube = c4d.BaseObject(c4d.Ocube) if cube is not None: doc.InsertObject(cube, None, None) doc.AddUndo(c4d.UNDOTYPE_NEW, cube) if torus is not None: doc.AddUndo(c4d.UNDOTYPE_DELETE, torus) torus.Remove() rd = doc.GetActiveRenderData() videoPost = rd.GetFirstVideoPost() if videoPost is not None: doc.AddUndo(c4d.UNDOTYPE_BITS, videoPost) videoPost.SetBit(c4d.BIT_VPDISABLED) if child is not None and parent is not None: doc.AddUndo(c4d.UNDOTYPE_HIERARCHY_PSR, child) child.Remove() doc.InsertObject(child, parent, None) doc.EndUndo() c4d.EventAdd() if __name__=='__main__': main()
On 12/11/2015 at 04:17, xxxxxxxx wrote:
um, that's not what I said at all...
You need StartUndo, EndUndo, and a certain number of AddUndos that cover the changes you make.
In certain cases, one AddUndo can cover more than one operation.
But you still need to tell C4D what you want to undo.
On 12/11/2015 at 05:15, xxxxxxxx wrote:
Thanks Guys, I think I have just a wrong understanding of "Storing" Undos...If the function would be called RemoveUndo or IgnoreUndo it would be clearer to me. AddUndo for me means that the current State of an objects gets saved so if the user presses Undo this state will be recovered because its in the Undolist. But it seems its quite the other way around. If I AddUndo that means that the current state gets not added to internal Undolist.
NeverMind Guys...I will just plainly do it how its supposed to. If I have issues I guess I will just need to find the Problem and deal with it.
Thanks again.
On 12/11/2015 at 05:29, xxxxxxxx wrote:
Hi Holger,
no, I think, you are still confused. Actually it is pretty much like you describe for AddUndo:
AddUndo for me means that the current State of an objects gets saved so if the user presses Undo this state will be recovered because its in the Undolist.
And it's NOT the other way round, so it shouldn't be called RemoveUndo(), either.
Perhaps check and play with the examples I posted. | https://plugincafe.maxon.net/topic/9203/12227_fighting-with-undo/1 | CC-MAIN-2020-10 | refinedweb | 1,866 | 64.51 |
<< Back to Course Outline
Contents
Introduction
We have looked a little into the background behind object oriented programming, and some of the fundamentals of classes, objects, attributes, and methods.
Don't expect it all to sink straight in - it's pretty different to traditional programming languages, but the best way to learn is to go over it again, and look at some more examples to help it sink in.
So that's what we'll be doing this week.
We'll be exploring some new territory such as the idea of inheritance, Nested Classes, and importing classes so we can use them.
However, we'll be doing a lot more hands-on work to get us used to working with the Java language.
So here goes...
Session 2 Summary
In Session 2, we covered:
Variables (Attributes)
Integers
Strings
Case-Sensitivity
Arrays
Testing variables with QuickCup
What are classes and objects
Methods and attributes
The bike class
Bike attributes
How a method is declared
Creating bike objects
Accessing objects - array example
Getting information back from a method - return values
Amending TextBurst example to alter its speed from HTML page
The getParameter method
The parseInt method (converting strings to integers)
Standard Java Documentation
Session 3 Overview
In session 3, we will be looking at:-
Summary from Session 2 incl. recap on object orientation.
Session 3 overview
Code style - comments and indentation.
Inheritance and the Applet.
Example class - the JLabel.
Amending the TextBurst sample to add a second JLabel.
Scope
Libraries, and importing classes
Nested Classes
Adding a dynamo to our Bicycle
<<break>>
Create a simple 'pair matching' game using buttons
Summary and Further Sources
Code Style - comments and indentation
You may have noticed in the various Java source code listings, descriptive text littered around.
For example, at the beginning of the TextBurst.java file (open up the TextBurst project from within QuickCup to look at it) there's a copyright notice and a history of changes made to the source code. A history is useful to let you know how and why the program has changed over time, and if other people are going to use your code, possibly who changed it.
/*
** TextBurst sample applet
**
** by (c) Copyright 2005 Simon Huggins
**
** For demonstration purposes only.
...
** Change History
** ~~~~~~~~~~~~~~
** 17-Sep-2001 v1.0 Release version
** 24-Sep-2001 v1.1 Alter speed
** 30-Sep-2001 v1.2 Second label
*/
Comments are a useful way to record information in a source code listing to give information about the code. Another use is to place information near where something is happening to explain why the code is there, or what it does. e.g.
/* If the font size reaches max or 2, reverse the direction of shrinking / growing */
if ((fontSize==maxFontSize) || (fontSize==2)) fontDirection = -fontDirection;
To record a comment, start your comment anywhere in your code with the characters /* and then when your comment ends, put in the characters */
As you can see, these comments can go over several lines, or just one line.
If you want to add some comments to the end of a line, add the characters // to the end of your line, and then put in your comments. Note that the comments automatically stop at the end of the line, so this type of comment is no use if you have several lines of description to include. E.g.
theLabel.setFont(new Font("Helvetica",Font.BOLD,fontSize)); // change the font size
Using comments to try things out
Another use for comments is to test a variation without removing the original version. For example, we might want to look to see what the font would look like in italics instead of bold. We might 'comment out' the Font.BOLD parameter by making it into a comment, and then placing Font.ITALIC straight afterwards - e.g.
theLabel.setFont(new Font("Helvetica",/*Font.BOLD*/Font.ITALIC,fontSize)); // change the font size
This means that Font.BOLD will now be ignored. If we like the effect, we can then delete the comment. If we don't, we can delete the /* and *.Font.ITALIC to leave the original code.
Indentation
Indentation is used to offset blocks of code. Thus, you will find that lines that are aligned vertically down the page, are all in the same block of code, and so will be related.
Blocks of code tend to start with a { and end with a } and are typically used when defining a class, method, loop, or condition. If you don't know what this means, don't worry - we'll get onto this later.
You'll typically find that when you find a new { to define a new block, the following lines of code are indented a little further to the right, and when the } is reached, lines following this code are indented back to the left a little.
The indentation is not compulsory - people just do it to make following their programs a little easier. Typically, each extra level of indentation (e.g. block within a block) is represented by about two or three spaces (presses of the space bar).
Sometimes, if a line of code is too long, you may wish to continue it to the next line. It is common to see the following line indented a little, to show that the second line is really part of the first line. It's rare you'll see this, as most programmers will simplify the line of code by splitting it down into smaller steps.
Inheritance
Following on from our discussion in the last session about classes and methods, one other important part of object orientation is the idea of Inheritance.
In terms of our bike, we may have defined a nice bike which can be made to go faster by pushing the pedal, or slower by clasping the handle.
However, we may wish to have versions of the bicycle with customizations. For example, a different model with an electric motor.
Rather than specify the class all over again, it is possible to create a new class based on the original class, and just add a few bits to customize it.
Sounds great - less work!
The way this is done is to use the extends keyword when defining our class - e.g.
public class
ElectricBike extends Bicycle {
private double batteryLevel = 100;
public getBatteryLevel() { return batteryLevel; }
}
Magic! So if we wanted to create an ElectricBike object now:-
ElectricBike mynewbike = new ElectricBike();
system.out.writeln("Battery is at "+mynewbike.getBatteryLevel());
system.out.writeln("And push the pedal for speed "+mynewbike.pushOnPedal());
You can see that not only can you get at the methods defined in the ElectricBike class, you can also get access to those defined for the original Bicycle.
When people talk about inheritance, they often lapse into jargon - here's a few terms you may come across:-
Parent or Superclass - Bicycle is the parent or superclass of ElectricBike.
Child or Subclass - ElectricBike is the child or subclass of Bicycle.
Ancestor - If we had another class called SoupedUpElectricBike which extended the functionality of ElectricBike, then Bicycle would be the Ancestor of both ElectricBike and SoupedUpElectricBike, but only ElectricBike would be the parent of SoupedUpElectricBike.
Descendant - Conversely, both SoupedUpElectricBike and ElectricBike would be the descendants of Bicycle, but only EletricBike would be the child of Bicycle.
Don't worry too much about the terminology. If someone starts sprouting on about it, take a look back at your notes to see if it's any clearer!
Applet and Inheritance
When you create an applet, what you're really doing is taking a class called JApplet and extending its functionality to do something more useful than display a grey box on a web page. So you are creating a subclass of JApplet whenever you are creating a new applet of your own. If you look at the TextBurst example, you can see that the class is defined as follows:-
public class TextBurst extends JApplet implements ActionListener {
...
}
So, our TextBurst class is creating a new class, which takes on all the functionality of a JApplet class, and adds a bit more to do something useful.
Take your eyes away from the part that says implements ActionListener - this is reserved for the next session, where we start looking at the concept of the Interface and how it relates to event-handling in Java.
Example class - the JLabel
A lot of classes have been created for you to use in your programs.
For example, there is a class called JLabel. You could extend its functionality to do something else if you liked, but in general, we just want to put lots of different JLabel objects into our applet. Take the TextBurst example. First, we state that we will have an object called theLabel which will be an example of a JLabel class, holding its own data.
JLabel theLabel;
Then, we need to create a new JLabel to hold some text:-
theLabel = new JLabel(burstText,SwingConstants.CENTRE);
and finally, we add that label to the applet:-
getContentPane().add(theLabel);
All well and good. You can guess from the last statement that the getContentPane() method is a method inherited from (i.e. exists in) the JApplet class. This is the case. It passes back what is known as a Container object as used by the Applet, which is where all of your buttons and labels etc. go. Thus to add the JLabel to the Applet's container, you call a method called add from the Container class. Read through this a few times to get your head around it:-
JApplet defines a method called getContentPane(),
getContentPane() returns a value, which is an object. The object belongs to a class called Container which relates to areas on the screen that can hold various different 'controls' such as buttons, labels, edit-boxes and check-boxes.
The Container class has a method to add a 'control' to the container - the method is called add.
Thus, this statements gets the container for the applet, and adds a label to the applet. Phew! Reread this a few time to try and get your head around it!
Amending the TextBurst sample to add a second JLabel
We can add a second JLabel to the TextBurst class for effect. However, you can open the changed class and try it yourself, and we'll go through the changes made in class. You will need to open the TextBurst project from the session3 directory.
One important note - when adding the labels, we now have to state where in the container we want the label to go - NORTH for the top, SOUTH for the bottom. This will be explained in further details next session when we look at the Java Layout mechanism.
Try swapping the following two lines around:-
getContentPane().add(theLabel,BorderLayout.NORTH); // and add it to the applet at the top
and
getContentPane().add(theLabel2,BorderLayout.SOUTH); // and add at bottom of applet
Do you notice a difference in how the applet runs? Try swapping the lines back, until you see the difference.
Scope
Scope refers to where attributes and methods are available.
In general, each extra 'layer' of complexity has access to the previous layer's information. However, the next less complex layer does not have access to the more complex layer unless that layer is made public.
For example, our class Bicycle has a private attribute called speed. If we go outside of the class, and create an object of type Bicycle, then the details of how the Bicycle works are now hidden to us, and we communicate purely using the methods of the Bicycle class, as all of the attributes are hidden. An example that because the attributes are not made public, the simpler layer does not have access.
However, the pushOnPedal procedure goes into more depth - i.e. is within the Bicycle class, and so has access to the speed attribute of the Bicycle class. Similarly, because the Dynamo object is within the Bicycle class, it can access the attributes of the Bicycle class. It couldn't do that if it was declared outside of the class.
Another way of looking at scope is that if you are part of an object, then you should have access to the object's information as you are working with it, and can be trusted to do the right thing. However, if you are working outside of it, then you should only know how to feed information into and out of it - like a black box.
Libraries, and Importing Classes
Java is a monumental language in that it has a huge number of classes already defined. To use these classes, your program must ask to see them. For this task, you use the import keyword, followed by the class you wish to use. e.g.
import Bicycle;
to use the Bicycle class from another of your classes - we will be doing this later with a class called RideBike.
Classes are sometimes grouped together and stored in a single file. This file is called a library. To access all of the classes in a library, rather than naming each one individually, you can use the following notation:-
import java.awt.*
The * is shorthand for everything and is known as a wildcard. It is also used in various other aspects of computers, such as selecting filenames (an aside).
So, in this case, we will be able to get at every class in the java.awt library (this is the Java Abstract Windows Toolkit which we'll be discussing later in the course).
Technical note about class paths
Note that libraries must be able to be found in something called the CLASSPATH. This is an environment variable (which means a variable held outside of the Java application, and available to all applications on the computer) which gives a list of the directories in which classes (ie. files ending with .class or ZIP file libraries) may be found. To see what the CLASS PATH is currently set to, in the QuickCup application, hover your cursor over the CLASSPATH check-box. A tool-tip is shown which shows the current CLASSPATH environment variable. Note that each path is separated by a semi-colon (;). Also note, that usually one of them is the directory . (single dot) - this means the current directory. Thus, if you compile on class file, and then compile another class file in the same directory that imports the first class file, it will be found, because it is in the same directory. If you wish to use the current CLASSPATH in QuickCup, you will need to check the check-box. Alternatively, the default is set to standard subdirectories within the Java SDK path, and the current directory. You can add extra directories to this by typing a list of classes in the text box labelled Class Paths. Note that these are not semi-colon separated - type one path per line.
Nested Classes
If the main class were declared as private then it would not be able to be used outside the Bicycle.java file. As this would be pointless, this is not allowed.
Note also, that you can only have one class per file - it must match the filename for the file. So when would we use private classes then? Well, imagine that later we wanted to include more information about the dynamo within the class - for example, when it was put in, the force it exerts against the wheel to make it more difficult to pedal etc.
To make things neater, we may want to create a new class to represent the dynamo (which we have done in the next example).
However, we may not want the dynamo to be accessible outside the bike, because it's a part of the bike and shouldn't be tampered with. In this case, we may decide to create a private class within the Bicycle class. This is called an nested class because it's nested inside another class.
This means theoretically that you could construct your whole program within your applet (the outer class), just by creating attributes, methods, and nested classes within the applet to structure everything. Takes a bit to get your head around, that one!
In the following example, we have declared the Dynamo class inside the outer (Bicycle) class as follows:-
private class Dynamo {
private double brightness = 0.0;
public void setBrightness() { brightness = speed / 2; }
}
So when a new Dynamo object is created, it will have an attribute called brightness which is accessible only within the Dynamo - not by the Bicycle! Thus, the only way to set it is to use a method, in this case called setBrightness, which sets the brightness to be the bike's speed divided by 2.
Adding a dynamo to our bicycle
Take a look at the project named session3_apps.qjp - it contains a modified Bicycle class to include the dynamo as an inner class.
It also includes a new class called RideBike.java
If you look at this class, you can see that it imports the Bicycle class, and uses it, outputting the results to the console window.
Compile
the RideBike class as normal, but click on the
(Launch Java Application) button to launch the application - note this is not an
Applet, as it does not output to a web page.
Try taking out some of the comments (//) at the beginning of lines describing something that won't work, save, and try to compile again. Note the error message - does this make sense to you why this is an error? If not, ask the tutor.
As an exercise, you may like to try to create a method in both the inner and main Bicycle classes to get the dynamo value. Ask the tutor if you would like some help.
Creating a simple 'pair matching' game using buttons
The following listing shows a simple pair matching game (project named pairs.qjp) using another Java component called a JButton. This introduces some important topics such as branching (if statement), looping (for statement), event handling (the ActionListener interface), and random number generation (the random() method).
We shall discuss these in class a little this week, and go through them thoroughly next week.
and the HTML portion that calls the applet is:-
Try compiling and running the applet with the appletviewer. Try changing the squaresAcross and squaresDown parameters in the HTML web page to make the game harder/easier. Try changing the width and height parameters to see what happens to the buttons. Try dragging the edges of the appletviewer window to resize it, and see what happens to the buttons.
Note that this isn't yet a very sophisticated game. It has not scoring, and no feedback when you complete the game. You cannot restart the game, either, and you will need to quite to applet and restart it in order to play the game again.
Summary and Further Sources | http://www.simonhuggins.com/courses/javaweb/course_notes/week03/index.htm | crawl-001 | refinedweb | 3,144 | 61.67 |
I J2SE 5.0, or maybe Java 2?), I only used primitives in my code. At that time, I thought it was nice I could rely on the default values instead of having to initialize something before I could use it. I didn’t know too much about wrappers at the time, and didn’t think I had a good reason to look into them any further.
I don’t have any clear memories of when I started to use the primitive wrappers, but I do remember when JDK 1.5 allowed for the automatic conversions between primitives and their respective primitive wrapper classes or commonly known as autoboxing/unboxing. This was nice as it didn’t matter if an int was passed to a method requiring an Integer or vice versa. It was syntactic sugar that seemingly made programming a little easier.
Frameworks
Even though Java enterprise frameworks such as JSF and JPA do a lot of work for you, it also exposes some of the weaknesses of relying on autoboxing and primitives.
These frameworks rely on the use of the primitive wrapper class instead of the respective primitive. If you use the JPA tool to create an entity based on an existing table, the tool will use the wrapper for the variable type. JSF inputs and converters operate on objects. With JPA, it has to. Remember the primitive defaults? A primitive’s default value can be confused with what is stored in the database.
If long was used as a simple entity id, the entity would have a default value of 0L. 0L is technically a value, so it makes it difficult to know whether the entity has been persisted or not. If id is of type Long, then it is easy to tell if the entity has been persisted since the id can now be null and therefore representing an un-persisted entity.
//id is long and entity is not persisted long id = entity.getId(); //value of 0L Long id = entity.getId(); //doesn’t help, still 0L //id is Long and entity is not persisted Long id = entity.getId(); //null long id = entity.getId(); //what happens here? //reference:
Type Context
Primitive types do not adequately express the semantic context of the value. Let’s say we retrieve today’s temperature from a service and the returned value representing degrees is an int. Is it easy to determine what the context of int degrees is?
First, is the value represented in celsius or fahrenheit? Second, what if the value is 0? You would have to assume the value was actually set and it isn’t the default value of 0. You may wonder why it feels like 70 degrees outside when the service says it’s 0.
Instead of using a primitive or even a primitive wrapper, the best solution may be to use a custom object that resolves to a proper value. For our value representing temperature, we could create a Fahrenheit object. This object would remove all doubt on the context of the value.
// public class Fahrenheit { … private Integer degrees; … } Fahrenheit f = temperatureService.getDegrees(today); //
A developer wouldn’t be able to accidently pass in a Celsius object when the method is expecting Fahrenheit.
// … public Celsius convertDegrees(Fahrenheit f) { … } //only this would work Celsius c = temperatureService.convertDegrees(f); //
Using a primitive as a return value can also be ambiguous. Returning a boolean to represent if something worked or not doesn’t necessarily represent what did happen. Using a Result object is more descriptive by containing more information.
Mocking
While mocking frameworks can handle primitives, mocking frameworks like to work with objects. The code snippet below is the the Expectations class in JMock. As the code snippet shows below, some autoboxing magic is allowing the framework to set the expectation that a int value of 6 will be returned.
Expectations.returnValue(Object result): context.checking(new Expectations() { { atLeast(1).of(serviceMock).getPrimitive(5); will(returnValue(6)); …. }
JMock seems to handle primitive arrays properly since the object for arrays is dynamically created.
Expectations.returnValue(Object result): context.checking(new Expectations() { { int[] ints = { 2, 3 }; atLeast(1).of(serviceMock).getPrimitives(5); will(returnValue(ints)); …. }
Even though primitives and primitive arrays worked with mocking frameworks, it feels like you are not working with the real values. Your parameter is an int, but the mocking framework would like you to use Integer.
Thoughts
Looking back at the history of the primitive wrappers, the increased functionality of the wrappers over time, autoboxing/unboxing, and reading articles from developers from other languages, it feels like primitives could have been left out of the initial implementation of Java. Java is an object-oriented language, but contains non-object primitives. The autoboxing feature feels more like a band-aid than a real solution.
I am making this specific to enterprise applications due to the fact that enterprise applications have access to generous amounts of resources. The environment makes it easier to create descriptive code that use of objects like Integer and Fahrenheit. In constrained devices where garbage collection costs and heap size matter, primitives make sense and hold an advantage over object counterparts.
— John Hoestje, asktheteam@keyholesoftware.com
[thumbs-rating-buttons]
Interesting article and food for thought regarding application design. I’ve seen way too much code where the type context is left wanting, because good OO design was lacking. One thing, however…an application should not be designed to serve the testing tools. Testing tools should serve the application. Thus, I do not believe the challenges of mocking contribute to your point. Otherwise, I think this is an article that can be expanded in a follow-up, possibly even a discussion of specific primitive types and how each one compares to its wrapper.
Primitives are hard to work with, but their existence is fundamental to many things. I think in certain problem domains and at certain limited scale you can abandon primitives in favor of boxed types, but I can speak from absolute experience that when you’re deref is a tremendous cost, such as working with fast moving binary streams of data.
Staying on the stack is critical for memory pressure and cache coherence in many scenarios, and in fact I think the future of Java is to make primitives better citizens in the Java space. See:
Value Type Specialization:
Primitives in Streams:
Value Types:
Packed Objects:
Object Layout:
Admittedly, not all Java platforms are doing high-frequency trading or high-throughput low-latency network stacks, but it’s worth understanding the cost of just throwing it away. The apparent sheer number of people now using sun.misc.Unsafe (based on mailing lists, stack-overflow, etc) to get around the forced de-refs and sometimes wasteful data layout in Java heap is a sign that there is a need for this, and is where all of the above proposals were borne.
For the platform I run, I absolutely have to focus on every heap de-ref or indirection, every synchronized or atomic point of contention (what used to be “lock much?” has become “CAS much?”), every method that might not JIT. If we want to be able to use OO concepts at the rate we process data, we need those objects to not have spaghetti off to gobs of other objects.
At scale, pennies turn into dollars turn into servers 🙂
The same argument could be made for platforms like Minecraft where the sheer amount of math done to generate the voxel terrain would never manage even 2-3 FPS, let alone 60 with all boxed types. Just sneaking a couple boxed types into those tight loops, and the whole thing collapses.
On another point, one thing primitives offer that boxed types don’t is null-safety. While Java 8 finally adds Optionals, they are yet-another-heap-allocated-object, and so are often not really appropriate yet for being used at volume:.
(Java 9+ hopes to value type specialize optionals, which would allow them to be stack based whenever possible, but they aren’t now).
Java 8 also added the custom annotation-based type system, so you can start to use @NotNull in a standard way, which helps, but you have to be religious of its use, where-as primitives simply enforce it intuitively.
Now, all that being said, I force our payment platform to be 100% BigDecimal based so we have explicit (and strict) control of rounding and mathematical coersion, with no possibility of IEEE issues from the CPU. So I think that illustrates that problem domain matters.
So should they leave the language? Categorically No. Can certain problem domains operate without them? Almost certainly. Should Java get better explicit support for handling primitives? Absolutely – and that’s what I hope the above proposals will start to offer.
As is mentioned here having two roughly equivalent items auto convert when they are exactly equivalent can cause issues. If they are equivalent they should be identical as well. I vote against primitives as part of the language. All literals should be objects. | https://keyholesoftware.com/2015/02/23/do-primitives-need-to-go/ | CC-MAIN-2019-30 | refinedweb | 1,509 | 55.13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.