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 |
|---|---|---|---|---|---|
Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available as a free download by anyone, and can be downloaded as as both a VPC (allowing you to run it in a virtual machine) as well as a standalone setup install (note: if you are running Vista you want to make sure you only use the VPC version). You can download it here. :-)
cheers,
D
Hi Scott,
The automatic property feature looks great. I was just wondering, when it comes to adding say validation logic at a later date, will I have to rewrite the property and add my own private field, or will there be some way to access the automatically generated private field?
PingBack from
Alex Thissen, a teacher in the Nethelands, has written and excellent blog-serie about C# 3.0. Here's the last post with in the tail links to all the other posts:
Do you know if automatic properties work with the new get/set-specific protection levels?
One question: Is it possible to run the Orcas CTP besides VS2005 without problems on Vista?
Thanks,
Andreas
im glad to see some more ruby-like goodness is finding its way slowly into c#
Some suggested implementations ...
wow, I really love the property thing. Cant wait to get my hand on them
Scott,
Silly question perhaps, but why is the automatic properties feature a C# feature and not C# and VB.Net feature?
Great Post. Keep up the good work.
Why should we only use the VPC image with Vista?!
I have it installed on vista side by side with vs2005 and it works fine.
Will I have problems removing orcas?
This great! and a big time saver. I wonder with these features and DLINQ, simple application development may be in hands of Power Users rather then Programmers and Programmers will be spending more time doing more important stuffs.
Scott, if I correctly recall, the collection initializer syntax in some previous CTP's did not require the "new Person" inside the initialization list, it used to be even more compact since it was clear that the collection was for Person objects:
List<Person> people = new List<Person> {
{ FirstName = "Scott", LastName = "Guthrie", Age = 32 },
{ FirstName = "Bill", LastName = "Gates", Age = 50 },
{ FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
};
If this was the case, would you be able to explain why it had to be changed?
Yes yes yes! These are some great features!
thanks for the info. Really nice additions to the language.
BTW, it would be cool if we could attach a DebuggerVisualizer to an interface in Orcas. In VS2005 we can only do it to classes.
It will be helpful to have a built in code generator where we could specify just the property names it generates the code. (I gues one could do this now throeugh code snippets and visual studio extensions but I am curious as to what orcas has to offer)
Object Initializers are great in JavaScript and I am glad to C# is getting them as well.
Slightly (okay, _grossly_) off-topic, but...
Has anyone else found the Orcas downloads to be excruciatingly slow?
I usually get 1200KB/s (10mbps) from download.microsoft.com.
However, when I download any of the Orcas files, I get a maximum of 100KB/s -- it's like MS is throttling those downloads.
The entire set took over 2 days to download. Anyone else had this problem or found an alternative, faster place to download?
The automatic properties are an interesting idea but I don't think they will be all that useful in the real world. The problem is that I rarely have set accessors that say _firstName = value;
Instead, they usually say something like _firstName = value.Left( 50 ); to trim away data that won't persist to the database because of schema constraints. Or I might throw an exception in the setter if the data won't fit, for example.
What would have been really cool in the language is a feature that generates the backing field even if I put validation logic in the setter from the start. All you would need is a keyword that has special meaning in the setter, much like the value keyword. I want to write:
that = value.Left( 50 );
in the setter to mean set the unnamed backer field to the first 50 characters of the value.
I'm very excited for this new version of Visual Studio .NET! Any word on the pending release date/dates for beta/rc?
I'm sure there a million people looking forward to the JavaScript intellisence as I am...
Is there going to be any feature to minimize the javascript. It would be great to be able to remove comments, line breaks, and even rename local variables within .js files at build time.
I know you are the ASP.NET man..is there something like that already that can be hooked into the build proccess?
Great article, thanks. One thing mentioned that I don't truly understand is this new object initializers concept. Now, for me, my object classes have two constructors. One that accepts no parameters and just initializes all properties to blanks/zeros. The other constructor accepts all properties as parameters and sets them accordingly. It gets used like this:
Dim ThePerson as New Person("Bill", "Gates", 50)
Now that seems easier to me than:
Person person = new Person { FirstName="Scott", LastName="Guthrie", Age=32 };
The only true advantage I see from this new object initializer is that you can specifiy the properties in any order, whereas with the constructor they must be passed in the order in which the constructor expects them.
Is there something I am missing here? I am a VB developer, does C# not allow the use of constructors or what?
Thanks again!
Nice enhancements. With Orcas supporting multiple Framework versions, will the code above be compliled to the correct selected framework?
The enhancments are great, but I would avoid them if I need backwards framework compatible class designs.
These look like some great improvements. i am glad to finally get these over to vb. Nice work on improving the language
Felix:
I could be wrong, but I swear that I read that any DLL compiled in orcas would work in the current version of .net.
Ok now that's just scary.
I submitted my comment at 10:59 AM, and it was posted to the site around 12:20 PM, and at that precise moment one of my devs reported that the download speed throttled back _up_ to 10mbps.
Conspiracy? Coincidence? FATE?!
Portman: don't tell anyone, but I opened up the connection-speed just for you. :-)
P.S. Not really - it was just a coincidence. I've been able to get about 300-400kb/sec sustained from my cable modem.
It's quite interesting, especially considered against the fact that developers generate exactly the same amount of lines of code no matter what language, framework etc as long as they know the language equally good.
Everything that reduces the number of lines of code is therefore automatically interesting, however I think the uses of this feature is MARGINALLY at BEST...
And Scott, PLEASE don't write anything nice about VB, I read on theserverside.net that you're gonna cover also VB9...
Write the TRUTH!!
I think it's about time we get to kill this beast... :(
.t
Felix/Roger - all of the language features above will work with .NET 2.0 apps when using multi-targetting.
They don't require any special instructions nor libraries to support them.
If you use the LINQ libraries, though, or some of the new types in System.Core.dll then you can only run the code on .NET 3.5.
Hi SP,
Yep - in last year's May CTP you didn't need to specify the type name when using collection initializers, which meant you could write code like below:
{ FirstName = "Scott", LastName = "Guthrie", Age = 32 },
{ FirstName = "Bill", LastName = "Gates", Age = 50 },
{ FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
};
Although nice and terse, it did open up some interesting questions. For example, if you have a collection that is typed as a collection of Interfaces or Abstract Classes, what is the right behavior? Or, if you want to create a sub-class of a non-abstract class, what is the right behavior?
In the end the team decided to require that you specify the class name as part of the list in order to make it clearer.
Hi Josh,
If you have a class that already has constructors defined for all the parameters you want to pass in, then object initializers might not be super useful for your scenario.
Where they are useful is where you have a type that doesn't have overloaded constructors for everything (which is a super common scenario).
Note that you *can* use constructors and object initialization together. For example, the below sample would pass in one parameter as a constructor argument (assume there is a constructor for the firstname in my sample above), and two as properties:
Person p = new Person("Scott") { LastName="Guthrie", Age=32 };
P.S. You'll see that object initializers using properties also get very interesting when we start talking about anonymous types - which will be about 3 posts into my language series. With anonymous types you can easily "shape" data - which is super powerful for a lot of scenarios.
This is awesome! Can't wait to learn more about the new features! Keep up the great work.
Scott -
If I understood you right, these innovations that stemmed out of .NET 3.5/C# 3.0/VB 9, are now being applied to .NET 2.0 and .NET 3.0 via Orcas code generation. If true, that is a huge big deal (and wasn't hella obvious from reading your post at a glance).
I have 2 suggestions for (Orcas + 1).
Suggestion #1 -
-------------------
MSFT is doing a great job in the expression side of things by integrating designers with v.studio using the common platform of XAML.
I feel once you have the ADO.NET eF laid out, and innovations such as the above baked into .NET & VStudio, we could potentially benefit by integrating business analysts/project managers into the same fold as well. I strongly feel that PMs in the IT industry need to work with tools that integrate better with development tools (i.e. quit using MS Word to describe code).
Right now, business analysts create all kinds of UML diagrams, they follow some standard and non-standard methodologies to come up. This is a glorified process for Entity Shaping at heart. It would be nice if the medium they use to express those entity diagrams in (UML or otherwise and any number of softwares that do UML), were to port of a bit more directly to .NET entities.
Suggestion #2 -
The huge pink elephant that we are ignoring at this time, is entities that have validation logic in them. Entities with validation logic find it difficult to cross machine/process boundaries today - without sharing binary code.
I feel a company such as MSFT could pioneer a cross platform effort, that brings such validation logic in entities in a serializable form. Entities in literally any major OO language are shaped more or less with the same rules now. When you design stuff for SOA, the entities need to conform to a basic minimum cross platform standard anyway. It would be rather nice to embed validation - that becomes a part of the entity, and will have a mechanism to work on a cross platform basis using some kind of open specification.
And while you are at it, go ahead and add the ability to syntatically annotate Entities as well. Once you add syntactic capabilities, then finally you can address the problem of standardizing entities across business domains (We are talking year 2020 here), and then right after that is when machines take over the planet and kill human beings, total mayhem & blood all over, captain donut dies! (ok just kidding).
Anyhow, just 2-3 silly thoughts I had to share.
Good work :)
SM
Just what I have been looking for. Too often when building utility types it seems that the code gets fat due to repeated property blocks. With this candy it makes it much easier to copy- paste/paste/paste and rename a set of simple properties and have thime lay out in a very readably form. This makes teh important code easier to find and visually displays what is happening.
The initializers also make it easier to obtain a consistent look for repetitve common coding steps. This shuold help to eliminate some types of common keystroke errors and make the code more understandable.
In assembly languages we have always had macros to do some to do some of the grunt work. This performs a similar service. Enlisting the compiler is always a good idea in my book.
Great work on Orcas.
That's a nice little feature!
All this "property supporting garbage code" obfuscates useful code.
With "Automatic Properties" feature our classes would be much cleaner.
Interesting features, especially automatic properties, though I have to say off the cuff I prefer Delphi style of properties more, even though they are slightly more work. For example:
SomeClass = class(TObject)
private
_value: String;
public
property Value: String read _value write _value;
end;
Using that syntax is still cleaner than today's C# 2.0, you don't have to write an explicit getter/setter, you know the exact private variable name AND you can bind against it and at a future date swap out either the getter, setter or both without breaking anything. I think I would have prefered:
public class Person {
public string FirstName {
get _firstname; set _firstname;
}
}
OR even more strange:
public string FirstName -> _firstname;
I'm always looking for ways to reduce my code, so I'm down with these changes. Additionally, the object initialization is nice to see, and definately a move in the right direction.
As for properties, I don't care *that* much...I use resharper, which generates all my properties for me anyway.
Nice article scott, quick question, with the new object initialization, will it support positional parameters in addition to the named parameters? (similar to parameters on property attributes)
Ex
[DataFieldAttribute("Class_ID", TypeName=Number, PrimaryKey=true)]
Thanks!
Pwills: "Has anyone else found the Orcas downloads to be excruciatingly slow?"
I had a similar experience, but figured something was off - so I restarted the download after about 20 minutes and got a much improved speed.
Ok where did my comment go? :-/
Totally off-topic question.
What happened to the sample Wiki application that came with the early versions of Atlas? We were told it would return with later builds, but it disappeared...
Are all these 'New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers' things only a C# (which the title suggest) or will it be available from VB.net also ?
I would prefer to code C# but the company i work for only uses vb.net :(
/Søren
if I add a documentation comment to an automatic property, is it associated with the property, with the generated field, or both?
this is what I'd like to see in the new version of VS.
XPathMania
We use xml quite extensively and since it's native form is rarely useful enough we have to transform it. Having a quick/simple way to test our xpath in VS would be extremely useful. I can't get budget to buy xmlspy, and this is something that is clearly beneficial for all of us.
that's my wishlist.
Hi Scott, great blog.
I want to support Zack Jones.
Add automatic properties in VB too, something like this oneliners:
Public Get Set Property FirstName() As String
Public Get Set Property LastName() As String
Public Get Set Property Age() As Integer
Pingback from
The naysayers of these "small" features might fail to realize that these are steps towards a more declarative and expressive language. That is always a good thing.
The object and collection initializers are especially important. Not only do they wipe away some lines of code, they allow what previously demanded imperative constructs in an expression. That's huge! ...and necessary for what LINQ is trying to do with "queries" (another term for BLOCKED EXPRESSION. Keep in mind that these features (the two types of initializers) surely didn't exist merely because they seemed like a good enhancement. They were all but required to accomplish what LINQ aims to do.
As for automatic properties, this is clearly needed to attain something roughly resembling a tuple; another important requirement of LINQ.
None of these tweaks would be necessary of course if the language designers had just admitted that what they really needed were relations (tables) and such. As a D4 user, I'm spoiled though.
Automatic properties are definitely required in C# today, although stuff like ReSharper helps a lot to avoid the too-much-to-type effect of all C-based languages.
But this implementation seems a little bit dangerous. If I want an abstract property but forget the "abstract" keyword now I will suddenly have a valid statement.
Why not do it the Boo way? Put an attribute on the field instead, that autogenerates the property. You get both a property and a named field.
[Property("Name")]
private string _name;
These are really cool new features, I must say.
However I miss some examples on how to use the new stuff with VB9. p => syntax does not seem to exist in VB9, it must be something else right?
One question about Collection Initializers: Will it support IDictionary<TKey,TValue>?
Scott, thanks for the answer, I had thought that could be it, but I kind of wished that the compiler checked the declaring collection type and not require the type name if it was a concrete type, assuming all entries were for that type. If I tried to use an interface collection the compiler could reject. I think the concrete type case is way more frequent than the abstract one, so I hoped it could be handled differently. Anyway, thanks for thaking the time to explain it to us.
What I'd really like to see is to go a step further and allow a get or set to contain code - e.g. with a field that is only accessible by the getter or setter, e.g.:
public string FirstName
{
private string _firstName; // or implicit
get { return _firstName ?? ""; }
set;
}
This syntax allows lazy instantiation of the underlying field, and allows the compiler to catch typos in similar properties such as:
public string LastName
get { return _lastName ?? ""; }
public string MiddleName
get { return _lastName ?? ""; } // typo
See also:
Interesting features. I routinely code around those specific issues all the time. is my macro to encapsulate fields because typing all those curly-braces just gets old. The new feature here will be fantastic.
I have another macro that I use to generate a constructor to basically match the features of the object initializer. When I know I want a set of properties set on object creation, I simply highlight those fields in the IDE and run the macro. The macro creates the constructor with the set of arguments and assignments that I need.
And every custom collection I create has a constructor that takes an IList argument so I can populate the collection in initialization. This should have been a standard constructor in all collections.
So you have identified what are three of my own most common dealt with issues. At this rate, I may find myself with nothing to do but writing real business processes. I think that is a good thing. :)
Great job C# team!
No VB.NET support for automatic properties? Sigh.. perhaps
Public Automatic Property MyProperty As MyType
with no further code would be nice..
While I can see tremendous value in some of these new features, I am troubled at the direction in which Microsoft has apparently decided to move the .NET languages. In particular, implementing collection initializers by using any Add method, instead of relying on an interface, attributes, or keywords, signifies an intention to turn C# into a dynamic language. IMHO, this would be a terrible decision. See more discussion at
Pingback from <a href="">C# 3.0: The Sweet and Sour of Syntactic Sugar</a>
Great article. I would really like to appriciate the things makes easy to write and save a lot of code line. For me jajva script intellisense is a great addition to this. It will help a millions of developers to save a lot of their precious time while writing java script code.
One issue that i still face is converting inline styles into stylesheets. Is there any way to promote or manage the inline styles to stylesheets?
Pingback from Tobias Gurock ??? tobias.feedian.com » Blog Archive » Learning C# 3.0
Pingback from Arcadian Visions » Blog Archive » The Importance of a Name
The question “ Is Jasper useable from c#? ” came up on the Jasper forum . The short answer is – We designed
New "Orcas" Language Feature: Anonymous Types
I've been following Scott Gu's blog for news on what's new in Orcas. He has a "New in
Hace algunos días ya, bajé la máquina virtual con el Beta 1 de Visual Studio 2008
I wrote my first class with automatic properties in Orcas today... [DataContract(Name="FoodFact")]...
I'm very pleased to announce that the Beta 2 release of VS 2008 and .NET 3.5 Beta2 is now available
One of the big programming model improvements being made in .NET 3.5 is the work being done to make querying
Hi, Scott Guthrie, wrote a series of blog posts titled “ Using LINQ to SQL ”. Go have a look here . To
C# "Orcas" 新言語機能: 自動プロパティ、オブジェクトイニシャライザ、コレクションイニシャライザ | http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx | crawl-001 | refinedweb | 3,663 | 63.59 |
Mike Kelly's BlogFrom my Office to Yours Community 5.6.583.17018 (Build: 5.6.583.17018)2010-03-05T17:54:07ZTuesday Keynote @ Build Windows 8<p><em>Here are my notes from the Steven Sinofsky keynote at <a href="">BUILD</a>.</em></p> <p>Keynote started with a video of developers, designers etc. working on Windows 8 giving their favorite features in Win8.</p> <ul> <li>~450 million copies of Win7 sold (1500 non-security product changes seamlessly delivered)</li> <li>Consumer usage higher than XP</li> <li>542 million Windows Live sign-ins every month</li> </ul> <p><strong>Lots of change in Windows</strong></p> <ul> <li>Form factors/UI models create new opportunities (touch) <ul> <li>"People who say touch is only for small or lightweight devices are wrong. As soon as you use touch on a tablet, you're going to want to touch on your desktop & laptop."</li> </ul> </li> </ul> <ul> <li>Mobility creates new usage models – e.g. use while reclining on a couch</li> </ul> <ul> <li>Apps can't be silos - "customers want a web of applications" <ul> <li>Apps to interact easily</li> </ul> <ul> <li>Services are intrinsic</li> </ul> </li> </ul> <p>What is Win8?</p> <ul> <li>Makes Windows 7 even better - everything that runs on Win7 will run on Win8</li> </ul> <ul> <li>Reimagines Windows from the chipset (ARM work) through the UI experience <ul> <li>All demos shown today are equally at home on ARM and x86</li> </ul> </li> </ul> <p><strong>Performance / Fundamentals</strong></p> <p><em>Kernel Memory Usage</em></p> <table border="0" cellspacing="0" cellpadding="2" width="400"><tbody> <tr> <td valign="top" width="133">Win 7 RTM</td> <td valign="top" width="133">540 MB</td> <td valign="top" width="133">34 processes</td> </tr> <tr> <td valign="top" width="133">Win 7 SP 1</td> <td valign="top" width="133">404 MB</td> <td valign="top" width="133">32 processes</td> </tr> <tr> <td valign="top" width="133">Win 8 Dev Preview</td> <td valign="top" width="133">281 MB</td> <td valign="top" width="133">29 processes</td> </tr> </tbody></table> <h2><strong>Demos</strong></h2> <h3>User Experience (Julie)</h3> <ol> <li>Fast and fluid - everything's animated</li> <li>Apps are immersive and full screen</li> <li>Touch first - keyboard/mouse are first-class citizens ("you're going to want all three")</li> <li>Web of apps that work together - "when you get additional apps, the system just gets richer and richer"</li> <li>Experience this across devices and architectures</li> <li>Notes from Julie's demo</li> </ol> <ul> <li>Picture password - poke at different places on an image (3 strokes) to login</li> </ul> <ul> <li>Tiles on the home screen - each is an app - easily rearranged. Pinch to zoom in/out</li> </ul> <ul> <li>On screen keyboard pops up</li> </ul> <ul> <li>Swipe from right side to bring up Start screen - swipe up from bottom to get app menus ("app bar") - relevant system settings (e.g. sound volume/mute) also appear</li> </ul> <ul> <li>Select text in a browser - drag from right side to see "charms" - these are exposed by apps. One is "Share" - shows all apps that support the "Share contract". <ul> <li>Think of sharing as a very semantically rich clipboard.</li> </ul> <ul> <li>Target app can implement its own panel for information (e.g. login, tags, etc.) for sharing when it's the target.</li> </ul> </li> </ul> <ul> <li>Search <ul> <li>Can search applications, files - apps can also expose a search contract to make it easy for search to find app-specific data.</li> </ul> </li> </ul> <ul> <li>Inserting a picture <ul> <li>Shows pix on computer</li> </ul> <ul> <li>Social networking sites can add content right into picture file picker</li> </ul> </li> </ul> <ul> <li>Showed settings syncing from one machine to another machine she is logged in on that is an ARM machine.</li> </ul> <h3>Metro-style Platform/Tools (Antoine)</h3> <ul> <li>Current platform a mixed bag - silo of HTML/Javascript on top of IE, C#/VB on top of .NET & Silverlight, and </li> </ul> <ul> <li>Metro apps can be built in any language</li> </ul> <ul> <li>Reimagined the Windows APIs - "Windows Runtime" (Windows RT). <ul> <li>1800 objects natively built into Windows - not a layer.</li> </ul> <ul> <li>Reflect those in C#/VB.Net/C++/C/JavaScript</li> </ul> <ul> <li>Build your UI in XAML or HTML/CSS</li> </ul> </li> </ul> <ul> <li>Launch Visual Studio 11 Express - new app to build Metro apps. <ul> <li>Pick the language you want - pick the app template you want.</li> </ul> </li> </ul> <ul> <li>Enable millions of web developers to build these apps for Windows.</li> </ul> <ul> <li>Code you write can run either locally or in a browser from a web server - just JavaScript and HTML 5.</li> </ul> <ul> <li>New format - App Package - that encapsulates</li> </ul> <ul> <li>Use mouse or touch seamlessly - no special code.</li> </ul> <ul> <li>Modify button to bring up file picker dialog… <ul> <li>Also allows connecting to Facebook if the app that connects FB photos to the local pictures is there - every app now gets access to FB photos.</li> </ul> </li> </ul> <ul> <li>Adding support for the "Share" contract is 4 lines of JS</li> </ul> <ul> <li>Use Expression Blend to edit not just XAML but HTML/CSS. <ul> <li>Add an App Bar - just a <div> on the HTML page.</li> </ul> <ul> <li>Drag button into there to get Metro style where commands are in the app bar</li> </ul> </li> </ul> <ul> <li>Uses new HTML 5 CSS layout as Grid. Allows for rotation, scaling, etc. Center canvass within the grid.</li> </ul> <ul> <li>Expression lets you look at snapped view, docked view, portrait, landscape.</li> </ul> <ul> <li>58 lines of code total</li> </ul> <ul> <li>Post app to the Windows Store <ul> <li>In VS Store / Upload Package…</li> </ul> <ul> <li>Licensing model built into app package format. Allows trials.</li> </ul> <ul> <li>Submit to Certification <ul> <li>Part of the promise of the store to Windows users is the apps are safe and high quality.</li> </ul> <ul> <li>Processes can be a bit bureaucratic.</li> </ul> <ul> <li>Does compliance, security testing, content compliance.</li> </ul> <ul> <li>Will give Developers all the technical compliance tools to run themselves.</li> </ul> </li> </ul> <ul> <li>The Store is a Windows app. Built using HTML/JavaScript</li> </ul> </li> </ul> <ul> <li>Win32 Apps <ul> <li>Not going to require people to rewrite those to be in the store.</li> </ul> <ul> <li>Don't have to use Win8 licensing model.</li> </ul> <ul> <li>Give the Win32 apps a free listing service.</li> </ul> </li> </ul> <ul> <li>XAML / Silverlight <ul> <li>Using ScottGu sample SilverLight 2 app.</li> </ul> <ul> <li>Not a Metro app - input stack doesn't give touch access.</li> </ul> <ul> <li>How to make it a Metro app? <ul> <li>Runtime environments between SL and Win8 are different.</li> </ul> <ul> <li>Had to change some using statements, networkin layer.</li> </ul> <ul> <li>Reused all the XAML and data binding code - it just came across.</li> </ul> <ul> <li>Declare it supports "Search" and add a couple of lines of code.</li> </ul> </li> </ul> <ul> <li>Also can use same code on the Windows Phone.</li> </ul> <ul> <li>"All of your knowledge around Silverlight, XAML just carries across."</li> </ul> </li> </ul> <ul> <li>If you write your app in HTML5/CSS/XAML, it will run on x86/x64/ARM. If you want to write native code, we'll help make it cross-compile to these platforms.</li> </ul> <ul> <li>IE 10 is the same rendering engine as for the Metro apps.</li> </ul> <ul> <li>Can roam all settings across your Win8 machines - including you app settings if you want.</li> </ul> <h3>Hardware Platform (MikeAng)</h3> <ul> <li>8 second boot time - win7 pc.</li> </ul> <ul> <li>UEFI</li> </ul> <ul> <li>New power state called "Connected Standby" <ul> <li>Windows coalesces all the timer and network requests, turns the radio on periodically to satisfy them, then goes back to very low power consumption.</li> </ul> <ul> <li>But because app requests are getting satisfied they are up to date as soon as you press "ON"</li> </ul> </li> </ul> <ul> <li>USB 3 ~4x faster at copying a 1 GB file than USB 2</li> <li>Can boot Win8 from up to 256 TB drive.</li> </ul> <ul> <li>Direct Compute API - can offload compute loads to GPU</li> </ul> <ul> <li>Every Metro app has hardware acceleration UI baked in.</li> </ul> <ul> <li>Doing work with OEMs on testing sensitivity of touch hardware <ul> <li>Windows reserves only one pixel on each side for the Windows UI, so sensitivity important.</li> </ul> </li> </ul> <ul> <li>Down to 1024 x 768 for Metro apps. If 1366 x 768, get full Windows UI (side-by-side snap in). Any form factor - about resolution.</li> </ul> <ul> <li>Have a sensor fusion API - accelerameter, touch.</li> </ul> <ul> <li>NFC - near field communication - business card can have a little antenna built in to send data to Win8.</li> </ul> <ul> <li>Integrating device settings (web cam, HP printer, etc.) into Metro UI rather than as a third-party app.</li> <li>Ultra Books <ul> <li>Full core powered processor in a super-thin and light package.</li> </ul> <ul> <li>Some are thinner than legacy connectors - RJ45 and VGA - they are bumps.</li> </ul> <ul> <li>These things are mostly battery.</li> </ul> </li> </ul> <ul> <li>Samsung PC giveaway - to all BUILD attendees <ul> <li>64 GB SSD</li> </ul> <ul> <li>4 GB RAM (Steven: "so you can run Visual Studio")</li> </ul> <ul> <li>AT&T 3G included for one year (2GB/mo)</li> </ul> <ul> <li>Windows tablet + development platform.</li> </ul> <ul> <li>2nd generation core i5</li> </ul> <ul> <li>1366x768 display from Samsung - amazing</li> </ul> </li> </ul> <ul> <li>Refresh your PC without affecting your files <ul> <li>Files and personalization don't change.</li> </ul> <ul> <li>PC settings are restored to default</li> <li>All Metro apps are kept - others are removed.</li> </ul> <ul> <li>Command-line tool to establish base image for this for pros.</li> </ul> </li> </ul> <ul> <li>Hyper-V in the Windows 8 client</li> </ul> <ul> <li>ISOs get mounted as DVD drives.</li> </ul> <ul> <li>Multi Mon - <ul> <li>Screen background extends</li> <li>Task bar customizes to multi-mon - can have identical across two mons or have per-monitor task bar (show only apps running on that monitor)</li> </ul> <ul> <li>Ctrl/PgDn to switch Metro start screen between the two monitors - develop on one, test on another.</li> </ul> </li> </ul> <ul> <li>Keyboard works the same - type "cmd" from Metro Start screen and are in search for CMD.</li> </ul> <h3>Cloud Services (ChrisJo)</h3> <ul> <li>Windows Live mail Metro client connects both Exchange and Hotmail. <ul> <li>Full power delivered by ActiveSync.</li> </ul> </li> </ul> <ul> <li>Windows Live Metro calendar app.</li> </ul> <ul> <li>Bring together all the Friends through Linked In, Facebook, Windows Live.</li> </ul> <ul> <li>Photos <ul> <li>Connected to Facebook, Flickr, local photos.</li> </ul> <ul> <li>Written as a Metro app.</li> </ul> </li> </ul> <ul> <li>SkyDrive - 100 million people. <ul> <li>Every Win8 user, every Win Phone has a SkyDrive.</li> </ul> <ul> <li>Also accessible to developers - access the same way as you would use local store.</li> </ul> </li> </ul> <h2>Wrap</h2> <ul> <li>Used college interns to develop sample apps included in dev preview build.</li> </ul> <ul> <li>17 teams (2-3 devs per team).</li> </ul> <ul> <li>10 weeks.</li> </ul> <p>Developer Preview (not Beta).</p> <p>Learn more:</p> <ul> <li><a href=""></a></li> </ul> <p>MSFT will let everyone download the Developer preview starting tonight.</p> <p><a href=""></a></p> <ul> <li>X86 (32- and 64-bit)</li> </ul> <ul> <li>With Tools + Apps or just Apps</li> </ul> <ul> <li>No activation, self-support.</li> </ul><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Windows 8<p>I'm down in LA (OK, Anaheim actually...) for the <a href="" target="_blank">BUILD Windows 8 conference</a> - what was previously known as the "<a href="" target="_blank">Professional Developers' Conference</a>" (PDC) - not sure if the fact that it's changed names means that they want a broader appeal beyond just professional developers, but we'll see. At $1600-$2400 to attend (plus travel) I doubt too many hobbyists are coming.</p> <p>I'll be posting here my impressions from the keynotes and from the sessions I attend. There is a rumor that a new tablet with Win8 is going to be distributed to attendees - we'll see. <a href="" target="_blank">Microsoft gave an Acer tablet</a> <a href="" target="_blank">this video showing an absolutely amazing bootup time for Win8</a>. We'll see...</p> <p> </p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly BidNow to Work<p.</p> <p>I downloaded the <a href="">BidNow sample</a>.</p> <p>There are a set of automated scripts the developers of BidNow have provided to configure things, which is good and bad. It’s <strong><em>good</em></strong> in that the configuration is somewhat complex and the scripted PowerShell scripts take you through setting it up by asking you a set of questions, TurboTax-style. It’s <strong><em>bad</em></strong>="Error Setting up - 1-28-11" border="0" alt="Error Setting up - 1-28-11" src="" width="563" height="304" /></a></p> <p.</p> .</p> <p>The code apparently uses <a href="">AppFabric Labs</a>.</p> <p>I figured I’d just try the URL the page issues to retrieve the AppFabric Labs identity providers and see what I got. The URL is something like: (<i>spacing added for readability):</i></p> <pre>? protocol=wsfederation&realm=http%3a%2f%2flocalhost%3a8080%2f& reply_to=http%3a%2f%2flocalhost%3a8080%2fLogOn.aspx&version=1.0</pre> <p>It seemed wrong to me that it was referring to the <font style="background-color: #ffff00" face="Courier New">bidnow-sample</font> namespace within AppFabric labs, not the namespace I had created, so I figured that was probably one of the things that didn’t get updated by the scripts. However, plugging this URL into a web browser, I get this:<="image" border="0" alt="image" src="" width="431" height="173" /></a></p> <p>Hmm, so it’s not complaining about an invalid namespace, as I’d expect; it’s complaining about the <strong><em>realm</em></strong> <a href="">this page</a> which explains how to set up ACS with Windows Azure. It explains that when registering the “relying party application” with ACS, you have to specify the URI – I didn’t do that when I set up my AppFabrics lab info. (<a href="">This page</a> also has more in-depth information about “relying party applications” and the realm – one of the challenging things about learning any new technology like this is that there are a bunch of new terms which you have to first learn; a good resource here is the <a href="">December 2010 MSDN article “reintroducing” :) ACS</a>; I guess you have to write an article <em>re-introducing</em> something when the first documentation on this just led to ho-hums and scratching heads. But this article actually guides you through the necessary steps of configuring the ACS namespace and realm and all up on the AppFabrics Labs web site reasonably well.</p> <p.</p> <p.</p> <p>This got me past the first step – when I build and run the app and go to the BidNow home page and click “Login”, I now get a list of providers:<="327" height="221" /></a></p> <</a></p> <p>Hmm… Searching for this error on the web, I find a helpful explanation on acs.codeplex.com:</p> <blockquote> <p>The rule group(s) associated with the chosen relying party has no rules that are applicable to the claims generated by your identity provider. Configure some rules in a rule group associated with your relying party, or generate passthrough rules using the rule group editor.</p> </blockquote> <</a></p> <p>Now you would think that default rules would be, oh, I don’t know, <strong><em>defaulted</em></strong> but apparently not unless you click the button to generate them. Yup, I’m understanding more and more why they had to write an article <strong>re-introducing</strong> this service.</p> <p>After generating these, going back to my dev fabric hosted BidNow, I am able to login!</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly and Hyper-V<p>For a client engagement, I was provided VMWare images. I don’t have VMWare, but have a server running Windows Server 2008 R2 with Hyper-V. So I needed a conversion from the VMWare image to a Hyper-V image.</p> <p.</p> <p>Sure enough, I found a good <a href="">blog post</a>. </p> <p>But that gives me a virtual hard drive with the image – it doesn’t give me a virtual machine. Here are the steps to convert that from the VMWare virtual machine information provided:</p> <ol> <li>Download the <a href="">VMDK to VHD Converter</a> from <a href="">VMToolkit</a>. </li> <li>Use it to convert the VMWare VMDK (virtual disk image) to a Hyper-V VDK (virtual disk image). This creates a new file that is a sector-by-sector copy of the original virtual hard disk. </li> <li>Start Hyper-V Manager and click on your server name in the tree control on the left. </li> <li>Click New / Virtual Machine… and name it and configure memory/networking. </li> <li>When you get to step 4 (Connect Virtual Hard Disk), click the second option “Use an existing virtual hard disk” and point it at the VHD you created from the VMDK. </li> <li>Start the Virtual Machine. Depending on whether the virtual configuration is significantly different than the VMWare image you received, Windows may need to configure hardware and restart the VM – this will happen automatically.</li> </ol> <p>That’s about it – pretty easy migration from VMWare to Hyper-V!</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Pivot Table Missing a Column from Source Data?. </p> <p>I then went to pivot the data by clicking “Summarize with Pivot Table” in the “Table Tools” ribbon section, but the pivot table field list doesn’t contain my group column.</p> <p>At first I thought that maybe for some reason calculated fields wouldn’t be included in the pivot table – but this made no sense and there are are other calculated fields in my source data.</p> <p>After poking around a bit on the web, I found <a href="" target="_blank">this post</a>.</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Springsteen and Fred Brooks on Design<p>I’ve just been listening to <a href="">Ed Norton interviewing Bruce Springsteen</a> <a href="">Construx Software Executive Summit</a> last week (which was a great event).</p> <p>Springsteen put it this way:</p> <blockquote> <p>And I said man, there’s other guys that play guitar well. There's other guys that really front well. There’s other rocking bands out there. But the writing and the imagining of a world, that's a particular thing, you know, <strong>that's a single fingerprint.</strong> <strong>All the filmmakers we love, all the writers we love, all the songwriters we love, they have they put their fingerprint on your imagination and then on - in your heart and on your soul.</strong> That was something that I'd felt, you know, felt touched by. And I said well, I want to do that.</p> </blockquote> <p><a href="">Fred Brooks</a> (author of “<a href="">The Design of Design</a>”, and of course, famously, “The Mythical Man-Month”) put it a bit differently:</p> <blockquote> <p>“Great design does not come from great processes; it comes from great designers. Choose a chief designer separate from the manager and give him authority over the design and your trust.”</p> </blockquote> <p>Both are really saying the same thing – great, consistent, beautiful designs always come from a single mind expressing himself or herself.</p> <p.</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly 7 Homegroup and Domain<p>For a consulting project, I recently had to join my laptop to an Active Directory domain at a client's workplace. Suddenly, my home computers can no longer see the computer. I found that the laptop could see shared items on my home network, though.</p> <p>I went to the "Network and Sharing Center" to see if there was some setting I had to tweak and found this:</p> <p><img height="218" width="550" src="" border="0" /></p> <p>Hmmm... so I'm kinda/sorta still part of a homegroup, it sounds like. Searching for the message highlighted I found this Windows Online help topic that explains it: </p> <p><a href=""></a></p> <p>So it turns out that yes, you can see other computers from the domain-joined laptop, but the other computers on the homegroup can't see the domain-joined laptop any longer. I suspect this is a security thing.</p> <p> </p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly 2010 Always Trying to Send Messages<p.</p> <p>I found <a href="">this post</a>.</p> <p>There is a <a href="">$50 tool called OutlookSpy</a> (with a free 30-day trial) that was also mentioned and might help some folks who find the tool I used a bit too geeky.</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly to XML<p. </p> <p>To gather the data, I use a timer which I put into a simple value class:</p> <pre>); } }</pre> <p>Then I just have a list of these which I add to as I run each test:</p> <pre> static private List<TimerInstance> _Timers = new List<TimerInstance>();</pre> <p.</p> <p>This seemed super easy, but I found that serializing to XML is not as straightforward as I thought it would be.</p> <p>First, I added the <pre>[Serializable]</pre> attribute to the struct (as shown above). But what I ended up with was something like this:</p> <pre><?xml version="1.0"?> <ArrayOfTimerInstance xmlns: <a href=""</a>">"</a> </a> xmlns: <a href=""</a>>">"</a>> </a> <br /> <TimerInstance /> <br /> <TimerInstance /><br /> <TimerInstance /><br /> <TimerInstance /> <br /></ArrayOfTimerInstance></pre> <p>I couldn’t figure out why the public properties (Name and Ticks) of the items in the list weren’t getting serialized. </p> <p>After poking around a bit, I realized two things:</p> <ul> <li>The Serialize attribute has nothing to do, really, with XML Serialization – it marks the object as binary serializable which I wasn’t interested in for this. </li> <li>There is an interface, IXmlSerializable, you can implement on a struct or a class to control how XML serialization happens. </li> </ul> <p>So I modified my struct as follows:</p> <pre> }</pre> <p>and used this code to serialize it into a MemoryStream:</p> <pre> // Return items that should be persisted. By convention, we are eliminating the "outlier" // values which I've defined as the top and bottom 5% of timer values. private static IEnumerable<timerinstance><timerinstance>)); x.Serialize(s, ItemsToPersist().ToList()); } }</timerinstance></timerinstance></pre> <p. </p> <p>Once I have this, it's a pretty straightforward thing to store the memory stream in an Azure Blob using <a href="">UploadFromStream</a>: </p> <pre> //); } }</pre> <p>(Diagnostics is my own class to provide TraceSource-based logging to Azure). The only additional trick I needed here was to Seek on the MemoryStream to the beginning - I was getting empty blobs before I did that. </p> <p>The final result: </p> <pre><p><?xml version="1.0"?><br /><ArrayOfTimerInstance xmlns:</p><p>"</a></p><p> xmlns:</p><p> <a href=""</a">"</a</a>>><br /> <TimerInstance Name="Fibonacci Generation (Trace) 1" Ticks="468294" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 9" Ticks="410877" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 3" Ticks="402439" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 5" Ticks="388574" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 8" Ticks="385690" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 2" Ticks="385261" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 10" Ticks="376425" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 6" Ticks="345973" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 7" Ticks="339461" /><br /> <TimerInstance Name="Fibonacci Generation (Trace) 4" Ticks="331053" /><br /></ArrayOfTimerInstance></p><p> </p></pre><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Memory and Performance<p>There’s an <a target="_blank" href="">interesting article</a> about performance of server apps in the July 2010 Communications of the ACM somewhat provocatively titled “You’re Doing It Wrong”. In it, Poul-Henning Kamp, the architect of an HTTP cache called <a target="_blank" href="">Varnish</a>, describes the “ah ha!” moment (on a night train to Amsterdam, no less) where he realized that traditional data structures “ignore the fact that memory is virtual”.</p> <p.</p> <p. </p> .</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Mailing Addresses<p>To fix a problem with a <a href="">corrupted Outlook profile</a>,.</p> <p.</p> <p>After living with this for a bit, I pulled out my old “<a href="">VBA for Microsoft Office 2000 Unleashed</a>” (<em>yup, it’s been a while…</em>) and wrote a little Outlook macro to do the right thing here:</p> <pre</pre><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly With Outlook Connector Errors (80004005 and 4350)<p.</p> <p.</p> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Outlook 2010 Sync Error 2" border="0" alt="Outlook 2010 Sync Error 2" src="" width="372" height="393" /></a></p> <br /> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Outlook 2010 Sync Error" border="0" alt="Outlook 2010 Sync Error" src="" width="398" height="349" /></a></p> .</p> <p? <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="" /> .</p> <p>So for anyone else who runs into this, </p> <p>a. You can contact support at <a href=""></a> – for me at least it was no charge and pretty quick.</p> <p>b. You can try to create a new profile yourself - <a title="" href=""></a>.</p> <p>c. If you add a second account to the profile (e.g. an SMTP account) have it deliver to somewhere other than the same Inbox as the MSN/Hotmail account (e.g. “Work Inbox”). You can then <a href="">create an Outlook Search Folder</a> to consolidate mail from the two separate delivery folders. By isolating the SMTP inbox from the MAPI inbox that MSN/Hotmail is using, you apparently work around a problem that can lead to this problem.</p> <p>Good luck! <br /></p> <p> </p> <p><strong><em>UPDATE – June 30, 2010</em></strong></p> <p! </p> <p>After contacting MS support again and this time talking with Dinker, we figured it out. When creating a new profile, Outlook has a setting that (in Outlook 2010) you access through File / Account Settings in Outlook 2010:</p> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Outlook 2010 Account Settings - 1" border="0" alt="Outlook 2010 Account Settings - 1" src="" width="484" height="246" /></a></p> <br /> <p>There you’ll find a tab for “Data Files”. Windows Mobile Device Center syncs items in the <strong><em>default</em></strong> data file; below I have the dialog as it appears <strong><em>after</em></strong> I set the MSN data file as the default one, not the Outlook Data File:</p> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Outlook 2010 Account Settings - 2" border="0" alt="Outlook 2010 Account Settings - 2" src="" width="475" height="298" /></a></p> <br /> <p>Before I did this, “Outlook Data File” was set as the default data file so WMDC was syncing calendar and contact items from there. Note that this shows up in Outlook as separate calendars (“My Calendar” is the one syncing to Windows Live Calendar):</p> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Outlook 2010 Calendars" border="0" alt="Outlook 2010 Calendars" src="" width="191" height="339" /></a></p> <p>and as separate Contacts lists as well (obviously, “Contacts – <a href="mailto:mikekelly@msn.com">mikekelly@msn.com</a>” is the one synced with Windows Live):</p> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Outlook 2010 Contacts" border="0" alt="Outlook 2010 Contacts" src="" width="244" height="240" /></a></p> <br /> <p>Changing the default caused the WMDC to correctly sync.</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Development, or Working Remotely<p>I’ve come across a good new blog, <a href="">Coding Horror</a>, written by Jeff Atwood, one of the founders of one of my favorite coding sites, <a href="">Stack Overflow</a>. In reading through some of the older posts, I came across one that is close to my heart which is on <a href="">working remotely</a>,.</p> <p <a href="">Hyderabad, India</a>; <a href="">Beijing and Shanghai, China</a>; <a href="">Haifa, Israel</a>; <a href="">Dublin, Ireland</a>; and here in the United States in <a href="">Silicon Valley</a>, <a href="">Boston</a> and North Carolina; there also is a center in <a href="">Vancouver, British Columbia</a>. Due to acquisitions, there are also a number of smaller sites doing product development all around the world, including in Portugal, France, Singapore, Germany, Norway, and Switzerland.</p> <p.</p> <p>Jeff’s post offers a number of good solutions, as does <a href="">my former colleague, Eric Brechner</a>. .</p> <p>Ultimately, though, the goal isn’t pain but gain. Jeff’s and Eric’s posts referenced above have a number of good suggestions on how to achieve that. These come down to just a few basic rules:</p> <ul> <li><strong>Communicate, communicate, communicate.</strong> !”</li> <li><strong>Virtual tools are no replacement for real relationships.</strong> A friend once wrote a book on software development with a memorable rule: <a href="">“Don’t flip the Bozo bit”</a>,”.</li> <li><strong>Follow the basic rules of distributed systems.</strong> .</li> </ul><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Custom Performance Counters with Windows Azure Services<p>Windows makes available a wide variety of performance counters which of course are available to your Azure roles and can be accessed using the Azure Diagnostics APIs as I described in my recent <a href="">MSDN article on Windows Azure Diagnostics</a>.</p> <p>However, it can be useful to create custom performance counters for things specific to your role workload. For instance, you might count the number of images or orders processed, or total types of different data entities stored in blob storage, etc.</p> <p.</p> <p><font color="#c0504d" size="4">Custom Performance Counters aren’t yet supported in the Azure Cloud fabric due to restricted permissions on Cloud-based Azure roles (see </font><a href=""><font color="#c0504d" size="4">this thread</font></a><font color="#c0504d" size="4"> for details) so this post describes how it <em>will</em> work when it is supported.</font></p> <h2>Create the Custom Performance Counters</h2> <ol> <li>You create your counters within a custom category. You cannot add counters to a category, so you have to create a new performance counter category using <code><a href="">PerformanceCounterCategory.Create</a></code> in <code>System.Diagnostics</code>. The code below shows how to create a few different types of counters. Note that there are different types of counters: you can count occurrences of something (<code>PerformanceCounterType.NumberOfItems32</code>); you can count the rate of something occurring(<code>PerformanceCounterType.RateOfCountsPerSecond32</code>); or you can count the average time to perform an operation(<code>PerformanceCounterType.AverageTimer32</code>). This last one requires a "base counter" which provides the rate to calculate the average. <pre> //()); }</pre> </li> <li>When you create a performance counter category, you need to specify whether it is <i>single-instance</i> or <i>multi-instance</i>. <a href="">MSDN helpfully explains</a> that you should choose single-instance if you want a single instance of this category, and multi-instance if you want multiple instances. :) However, I found a <a href=" ">blog entry from the WMI team</a> that actually explains the difference - it is whether there is a single-instance of the counter on the machine (for Azure, virtual machine) or multiple instances; for example, anything per-process or per-thread is <i>multi-instance</i> since there is more than one on a single machine. As you can see, since I expect multiple worker thread role instances, I made my counters multi-instance. </li> <li>After creating the counters, you need to access them in your code. I created private members of my worker thread role instance: <pre> public class WorkerRole : RoleEntryPoint { ... // Performance Counters PerformanceCounter _TotalOperations = null; PerformanceCounter _OperationsPerSecond = null; PerformanceCounter _AverageDuration = null; PerformanceCounter _AverageDurationBase = null; ...</pre> </li> <li>Then in the code after I create the counter category if it doesn't exist, I create the members: <pre>()); }</pre> </li> <li>Note that I use "." for machine name, which just means current machine, and I use the <code>CurrentRoleInstance.Id</code> from the <code>RoleEnvironment</code> to distinguish the instance of each counter. If instead you wanted to aggregate these across the role rather than per-role instance, you could just use <code>RoleEnvironment.CurrentRoleInstance.Name</code>. </li> </ol> <h2>Using the Custom Performance Counters</h2> <p <code>Run</code> method of your role to do the work, and this method should not return - it instead runs an infinite loop waiting for work to do and then doing it. Let's look at some simple code to use the performance counters defined above: <table cellspacing="2" cellpadding="2" width="100%"><tbody> <tr> <td width="30%">_TotalOperations </td> <td width="70%"># worker thread operations executed </td> </tr> <tr> <td>_OperationsPerSecond </td> <td># worker thread operations per sec </td> </tr> <tr> <td>_AverageDuration </td> <td>average time per worker thread operation </td> </tr> <tr> <td>_AverageDurationBase </td> <td>average time per worker thread operation base </td> </tr> </tbody></table> Here's the code for Run that uses these; note that it uses the System.Diagnostics Stopwatch class which provides access to a higher-accuracy timer than simply calling <code>DateTime.Ticks</code> <i>(see <a href="">this blog post</a> for more information)</i> </p> <pre>()); } }</pre> This code also shows how to take two samples of a counter and calculate the difference - the counter I'm showing is rather uninteresting, but it illustrates the approach. <h2>Monitoring the Performance Counters</h2> <p <code>DiagnosticMonitorConfiguration</code> with code like this (note this is from my role <code>OnStart</code> method):</p> <pre>()); }</pre> <p>This code also adds a standard system performance counter for % CPU usage.</p> <p>Note that you can either pass the <code>DiagnosticMonitorConfiguration</code> to <code>DiagnosticMonitor.Start</code> or you can change the configuration after the DiagnosticMonitor has been started:</p> <pre>);</pre> <p>Once you've transferred the performance counter data, they go into the Azure table storage for the storage account you've passed (i.e. the account specified by <code>DiagnosticsConnectionString</code> in <code>ServiceConfiguration.cscfg</code>). You can then either use a table storage browser to look at <code>WADPerformanceCountersTable</code> or you can use the very helpful <a href="">Windows Azure Diagnostics Manager</a> from Cerebrata Software (there is a free 30-day trial). This tool reads the raw data from the Azure table storage and allows you to download it, graph it, etc. </p> <h3>References</h3> <p>Thanks to the following which provided invaluable information along the way to figuring this out:</p> <ul> <li><a href="">Michael Groeger on CodeProject – An Introduction to Performance Counters</a> </li> <li><a href="">Channel 9 – Monitoring Applications in Windows Azure</a> </li> <li><a href="">Stack Overflow – Getting High Precision Timers in C#/.NET</a> </li> </ul><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly Azure Diagnostics to Troubleshoot Intermittent Problems<p>One of the practices I advise with Windows Azure services (and really any service) is self-monitoring to find problems that may not be fatal but are indications of serious problems developing. </p> <p>I happened to run across a good example of how to do this on the <a href="">Azure Miscellany blog.</a></p> <p.) </p> . </p> <p.)</p> <p>You could even have a separate role monitoring the role and then working through the Azure Service Management API to tweak the role that is experiencing problems. </p> <p>While at Microsoft, I worked with a Microsoft Research developer on a prototype tool called <a href=")">HiLighter</a>.</p> <p>Think of Diagnostics broadly – not just as logging, but also as active monitoring of problems in your roles.</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly and Logging in Windows Azure<p>My <a href="" target="_blank">MSDN Magazine article on diagnostics and logging in Windows Azure</a> is now available in the June 2010 issue and online.</p> <p>There was some material that I didn’t have space to include or that I’ve learned since submitting the final revision of this to MSDN in March. I’ll use this blog entry to capture some of that.</p> <p>First, Rory Primrose’s blog has a few good posts on <a href="" target="_blank">performance issues of tracing</a>. <a href="" target="_blank">Debugger.Log</a>).</p> <p. <a href="" target="_blank">Josh Twist</a> from that group has done a nice job of providing a <a href="" target="_blank">good overview of using the standard System.Diagnostics features</a> (on which Azure Diagnostics is based) and then showing how to incorporate their open-source library, <a href="" target="_blank">UKADC.Diagnostics</a>, into that. I wrote a custom listener for UKADC.Diagnostics which directs the output to the Azure logging listener. There is more information on creating a customer listener in <a href="" target="_blank">this MSDN article</a>: <strong>how much overhead does tracing add to my application if I’ve disabled at run-time the level of tracing being invoked</strong>,.</p> <p>While Azure provides the logging and tracing information you write through the TraceSources in your app, it also provides access to a bunch of system logs (e.g. IIS logs, system event logs, etc.). There is a <a href="" target="_blank">good post from Mix on getting IIS logs out of Azure</a>.</p> <p>Hope you find the article helpful – post any questions here and I’ll try to respond, and I’ll also be posting more as I get the UKADC.Diagnostics working with Azure.</p><div style="clear:both;"></div><img src="" width="1" height="1">MikeKelly App-to-App Channels and Microsoft Robotics Studio<p>For a consulting project, I’ve been playing around with getting the Skype public API to work with Microsoft Robotics Developer Studio (RDS) by building a DSS service that communicates with Skype.</p> <p.</p> <p>I found, though, a problem that is <strong><em>alluded to</em></strong> but not really <strong><em>explicitly stated</em></strong> in the Skype API documentation.</p> <p>For an app-to-app connection to work, <strong><em>both sides have to establish the Application</em></strong> (in Skype terminology). In other words, both sides of the conversation have to have done a</p> <p>CREATE APPLICATION Xyzzy</p> <p>using the Skype API to create the “Xyzzy” <em>application</em> (note: <em>application</em> is Skype’s name for an app-to-app channel). </p> <p>Once both sides have created the channel, one side (typically the originating caller) has to do a:</p> <p>ALTER APPLICATION Xyzzy CONNECT otheruser <br /></p> <p>where Xyzzy is the application created and otheruser is the user you’re calling.</p> <p:</p> <p>OnReply to Command 0(): APPLICATION Xyzzy STREAMS otheruser:1 <br /></p> <p>which tells you that “otheruser” can now receive communications through the app-to-app channel.</p> <p>Like a lot of things in programming, this is obvious once you realize it – you can’t send through a channel unless both sides have established the channel. I was hoping I could test one side, but no go.</p> .</p><img src="" width="1" height="1">MikeKelly Studio R2<p.</p> <p:</p> <p>The type or namespace name 'Robotics' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) </p> <p>pointing at this line generated by the RDS code:</p> <p>using drive = Microsoft.Robotics.Services.Drive.Proxy;</p> <p>Sure enough, trying to add a reference to Microsoft.Robotics. <em>anything</em> fails since that namespace doesn’t exist on my machine.</p> <p>Hmm…</p> <p>I guessed that I was missing an install of something, perhaps the “CCR and DSS toolkit” – but talking to someone on the Robotics dev team at MS, I verified that I had the same assemblies as he did. </p> <p>I then realized I was using Visual Studio 2010 Release Candidate – could that be the problem?</p> <p.</p> <p>That then took me on to the next problem –getting this to run. When I run it in VS 2008, I get an error:</p> <blockquote> <p><font size="2" face="Courier New">The thread 0x670 has exited with code 0 (0x0). <br />*** Initialization failure: Could not start HTTP Listener. <br />The two most common causes for this are: <br />1) You already have another program listening on the specified port <br />2) You dont have permissions to listen to http requests. Use the httpreserve command line utility to run using a non-administrator account. <br />Exception message: Access is denied</font></p> </blockquote> <p> </p> <p.</p> <p>I decided to just move this to another machine where DSS is working and where I had VS 2008 installed, so copied the files over there. I ran into a couple of more problems before I got this working: </p> <p>The final two problems:</p> <p>*”</p> <p>*</p> <blockquote> <p><font face="Courier New">Reference Assemblies/Microsoft/Robotics/v2.0</font></p> </blockquote> <p>instead of </p> <blockquote> <p><font face="Courier New">Reference Assemblies/Microsoft/Robotics/<strong><u>v2.1</u></strong></font>. </p> </blockquote> <p>This also confuses DSS Proxy. Deleting those references in VS and adding the correct ones from the V2.1 directory (references for Microsoft.Ccr.Core, Microsoft.Dss.Base, and Microsoft.Dss.Runtime fixed the problem and I am now running!</p><img src="" width="1" height="1">MikeKelly Azure Panel Discussion Q&A<p>I am at the <a href="">Azure Firestarter</a> event in Redmond today which just finished with a panel discussion and Q&A. Here are my notes.</p> <p>Q: For Dallas, do I need to use C# to access the data?</p> <p>A: No - it's pretty easy to use C# classes but Dallas exposes an OData feed so you need a language that can access a REST API.</p> <p>Q: Is there pricing on the CDN?</p> <p>A: Still preview. No pricing info.</p> <p>Q: You mentioned you could run an EXE by hosting it in WCF. Will it recycle with the role or will it run persistently?</p> <p>A: When I do this, I create a worker role that starts the process, wait for exit and if it exits throw an exception - which causes Azure to recycle the role and restart the EXE.</p> <p>Q: Is it possible to have a private cloud?</p> <p>A: Not today. No offering for that today. But it's under consideration.</p> <p>Q: If I have an app that can't be deployed via xcopy - it requires something installed or configed, can it be run in Azure?</p> <p>A: If the MSI can run as a non-administrator, you could conceivably run that and wait for it to finish in your OnStart method in the web role. Admin mode is coming later.</p> <p>Q: Can we change the affinity?</p> <p>A: No - once it's set cannot change.</p> <p>Q: Suppose you have a web role that needs to adjust affinity based on work week differences in US, Europe and Asia?</p> <p.</p> <p>Q: What kind of techniques have you seen to secure the SQL Azure connection string?</p> <p>A: Those configuration files are encrypted when uploaded - you can use code-based cryptography to encrypt and decrypt the connection string when reading it.</p> <p>Q: Is there a plan to expand COUNT support in Azure Tables?</p> <p>A: No.</p> <p>Q: When you roll out changes to the OS, how do we make sure it doesn't break?</p> <p>A: The guest OS in the virtual machine doesn't change unless you update the OS Version string. The base OS actually running on the machine is updated but not the guest OS.</p> <p>Q: Is there a Patterns & Practices document for building on-premises apps?</p> <p>A: There is Windows Azure guidance is working on it. Eugenio Pace has been blogging on this at <a href=""></a></p> <p>Q: Is there a way to authenticate to Azure and use the service fabric to proxy authenticate?</p> <p>A: No clear what the question is.</p> <p>Q: What is your replication and disaster safety policy?</p> <p.</p> <p>Q: What are the plans for SharePoint on Azure?</p> <p>A: None of the slides put SharePoint on it now - not sure what the plans are around offering SharePoint developer services.</p> <p>Q: Only thing we can't automate now using Service Management API is to create hosted services. Are there plans to change that?</p> <p>A: Probably.</p> <p>Q: How can I test in the cloud without exposing to the entire Internet?</p> <p>A: You can write code to do this. There is nothing in the platform that helps. You could have an IP address whitelist and not allow through anything not on the whitelist.</p> <p>Q: Does SQL Azure support page compression?</p> <p>A: No</p> <p>Q: Does 50 GB limit include the log?</p> <p>A: No</p> <p>Q: How do you manage compatibility if you upgrade to SP1?</p> <p>A: Don't apply the service pack itself. We make modifications to the engine themselves. Will announce that as part of the service updates.</p> <p>Q: Is SQL Azure good for OLTP or OLAP applications?</p> <p>A: Primary application is light workload OLTP - types of traffic you see within a departmental application - hundreds of transactions per second. Have some customers hosting the cubes in the cloud and running analysis services on premises, but planning to make this available hosted this year.</p> <p>Q: When will you get transparent data encryption?</p> <p>A: SQL Azure is a multi-tenant system - managing the keys is a hard problem. It's on the roadmap but have some work to do.</p> <p>Q: Why isn't the CLR enabled?</p> <p>A: Haven't done enough testing - have to be sure that no malicious user can do something evil with a DLL even if it's marked safe. It's on the roadmap but have to be really careful about security around this.</p> <p>Q: Can I use Bing to crawl my database?</p> <p>A: Have a SQL Azure Labs site and can expose your DB as an Odata feed. Power of that is you can expose to non-MS clients like an iPhone app.</p> <p>Q: When you said multiple tenants share the same data file did you mean that multiple databases are within the same MDF file?</p> <p>A: That's correct.</p> <p>Q: So each SQL Azure database isn't really a database it's effectively a set of tables?</p> <p>A: There was an "under the hood" talk at PDC that you can look at to learn more about how this works.</p> <p>Q: Isn't it scary to have SQL Server exposed on the Internet?</p> <p>A: There is a firewall feature that restricts access to SQL Server based on IP addresses, and also prevent some user name /password changes.</p> <p>Q: Can you put Microsoft PII data on an Azure database?</p> <p>A: Not sure - need to get back to you on that.</p> <p>Q: Can you use SQL Profiler?</p> <p>A: No - but we are adding some DMVs to get that information.</p> <p>Q: Can we authenticate to Azure using RSA two-factor ID?</p> <p>A: No - today only a Live ID for the windows Azure portal</p> <p>Q: Can we install Windows Media Services or third-party services?</p> <p.</p> <p>Q: How long does it take to deploy millions of records to SQL Azure?</p> <p>A: Depends on Internet connection speed, whether you're doing single inserts or bulk copy API.</p> <p>Q: Mark was talking about session state - how do you do that without SQL Server</p> <p.</p> <p>Q: When will you increase beyond 50 GB?</p> <p>A: Are there bigger databases in the future? Can probably assume there will be. Keep in mind that you really want to think about a scale out pattern.</p> <p>Q: What's the motivation for multi-tenanting MDF files?</p> <p>A: Better use of resources.</p> <p>Q: Can you say what the releases are for Azure? <br />A: This year is all I can say.</p> <p>Q: What's the best pattern for implementing a cold storage / hot storage model?</p> <p.</p> <p>Q: If someone has 3 TB of data can they send you the data on a DVD to upload it to SQL to avoid connection costs for the upload?</p> <p>A: No plans at present but it's a great idea.</p> <p>Q: What kinds of things are people doing with Python?</p> <p>A: Haven't seen much on Python.</p> <p>Q: Is there academic pricing for Azure? <br />A: There is programmatic things where we give it out to universities. Talk to your account manager.</p> <p>Q: You mentioned throttling - at what point does an app get cut off?</p> <p.</p> <p>Q: At SxSW there was a Facebook toolkit deployed. Any experiences?</p> <p>A: It's based on best practices of people who've actually built some Facebook apps on Azure.</p> <p>Q: Is there a standard way to synchronize between on-premises and cloud DBs?</p> <p>A: Yes -it's on the Windows Azure portal.</p><img src="" width="1" height="1">MikeKelly Apps to Windows Azure<p>I am at the <a href="">Azure Firestarter</a> event in Redmond today and just heard <a href="mailto:mark.kottke@microsoft.com">Mark Kottke</a> talk about his experiences as an app development consultant with Microsoft on migrating existing customer apps to Azure. Here are my notes; slides and sample code are to be posted later and I will update the post with them when they are.</p> <p>Migrating to Windows Azure - <a href="mailto:mark.kottke@microsoft.com">Mark Kottke</a></p> <ul> <li>Helping early adopter customers move to Azure</li> <li>Most were new applications but some were migrations.</li> <li>How to plan a migration <ul> <li>What is easy?</li> <li>What is hard?</li> <li>What can you do about it?</li> </ul> </li> </ul> <ul> <li>Why migrate? <ul> <li>Flexibility to scale up and down easily</li> <li>Cost</li> </ul> </li> </ul> <ul> <li>Is it better to start over or just migrate existing code? <ul> <li>Migration "seems" easier - code already written, tested, no users to train, …</li> <li>But…</li> </ul> </li> </ul> <ul> <li>Six customers <ul> <li>Kelley Blue Book <ul> <li>Now in two data centers and costs quite a bit to keep up the second data center</li> <li>ASP.Net MVC app with SQL Server</li> <li>Migrated pretty quickly</li> <li>Use Azure as a third data center (in addition to their two existing data centers)</li> </ul> </li> </ul> <ul> <li>Ad Slot <ul> <li>Migrated storage to Azure tables.</li> <li>Biggest change because of difference from SQL</li> <li>Similar data architecture to the BidNow application.</li> </ul> </li> </ul> <ul> <li>Ticket Direct <ul> <li>New Zealand's ticket master</li> <li>Used SQL Azure</li> </ul> </li> </ul> <ul> <li>RiskMetrics <ul> <li>Pushed the scaling the most of the case studies.</li> <li>It had scaled to 2000 nodes by the time of PDC 2009</li> <li>Do Monte Carlo analysis for financial applications. The more trials they can run, the better the results.</li> <li>Their key IP is a 32-bit DLL that does this - they were able to move that without rewriting it.</li> </ul> </li> </ul> <ul> <li>CSC - Legal Solutions Suite <ul> <li>ASP.Net application like Kelley Blue Book</li> </ul> </li> </ul> <ul> <li>CCH Wolters Kluwer <ul> <li>Financial Services ISV</li> <li>Sales tax engine to integrate with ERP systems. Currently sold as an on-premises solution with regular updates for the sales tax rate changes.</li> <li>Moving to the cloud made it easier for customers - no need to do updates or manage software on-site.</li> <li>Sales Tax engine was written in a 4GL from CA called FLEX that generates .NET code but it worked fine.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Typical apps are comprised of n-tiers: presentation, services, business logic, data. First thought is to migrate everything - but could migrate just part of it. <ul> <li>e.g. Could migrate just the presentation layer - avoids dealing with all the security issues. <ul> <li>Benefit is get development team up to speed on Cloud, processes modified to include Cloud, …</li> </ul> </li> </ul> </li> </ul> <ul> <li>Q: Could you upload a BLG file (Binary Log File) that shows what RAM usage, what transactions, etc. and have the Azure ROI tool estimate the cost of running this service on Azure? <ul> <li>A: Not in the plans now. Go to <a href=""></a> to enter this.</li> </ul> </li> </ul> <ul> <li>Q: How about if you put the cost of your demo apps on the apps - just knowing what the cost of a demo app would be helpful. <ul> <li>A: Good idea.</li> </ul> </li> </ul> <ul> <li>Data Storage Options <ul> <li>Have MemCacheD, MySQL in addition to other options discussed (SQL Azure, Azure Tables, etc.)</li> <li>To migrate a DB to SQL Azure… <ul> <li>Using SQL Server Save or Publish Scripts, extract all the information about the local DB.</li> <li>Using Management Studio connected to SQL Azure, create a new DB.</li> <li>Open the script file created from the existing local DB</li> <li>Execute it against the SQL instance.</li> <li>Can use SQL Azure Migration Wizard (<a href=""></a>)</li> </ul> </li> </ul> <ul> <li>Q: Will the database automatically scale up from 1 GB -> 10 GB? <ul> <li>A: No, but you can use the portal to modify it.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Caching / State Management <ul> <li>Velocity - not yet available for Windows Azure</li> <li>Can use ASP.NET cache but not shared across instances.</li> <li>Can use ASP.NET membership / profile providers - on Codeplex there is one that uses SQL Azure.</li> <li>Can use Memcached. Pretty straightforward to use for caching session state.</li> <li>Cookies, hidden fields - any client-side providers basically work fine.</li> </ul> </li> </ul> <ul> <li>For app.config and web.config - how much of your state needs to be able to be changed when the app is deployed <ul> <li>Move to ServiceConfiguration.cscfg to allow for run-time update.</li> <li>Leverage RoleEnvironmentChanging and RoleEnvironmentChanged events if you want to be able to change default behavior of recycling the role on any config change.</li> <li>Use RoleEnvironment.IsAvailable to determine whether you are running in the cloud or on premises.</li> </ul> </li> </ul> <ul> <li>Using WCF Service endpoints that are exposed only within the role - not exposed to the Internet, not load balanced. <ul> <li>Need to call Windows Azure APIs to discover the services and wire up once the server is running.</li> <li>Important for Memcached to share caching.</li> <li>WCF Azure samples: <a href=""></a></li> </ul> </li> </ul> <ul> <li>Legacy DLLs <ul> <li>COM Applications - typically have a dependency on the registry and won't be able to update that when running in the cloud. <ul> <li>Use registration-free COM+ with manifest files. (See <a href=""></a>)</li> </ul> </li> </ul> <ul> <li>To call a 32-bit DLL use a WCF host process </li> <li>For external processes (EXEs) <ul> <li>Host in a worker Role</li> </ul> </li> </ul> </li> </ul> <ul> <li>Can deploy to staging and then flip to production - the staging has a GUID. <ul> <li>No requirement to use staging but it is a good practice to test.</li> <li>Sometimes need to change configuration changes between staging (test) and production</li> </ul> </li> </ul> <ul> <li>Start with development fabric / development storage <ul> <li>But if using SQL Azure - better to use SQL Azure in the cloud because there are a enough differences between the local SQL and SQL Azure that it's worth testing against the cloud SQL</li> </ul> </li> </ul> <ul> <li>Then test development fabric / cloud storage</li> <li>Then cloud fabric / cloud storage</li> </ul><img src="" width="1" height="1">MikeKelly Applications for the Cloud<p>I am at the <a href="">Azure Firestarter</a> event in Redmond today and just heard <a href="">David Aiken</a> from the Azure team give an overview of best practices for developing applications for the cloud along with some tips and tricks. Here are my notes; slides and sample code are to be posted later and I will update the post with them when they are.</p> <p><a href="">David Aiken</a> - Applications for the Cloud</p> <ul> <li>We can migrate an existing app and many will migrate without that much work.</li> <li>However, let's focus on what new things we can use if we build an app for the cloud.</li> <li>Optimal workload patterns for the cloud <ul> <li>"On and Off" workload - e.g. my app is only used between 7 AM and 7 PM. Can I turn it off? <ul> <li>Yes - add instances during the day and turn them off at night.</li> </ul> </li> </ul> <ul> <li>Growing Fast <ul> <li>Startups. Turn the dial up as get more users.</li> <li>Don't need a huge upfront investment for what you guess your peak load might be.</li> <li>Priced out a high-end HP server last night: 48-way CPU, 15000 rpm drives, 512GB of RAM = $144K</li> <li>Facebook apps <ul> <li>Have 200 users week 1</li> <li>2000 week 2</li> <li>200,000 week 3</li> <li>20 million week 4</li> </ul> </li> </ul> <ul> <li>If you don't think about this upfront and design for it - you'll be in a world of hurt between week 3 and week 4</li> <li>Cost scales linearly with usage</li> </ul> </li> </ul> <ul> <li>Unpredictable bursting <ul> <li>"My site is being featured on Oprah on Wednesday - they told me expect 20 million additional users".</li> </ul> </li> </ul> <ul> <li>Predictable bursting <ul> <li>Could be seasonal, monthly, quarterly, …</li> </ul> </li> </ul> </li> </ul> <ul> <li>When you don't have to buy for the peak and pay for it when you don't need it, you can actually oversupply the peak demand to provide even better performance <ul> <li>If you don't have to pay for 12 instances when you usually only need 1, can you afford to buy 20 instances when you need 12 and provide that much better performance?</li> </ul> </li> </ul> <ul> <li>How do I get started? <ul> <li>Think about how to manage subscriptions for your dev team - or you'll have everyone sharing one Live ID</li> <li>Download the <a href="">training kit</a></li> <li>Tools for looking at storage (<a href=""></a> has some; others at….)</li> <li>Diagnostics tools (<a href=""></a> has a tool for looking at diagnostics data; others at …)</li> </ul> </li> </ul> <ul> <li>Billing and Subscription <ul> <li>Billing Account is one WLID. Subscription can be the same WLID or a different WLID. In general, should be different if not a one-person shop.</li> <li>Finance guy should have the billing WLID -- not developers.</li> <li>He creates multiple subscriptions. <ul> <li>One per developer (each dev has own WLID)</li> </ul> </li> </ul> <ul> <li>But how do they deploy to the same app if they are working on the same app? <ul> <li>Create certificate for the app. Create a self-signed certificate - <a href="">directions here</a>.</li> <li>Give to developers</li> <li>They deploy using certificate. Can use PowerShell scripts using the Azure Cmdlets to deploy (details on <a href="">Channel 9</a>).</li> </ul> </li> </ul> </li> </ul> <ul> <li>When you're testing apps in the cloud - you can use the real cloud. Don't have to build a virtual data center in a single machine in your office.</li> <li>Q: Can you delete a subscription? <ul> <li>A: Call the helpdesk to delete a subscription - they'll do it.</li> <li>A: You can write a script that enumerates every service you have running under a certificate and removes them - to avoid paying for unneeded cloud instances.</li> </ul> </li> </ul> <ul> <li>Remember that the data centers all run UTC time.</li> <li>Simple Azure App - Archivist - builds an archive of Twitter feeds. <ul> <li>Used SQL Azure for store because very easy to write a WHERE clause against DateTime - would be harder against Table storage.</li> <li>For each search term… query Twitter… Convert to JSON for ease of use in a Silverlight client.</li> <li>Do some aggregation.</li> <li>Repeat about 200,000 times per hour.</li> <li>Key: Decouple the pieces. Assume failure at any point. <ul> <li>"Made a guarantee that you will read every message on a queue at least once - and we literally mean at least once - good chance you will read it more than that."</li> <li>Send each search term to query twitter for into a queue.</li> <li>Query twitter piece gets each search term, queries twitter and puts results in a blob - puts that into a queue.</li> <li>Next piece pulls the blobs off the queue and aggregates results.</li> <li>Can scale independently <ul> <li>Piece that pulls search terms and puts into queue - probably one instance.</li> <li>Piece that queries Twitter - might want 2-3 instances.</li> <li>Piece that aggregates - maybe 10 or so instances.</li> <li>By dividing up work so granularly, can do this.</li> </ul> </li> </ul> <ul> <li>Look at queue length to determine how many instances you need - turn off and on as needed. <ul> <li>If increasing number of instances, might also want to create number of queues - nothing fancy, just round robin.</li> <li>Can do all this in the cloud - so app becomes almost self-monitoring and self-adjusting.</li> <li>Another approach is to combine 5-10 search terms into a single queue entry - might reduce overhead of just pulling a message off the queue.</li> </ul> </li> </ul> <ul> <li>Might make sense to do some pre-processing to enable common queries - to show top 10 contributors on Twitter to a search term, read in whole feed into memory, figure out the top 10 in memory and write out a blob pre-formatted in JSON or HTML with the answer - then on the display, don't do a query - just show the content.</li> </ul> </li> </ul> <ul> <li>Could use Command pattern to decouple instances from work - so implement in threads on a single instance in testing but implement in role instances in production.</li> </ul> </li> </ul> <ul> <li>Cloudy Tips <ul> <li>Remember you are 64-bit in the cloud. Make sure your 3rd party DLLs are 64-bit. Leave your setting at AnyCPU.</li> <li>Ship everything to the Cloud for testing. <ul> <li>If see app doing "Initializing… Busy… Initializing… Busy" - probably missing a reference you have on Dev Fabric but not on the cloud.</li> <li>No harm in saying "Copy Local" on any dependencies and references, even those in the GAC.</li> <li>If you're using PHP - include the PHP engine in the deployment.</li> </ul> </li> </ul> <ul> <li>What does stateless mean anyway? <ul> <li>Don't have state be in your compute instance - it's somewhere else.</li> <li>It could be in table storage, in SQL, in blob storage, whatever.</li> <li>Can use the Membership and Profile providers to persist this into Table storage.</li> <li>If you have state in your compute - as soon as that compute instance dies, the state is gone.</li> </ul> </li> </ul> <ul> <li>No Azure SLA if you don't have at least 2 instances. <ul> <li>If you have just one instance, you can go down with the hardware.</li> <li>More than one instance - will guarantee those on separate scale units.</li> </ul> </li> </ul> </li> </ul> <ul> <li>SQL Azure vs. Tables <ul> <li>How do I choose between them?</li> <li>SQL is the easiest - but what if I need 60 GB? But Table storage sounds really limited on queries?</li> <li>How do I find the top 10 items in a Table store?</li> <li>Have a sample app - BidNow. It's out on Code Gallery. <ul> <li>Online auction site.</li> <li>Have bids ending soon, most viewed items, hot items (most bids)</li> <li>Can imagine the SQL queries to do this… but don't use SQL Azure in BidNow.</li> <li>There is a separate Azure Table for each UI component - Hot Items, Most Viewed, Bids Ending Soon.</li> <li>How do you make a SQL query fast? You create an index on the items you're querying. What SQL does is when you update or add an item, it updates the index as well. <ul> <li>But don't have indices on table storage except for PartitionKey and RowKey.</li> <li>Can use that to create a new item with the right partition key so that if we just read the first 10 items from ItemsMostViewed - the order in which they will come out based on partition key is right.</li> <li>So when an item is viewed, add a message to a queue and have a worker role process those and update the Most Viewed Items table.</li> </ul> </li> </ul> <ul> <li>When appropriate - use both. <ul> <li>If your database is really big because you have binary data in there - pull it out and put it in blob storage.</li> <li>Don't limit yourself by "I have to use SQL Server."</li> <li>Table storage is a lot cheaper.</li> <li>It's flexible. In your profile can store arbitrary data: <ul> <li>Can have n rows for each user. First is generic user info (email, name, etc.)</li> <li>Next set of rows has the items you've bidded on.</li> <li>Next set of rows has the items you've listed.</li> <li>All share same partition key - user name - but rowkey can be different.</li> </ul> </li> </ul> <ul> <li>Denormalize and partition. <ul> <li>Don't think I have a 32-way box running my database - think I've got 32 1-way boxes running my DB.</li> </ul> </li> </ul> <ul> <li>Think about access patterns - you're charged for both accesses and storage. You might end up spending more on access charges than on storage charges.</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>Failure <ul> <li>100% guaranteed. 99.99% uptime -> run long enough and eventually you'll be down.</li> <li>At least will happen when need to patch the machine your instance is running on.</li> <li>You'll get notified by this - get a bit of time to run shutdown code.</li> <li>It doesn't matter how many times we do the same task: <ul> <li>If it fails at the beginning…</li> <li>If it fails at the end…</li> <li>If it fails in the middle…</li> <li>Or we do it 300 times in a row</li> </ul> </li> </ul> <ul> <li>You get the same answer!</li> </ul> </li> </ul> <ul> <li>If your service is on fire - could you figure it out? <ul> <li>Use Diagnostics</li> <li>Could have an XML file that specifies what logs and Perf Counters you want. <ul> <li>Read it and adjust the diagnostics settings to do the right thing.</li> </ul> </li> </ul> <ul> <li>In the <a href="">App Fabric SDK</a> there is a real-time tracing tool using the Service Bus. <ul> <li>You can have a trace listener that just puts its messages on the service bus</li> <li>Can look at it on any machine.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Collecting log data also helps with spotting patterns of usage that would affect your capacity planning.</li> <li>Q: If your application fails over and over - how long will the fabric controller keep starting it? <ul> <li>A: I've never seen it stop it. It will keep recycling.</li> </ul> </li> </ul> <ul> <li>Q: If I want to run 10 instances at day and no instances at night, will that happen automatically or do I have to script it? <ul> <li>A: You have to script that or write the code.</li> </ul> </li> </ul><img src="" width="1" height="1">MikeKelly Azure SQL Notes<p>I am at the <a href="">Azure Firestarter</a> event in Redmond today and just heard <a href="">David Robinson</a> from the SQL team give an overview of SQL Server for Azure. Here are my notes; slides and sample code are to be posted later and I will update the post with them when they are.</p> <p>SQL Azure - <a href="">David Robinson</a></p> <ul> <li>Goal is to convince you that there is no difference between SQL Server and SQL Azure.</li> <li>First called "SQL Data Services for Azure" at PDC 2008. <ul> <li>Looked a lot like the Azure table storage that <a href="">Brad just talked about</a>.</li> <li>Feedback - why not expose SQL Server?</li> </ul> </li> </ul> <ul> <li>Done that - extended the SQL Server platform to the cloud. <ul> <li>Rich ecosystem of tools: BI, reporting, VS integration, …</li> <li>Goal -> same SQL Server you have on premise you now have in the cloud.</li> </ul> </li> </ul> <ul> <li>Difference between hosted DB and DB as a service <ul> <li>SQL Azure combines best of both.</li> <li>Nothing to install, nothing to maintain, nothing to patch.</li> <li>Every 8 weeks provide new features as a service update <ul> <li>Service Update 2 deployment started today. Expect it to complete by Friday (4 days).</li> </ul> </li> </ul> <ul> <li>Use existing tools - management studio, visual studio - all just work <ul> <li>Need November 2009 CTP of SQL Server 2008 R2 to manage Azure SQL Services</li> </ul> </li> </ul> <ul> <li>Automation manages servers in the data centers.</li> </ul> </li> </ul> <ul> <li>Key customer scenarios for SQL Azure v1 <ul> <li>Departmental collaboration apps <ul> <li>Low concurrency, cyclical usage apps</li> <li>Corp IT doesn't manage the application and isn't aware of it</li> <li>Provides better management</li> </ul> </li> </ul> <ul> <li>Data hubs <ul> <li>Consolidate multiple data sources and allow access from anywhere</li> </ul> </li> </ul> <ul> <li>Packaged LOB applications <ul> <li>ISVs extending their on-premise offering to be cloud hosted</li> </ul> </li> </ul> </li> </ul> <ul> <li>Architecture <ul> <li>Provisioning <ul> <li>Listen for connections on Port 1443, monitor and bill.</li> <li>Gateway to SQL Azure</li> </ul> </li> </ul> <ul> <li>Scalability and Availability fabric <ul> <li>Provides load balancing, management, etc.</li> <li>Provides automatic backup replicas</li> <li>Have a scale unit - fully redundant rack of machines. <ul> <li>Puts your primary and backup on different scale units.</li> <li>Upgrade: <ul> <li>Failover a scale unit</li> <li>Update the scale unit with new service bits</li> <li>Put scale unit back in rotation</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>In between - SQL Server</li> </ul> </li> </ul> <ul> <li>Use existing client libraries <ul> <li>ADO.NET, ODBC, PHP</li> <li>Client libraries are pre-installed in Azure roles</li> <li>Support for ASP.Net controls</li> <li>Clients can connect directly to the database <ul> <li>Cannot hop across DBs (no USE command)</li> </ul> </li> </ul> </li> </ul> <ul> <li>Management <ul> <li>All the "pain in the butt" things that DBAs don't want to be bothered with (the log file is running out of space) are handled automatically.</li> <li>All the application-specific things like query tuning, index creation still managed by DBAs.</li> <li>Support "code far" scenario (where code and DB are not co-located) but will generally work best when you insure your DB and code are co-located in a single Azure DC <ul> <li>Unless you do special work to do caching locally.</li> </ul> </li> </ul> </li> </ul> <ul> <li>No way to do a backup of a regular SQL DB on premise and restore to a SQL Azure instance. <ul> <li>Working on this.</li> <li>Now have to write a script to create the DB and indices, etc. then use BCP to import data.</li> </ul> </li> </ul> <ul> <li>In VS 2010 - new project type "Data Tier Application" <ul> <li>Supported with SQL Azure and on-premise</li> <li>Captures data tier requirements (e.g. machine type assumptions, usage patterns) in addition to basic create table/etc. scripts.</li> <li>Compiles to a DACPAC - like an MSI for a database.</li> <li>Can deploy a DACPAC on-premise or to the cloud. <ul> <li>Click on Properties on the Data Tier Application in VS and go to Deploy tab.</li> <li>Change deployment location in Destination Connection String to a SQL Azure database and will deploy there.</li> <li>Build and then Deploy to send to SQL Azure.</li> <li>Q: What about changes? <ul> <li>A: You have the ability to deploy just changes for on-premise. <ul> <li>Saves the DACPAC you deployed in the master DB. When you deploy upgrades, it will compare the DACPAC against the actual live schema to make sure they match and then figures out the changes to make.</li> <li>Not yet available for SQL Azure - for now a manual process. KB article on how to do this.</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>Uses regular SQL Server security model</li> <li>New features announced at MIX 10: <ul> <li>50 GB SKU <ul> <li>Now in beta (preview) - must sign up by emailing engagesa@microsoft.com</li> <li>General availability with SU3 of SQL Server Azure in June 2010</li> <li>Pricing TBA</li> </ul> </li> </ul> <ul> <li>MARS - Multiple Active Row Sets <ul> <li>Multiple SQL batches on a single connection</li> </ul> </li> </ul> <ul> <li>Spatial Data in the Cloud <ul> <li>Available in SU3 (June)</li> <li>Spatial data allows for geographic and mapping data in SQL.</li> <li>All features that on-premise supports for spatial data available in SQL Azure</li> <li>Example/ demo: <ul> <li>have a table with geo coordinates for every gas station in the U.S.</li> <li>Use Bing Maps API to figure route from A to B.</li> <li>Go to SQL Azure DB to get all gas stations from the table within 1000 meters of the map route calculated by Bing Maps</li> <li>Add those as pins on the Bing Map and display to users.</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>Q: How do you maintain app compatibility when you update underneath the app <ul> <li>A: Goal is to maintain 100% compatibility. Do extensive testing. Focusing on minor changes, not adding new features like data types.</li> </ul> </li> </ul> <ul> <li>Q: Can you run a linked server to SQL Azure <ul> <li>A: You can add a SQL Azure instance as a linked server if you have an on-premise SQL Server.</li> <li>You cannot link two SQL Azure servers.</li> </ul> </li> </ul> <ul> <li>Q: What about distributed transactions? <ul> <li>A: Not supported in SQL Azure.</li> </ul> </li> </ul> <ul> <li>Q: Can I run managed code and stored procedures in a SQL Azure instance? <ul> <li>A: Today, no. Spatial is the start of enabling that.</li> <li>You will never be able to run arbitrary code on SQL Azure.</li> </ul> </li> </ul><img src="" width="1" height="1">MikeKelly Azure Storage Overview<p>I am at the <a href="">Azure Firestarter</a> event in Redmond today and just heard <a href="">Brad Calder</a> give a quick overview of Azure data. Here are my notes; slides and sample code are to be posted later and I will update the post with them when they are.</p> <ul> <li>Blobs <ul> <li>REST APIs</li> <li>Can have a lease on the blob - allows for limiting access to the blob (used by drives)</li> <li>To create a blob… <ul> <li>Use StorageCredentialsAccountAndKey to create the authentication object</li> <li>Use CloudBlobClient to establish a connection using the authentication object and a URI to the blob store (from the portal)</li> <li>Use CloudBlobContainer to create/access a container</li> <li>Use CloudBlob to access/create a blob</li> </ul> </li> </ul> <ul> <li>Two types of blobs <ul> <li>Block blob - up to 200 GB <ul> <li>Targeted at streaming workloads (e.g. photos, images)</li> <li>Can update blocks in whatever order (e.g. potentially mulitple streams)</li> </ul> </li> </ul> <ul> <li>Page blob - up to 1 TB <ul> <li>Targeted at random read/write workloads</li> <li>Used for drives</li> <li>Pages not stored are effectively initialized to all zeros. <ul> <li>Only charged for pages you actually store.</li> <li>Can create a 100 GB blob, but write 1 MB to it - only charged for 1 MB of pages.</li> </ul> </li> </ul> <ul> <li>Page size == 512 bytes <ul> <li>Updates must be 512 byte aligned (up to 4 MB at a time)</li> <li>Can read from any offset</li> </ul> </li> </ul> <ul> <li>ClearPages removes the content - not charged for cleared pages.</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>CDN <ul> <li>Storage account can be enabled for CDN.</li> <li>Will get back a domain name to access blobs - can register a custom domain name via CDN.</li> <li>Different from base domain used to access blobs directly - if you use the main storage account URL, will retrieve from blob store not using CDN.</li> <li>To use CDN <ul> <li>Create a blob</li> <li>When creating a blob, specify "TTL" - time to live in the CDN in seconds.</li> <li>Reference the blob using the CDN URL and it will cache it in the nearest CDN store.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Signed URLs (Shared Access Signatures) for Blobs <ul> <li>Can give limited access to blobs without giving out your secret key.</li> <li>Create a Shared Access Signature (SAS) that gives time-based access to the blob. <ul> <li>Specify start-time and end-time.</li> <li>What resource-granularity (all blobs in a container, just one blob in the container)</li> <li>Read/write/delete access permissions.</li> </ul> </li> </ul> <ul> <li>Give out URL with signature.</li> <li>Signature is validated against a signed identifier. You can instantaneously revoke access to a signature issued by removing the signed identifier. <ul> <li>Can also store time range and permissions with the signed identifier rather than in the URL.</li> <li>Can change them after issuing the URL and the signature is still valid in the URL.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Windows Azure Drive <ul> <li>Provides a durable NTFS drive using page blob storage. <ul> <li>Actually a formatted single-volume NTFS VHD up to 1 TB in size (same limit as page blob)</li> <li>Can only be mounted by one VM instance at a time. <ul> <li>Note that each role instance runs on a VM, so only one role instance can mount a drive read/write</li> <li>Could not have both a worker role and a web role mounting the same drive read/write</li> </ul> </li> </ul> <ul> <li>One VM instance can mount up to 16 drives.</li> </ul> </li> </ul> <ul> <li>Because a drive is just a page blob, can upload your VHD from a client.</li> <li>An Azure instance mounts the blob <ul> <li>Obtains a lease</li> <li>Specifies how much local disk storage to use for caching the page blob</li> </ul> </li> </ul> <ul> <li>APIs <ul> <li>CloudDriveInitializeCache - initalize how much local cache to use for the drive</li> <li>CloudStorageAccount - to access the blob</li> <li>Create a CloudDrive object using CreateCloudDrive specifying the URI to the page blob</li> <li>Against CloudDrive… <ul> <li>Create to initialize it.</li> <li>Mount to mount it - returns path on local file system and then access using normal NTFS APIs</li> <li>Snapshot to create backups <ul> <li>Can mount snapshots as read-only VHDs</li> </ul> </li> </ul> <ul> <li>Unmount to unmount it.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Driver for mounting blobs only in the cloud - not on development fabric. <ul> <li>Instead, just use VHDs</li> </ul> </li> </ul> </li> </ul> <ul> <li>Tables <ul> <li>Table can have billions of entities and terabytes of data.</li> <li>Highly scalable.</li> <li>WCF Data Services - LINQ or REST APIs</li> <li>Table row has a partition key and a row key <ul> <li>Partition key: <ul> <li>controls granularity of locality (all entities with same partition key will be stored and cached together)</li> <li>provides entity group transactions - as long as entities have same partition key, can do up to 100 insert/update/delete operations as a batch and will be atomic.</li> <li>enable scalability - monitor usage patterns and use partition key to scale out across different servers based on partition keys <ul> <li>More granularity of partition key = better scalability options</li> <li>Less granularity of partition key = better ability to do atomic operations across multiple rows (because all must have same partition key)</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>To create / use an entity <ul> <li>Create a .NET class modeling an entity</li> <li>Specify the DataServiceKey attribute to tell WCF Data Services the primary keys (partitionkey, rowkey)</li> <li>APIs <ul> <li>CloudTableClient - establish URI and account to access table store</li> <li>TableServiceContext - get from CloudTableClient</li> <li>Add entities using the context AddObject method specifying the table name and the class with the data for the new entity <ul> <li>SaveChangesWithRetries against context to save the object.</li> </ul> </li> </ul> <ul> <li>To Query… using LINQ with AsTableServiceQuery<xxxx> where xxx is the .NET class modeling the entity. <ul> <li>Manages continuation tokens for you</li> </ul> </li> </ul> <ul> <li>Then do a foreach and can use UpdateObject to update objects in the LINQ stream.</li> <li>Use SaveChangesWithRetries <ul> <li>Add SaveChangesOptions.batch if < =100 records and all have same partition key - save as one batch.</li> <li>If not, sends a transaction for each object.</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>Table tips <ul> <li>ServicePointManager.DefaultConnectionLimit = x (default .NET HTTP connections = 2)</li> <li>Use SaveChangesWithRetries and AsTableServiceQuery to get best performance</li> <li>Handle Conflict errors on inserts and NotFound errors on Delete <ul> <li>Can happen because of retries</li> </ul> </li> </ul> <ul> <li>Avoid append only write patterns based on partitionkey values <ul> <li>Can happen if partition key is based on timestamp.</li> <li>If you keep appending, defeating scale out strategy of Azure</li> <li>Make partition key be distributed not all in one area.</li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>Queues <ul> <li>Provide reliable delivery of messages</li> <li>Allow loosely coupled workflow between roles <ul> <li>Work gets loaded into a queue</li> <li>Multiple workers consume the queue</li> </ul> </li> </ul> <ul> <li>When dequeuing a message, specify an "invisibility time" which leaves the message in the queue but makes it temporarily invisible to other workers <ul> <li>Allows for reliability.</li> </ul> </li> </ul> <ul> <li>APIs <ul> <li>Create a CloudQueueClient using account and credentials</li> <li>Create a CloudQueue using the client and GetQueueReference - queue name</li> <li>CreateIfNotExist to create it if not there</li> <li>Create a CloudQueueMessage with content</li> <li>Use CloudQueue.AddMessage to add it to the queue</li> <li>Use CloudQueue.GetMessage to get it out (passing invisibility time)</li> </ul> </li> </ul> <ul> <li>Tips on Queues <ul> <li>Messages up to 8 KB in size <ul> <li>Put in a blob if more and send blob pointer as message</li> </ul> </li> </ul> <ul> <li>Remember that a message can be processed more than once. <ul> <li>Make that not be a problem - idempotent</li> </ul> </li> </ul> <ul> <li>Assume messages are not processed in any particular order</li> <li>Queues can handle up to about 500 messages/second. <ul> <li>For higher throughput - batch items into a blob and send a message with reference to blob containing 10 work items.</li> <li>Worker does 10 items at a time.</li> <li>Increased throughput by 10x.</li> </ul> </li> </ul> <ul> <li>Use DequeueCount to remove "poison messages" that seem to be repeatedly crashing workers.</li> <li>Monitor message count to increase/decrease worker instances using service management APIs.</li> </ul> </li> </ul> <ul> <li>Q: can you set priorities on queue messages? <ul> <li>A: No - would have to create different queues</li> </ul> </li> </ul> <ul> <li>Q: Are blobs stored within the EU complying with the EU privacy policies? <ul> <li>A: Microsoft has a standard privacy policy which we adhere to.</li> </ul> </li> </ul> </li> </ul><img src="" width="1" height="1">MikeKelly Azure Developer Overview - Notes<p>I am at the <a href="">Azure Firestarter</a> event in Redmond today and just heard <a href="">Steve Marx</a> give a lap around the platform. Here are my notes; slides and sample code are to be posted later and I will update the post with them when they are.</p> <p>Idea behind Azure platform - we no longer think about transistors and what gates do I use to thinking about chips - how do I write machine code - then assembly and high-level languages. How do I connect to these different devices? Adding OS to abstract the basic needs of memory management, chips, devices, etc. We don't program to the machine layer, we program to the OS layer. But now building apps that run on many different machines - with minimal support from the OS. You have to think about too much low-level stuff - what load-balancer to get, whether the router is configured correctly, what version of the OS is on each of the servers, etc.</p> <p>Azure is to provide an abstraction that lets you think about data centers rather than those low-level details. </p> <p>.NET, PHP, Ruby, Java, … whatever</p> <ul> <li>Windows Azure is not an operating system. The OS is Windows. There is a layer on top of Windows that provides a platform.</li> <li>Anything that can be copy deployed to a Windows Server 2008 machine is probably going to be fine porting to Azure. Anything that requires more than a copy deployment might need more work.</li> <li>Can do create new .ASP net project and add to solution - and it will work.</li> <li>Csrun /devfabric:shutdown - F5 in VS just calls out to the command line tools to execute the dev fabric </li> <li>Upload starts a worker role instance to transfer the file into a blob, then generate a thumbnail.</li> <li>How it works… <ul> <li>Two roles <ul> <li>AnnoySmarxWeb is the ASP.Net MVC app to show the UI</li> <li>Thumbnail Generator generates the thumbnail.</li> <li>Upload code <ul> <li>Upload the file Request.Files[0] is the file uploaded</li> <li>Uploadfromstream on the blob to get it.</li> <li>The creates a cloudqueue and adds a message with the GUID name of the blob that was uploaded.</li> <li>Worker role just finds the full-size blob in storage and generates thumbnail.</li> </ul> </li> </ul> <ul> <li>Thumbnail generator <ul> <li>Reliable queues don't automatically dequeue the message - so that if you die while processing it, it will stay on the queue. It's just "invisible" while you're processing it. Then when you finish, you dequeue it using DeleteMessage. <ul> <li>Need to design for multiple workers dequeuing the same message and doing the work on it. Reason is that the message will reappear on the queue if you don't dequeue it, and another worker could then get it even though one worker has done most or all of the work on it. Two scenarios: <ul> <li>One worker dequeues, does all the work and then keels over dead before being able to delete it from the queue</li> <li>One worker dequeues it, does all the work and then before he gets to delete it, the wait time expires and so it becomes visible again on the queue. This could happen due to unusual network conditions. So think about the invisible time to be long enough to make this very unusual.</li> <li>Won't typically happen -so OK if your performance is bad if it happens, but you have to be able to handle it.</li> <li>Messages will be deleted from the queue if not dequeued after 7 days.</li> </ul> </li> </ul> </li> </ul> <ul> <li>Setting the cachecontrol allows the CDN in 18 different countries to cache it.</li> <li>Messages are limited to 8KB. <ul> <li>For more data, create a blob and reference the blob in the message. </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <ul> <li>Q: Is Azure PCI compliant? <ul> <li>It is possible to build PCI-compliant systems using Windows Azure, but Azure is not itself PCI compliant.</li> </ul> </li> </ul> <ul> <li>Q: What is the limit on Azure scale-out? <ul> <li>Compute - Need a credit check to go beyond 20 instances.</li> <li>Storage - Scale up 1 GB, 10 GB and 50 GB database options. Then have as many databases as you want. <ul> <li>10 GB database costs about $100/month.</li> <li>So for massive scale, want to probably use another option. <ul> <li>15 cents per Gigabyte per month for Windows Azure storage - so 10 GB would cost $1.50 per month.</li> <li>Only one index = the key.</li> <li>No join, no group by, no sort</li> <li>Automatically partition, replication (3x), strong write consistency, optimistic concurrency.</li> </ul> </li> </ul> <ul> <li>For SQL, go to the Azure portal, ask for a new database, specify the size and get a connection string you use in your code.</li> </ul> </li> </ul> </li> </ul> <ul> <li>ADO.NET Data Services == Astoria == Odata == WCF Data Services == REST API to data</li> <li>Q: Does blob store expose WebDAV? A: No but you could write your own. Blob store exposes REST API.</li> <li>Connectivity <ul> <li>How did the wallpaper change on Smarx's desktop when the blob was uploaded to the cloud?</li> <li>Service Bus and Access Control a/k/a Windows Azure Platform AppFabric <ul> <li>Service Bus solves the problem of having two apps behind firewalls but want to talk to each other. <ul> <li>Manages the relay</li> <li>Each makes outbound connections to the service bus in the cloud and the service bus manages the connection and if possible negotiates a P2P connection.</li> </ul> </li> </ul> <ul> <li>Common patterns <ul> <li>Eventing <ul> <li>One-way communication</li> <li>Unicast or multicast</li> <li>Immediate or buffered</li> </ul> </li> </ul> <ul> <li>Remoting <ul> <li>RCP, request/response, or duplex</li> </ul> </li> </ul> </li> </ul> <ul> <li>There is a sample with the app fabric SDK that shows how to send trace events.</li> </ul> </li> </ul> <ul> <li>Programming model for Service Bus is basically WCF but you switch a couple of bindings.</li> <li>There is a "hello world" kind of training in the SDK</li> <li>For the AnnoySmarx demo <ul> <li>The URL for the thumbnails in the display points to the service bus endpoint for set wallpaper. It's not that the Windows Azure service displaying the thumbnails is doing the change - you are in the browser by invoking the URL to change it.</li> <li>There is an interface that sets the wallpaper - called from browser</li> <li>Use ServiceBus.CreateServiceURI to figure out where to listen</li> </ul> </li> </ul> <ul> <li>ClemonsV has a good blog on using Service Bus</li> <li>Q: From the client perspective, is it push or pull? <ul> <li>It's a bit of both. Both sides establish a connection with the service bus.</li> <li>From the programming model, it looks like push. But then eventually something gets sent down through the connection because something happened on the other end.</li> <li>Client code just sits there and listens.</li> </ul> </li> </ul> <ul> <li>Pricing model is per connection.</li> <li>Access Control <ul> <li>About claims-based authentication on top of REST APIs.</li> <li>It does Active Directory federation.</li> <li>Uses OAuth WRAP and simple web tokens.</li> <li>Core scenario <ul> <li>I have a REST API and I want to give people access using claims-based authentication but I don't want to write all the goo to do that.</li> <li>Client that wants access to the service talks to the Access Control service to request an access token for the service.</li> <li>Access Control returns a simple web token.</li> <li>When client invokes the REST Service, it passes the access token.</li> <li>The REST service needs some code <ul> <li>The service maintains a periodic connection to the Access Control service to keep a trust relationship between them.</li> <li>The service has to accept the access token on a request</li> </ul> </li> </ul> <ul> <li>If you've used OpenID, it's a similar idea.</li> </ul> </li> </ul> </li> </ul> </li> </ul><img src="" width="1" height="1">MikeKelly PowerShell Cmdlet for Managing Windows Azure Diagnostics<p>I decided to write a PowerShell cmdlet to manage Windows Azure diagnostics. This cmdlet will let you retrieve and delete log information in the Azure cloud for your service; right now there isn’t any easy way to do this.</p> <p>I started out by writing a simple spec for my tool; you can see it <a href="" target="_blank">here</a>. The spec just lets me flesh out some of the design issues before writing code.</p> <p>I found that there is a <a href="" target="_blank">PowerShell 2.0 SDK</a> released a couple of months ago; I installed that. </p> ).</p> <p>I wnt to add a reference to System.Management.Automation as <a href="" target="_blank">MSDN told me to</a>. However, that doesn’t work. VS 2010 allows you to add a reference to System.Management, but not System.Management.<strong>Automation</strong>. After poking around a bit on the web, I found a <a href="" target="_blank">post on Stack Overflow</a> that provided the work-around.</p> <p>I implemented a bunch of properties for my parameters and wrote a very simple ProcessRecord override just to make sure I was on the right track. I added a simple class that inherits from PSSnapIn (System.Configuration.Install) to provide the basic properties of the snap-in. The MSDN article referenced below does a good job of explaining this.</p> <p>After doing this basic work, I wanted to install this as a PowerShell Cmdlet to make sure I’m on the right track. I built the Assembly in Visual Studio, and then started up PowerShell (which you can find in Start / Accessories / Windows PowerShell) and used a .NET tool called InstallUtil.exe to install the assembly so that PowerShell can find it. Note that you have to run PowerShell as Administrator for this install step to work – it doesn’t have to be running as Administrator to run the snap-in but to install it, it has to write to protected areas of the registry.</p> <p><a href=""><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="snapin" border="0" alt="snapin" src="" width="762" height="431" /></a> </p> <p>You can check that the snap in has installed using the PowerShell command “get-PSSnapIn” with the “-reg” flag to show you want the snap-ins that are registered:</p> <p><a href=""><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="snapin2" border="0" alt="snapin2" src="" width="1033" height="328" /></a> </p> <blockquote> <p>However, there is a problem. When I try to add the snap-in to your PowerShell session, I get this error from PowerShell:</p> <p><font size="2" face="Courier New">Add-PSSnapin : Cannot load Windows PowerShell snap-in AzureDiagnosticsSnapIn because of the following error: Could not load file or assembly ':\users\Mike Kelly\Documents\Visual Studio 2010\Projects\AzureDiagnosticsCmdlet\AzureDiagnosticsCmdlet\bin\Debug\AzureDiagnosticsCmdlet.dll' or one of its dependencies. <font color="#ff0000">This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.</font> <br />At line:1 char:13 <br />+ add-pssnapin <<<< AzureDiagnosticsSnapIn <br /> + CategoryInfo : InvalidArgument: (AzureDiagnosticsSnapIn:String) [Add-PSSnapin], PSSnapInException <br /> + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand</font></p> <p>There are two possible workarounds here:</p> <ul> <li>One is described on <a href="" target="_blank">StackOverflow</a> – it is to get PowerShell (and everything else) to run using .NET 4. I felt like this could cause other problems.</li> <li>The other workaround is to change the properties of the Cmdlet to require only .NET 3.5 instead of .NET 4. To do that, go to Visual Studio and right click on the Cmdlet solution. Select Properties and change “Target Framework” from “.NET Framework 4” to “.NET Framework 3.5”. OK the dialog telling you that the project must be closed and reopened. Then rebuild the Cmdlet and it will now work in PowerShell. Since I have no .NET 4 dependencies, this is an easier workaround for me. </li> </ul> <p>Finally, I wanted to be able to debug the Cmdlet in Visual Studio. I found a posting <a href="" target="_blank">here</a> describing how to do this – but it didn’t work with the Visual Studio 2010 RC build I have. I have entered a bug against the RC on this.</p> <p>So I rolled back to Visual Studio 2008, which I still have installed, and rebuilt the project there (because VS 2008 can’t read 2010 projects, I had to manually reconstruct the solution and project from the source files in VS 2008). In the process of doing this, I also found a <a href="" target="_blank">post</a> with (to me) simpler directions for debugging in Visual Studio. I am now happily debugging my Cmdlet in VS.</p> </blockquote> <h2>References</h2> <ul> <li><a href="" target="_blank">MSDN Article on PowerShell Cmdlets</a> </li> <li><a href="" target="_blank">Blog post on debugging Cmdlets using Visual Studio</a></li> </ul><img src="" width="1" height="1">MikeKelly | http://blogs.msdn.com/b/mikekelly/atom.aspx | CC-MAIN-2015-14 | refinedweb | 17,329 | 61.36 |
Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of an array are checked and swapped if they are in wrong order and this process is repeated until we get a sorted array. The steps of performing a bubble sort are:
- Compare the first and the second element of the array and swap them if they are in wrong order.
- Compare the second and the third element of the array and swap them if they are in wrong order.
- Proceed till the last element of the array in a similar fashion.
- Repeat all of the above steps until the array is sorted.
This will be more clear by the following visualizations.
Initial array
First iteration
SWAP
SWAP
Second iteration
SWAP
SWAP
Third iteration
No swap → Sorted → break the loop
Let’s code this up.
#include <stdio.h> #include <math.h> int main() { int a[] = {16, 19, 11, 15, 10, 12, 14}; int i,j; //repeating loop 7 (number of elements in the array) times for(j = 0; j<7; j++) { //initially swapped is false int swapped = 0; i = 0; while(i<7-1) { //comparing the adjacent elements if (a[i] > a[i+1]) { //swapping int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; //Changing the value of swapped swapped = 1; } i++; } //if swapped is false then the array is sorted //we can stop the loop if (!swapped) break; } for(i=0;i<7;i++) printf("%d\n",a[i]); return 0; }
In this code, we are just comparing the adjacents elements and swapping them if they are not in order. We are repeating this process 7 times (number of elements in the array). We have also assigned a variable ‘swapped’ and making it 1 (True) if any two elements get swapped in an iteration. If no interchanging of elements happens then the array is already sorted and thus no change in the value of the ‘swapped’ happens and we can break the loop. | https://www.codesdope.com/blog/article/sorting-an-array-using-bubble-sort-in-c/ | CC-MAIN-2021-39 | refinedweb | 331 | 66.37 |
Peter Norvig wrote a simple spelling corrector in 20 lines of Python
2.5,
so I thought I’d see what it looks like in Ruby. I’m not too pleased
with
my version, if anyone can make it more elegant, that would be great.
Some
of the sticking points were:
List comprehensions in Python made the edits1 function more elegant
IMO. Hopefully someone can improve that function.
The boolean expression in the correct function evaluates empty
sets/arrays as false in Python but not in Ruby, so I had to add the
“result.empty? ? nil : result” expression to several functions. I expect
there’s a better way to handle this also.
Minor point, but apparently Python has a built in constant for the
set
of lower case characters “string.lowercase”, so I just defined a
constant.
Otherwise, the translation was pretty straightforward.
Here’s a link to Norvig’s page:
That page includes a link to a text file that I saved locally as
holmes.txt:
Note: I wrapped a few of the longer lines for posting.
def words text
text.downcase.scan(/[a-z]+/)
end
def train features
model = Hash.new(1)
features.each {|f| model[f] += 1 }
return model
end
NWORDS = train(words(File.new(‘holmes.txt’).read))
LETTERS = ‘abcdefghijklmnopqrstuvwxyz’
Brian A. | https://www.ruby-forum.com/t/how-to-write-a-spelling-corrector/91526 | CC-MAIN-2021-25 | refinedweb | 215 | 68.57 |
REST, SOAP & default endpoints
When you create a service, there are by default three endpoints:
- User-defined REST endpoint
- SOAP endpoint:
/[soap11|soap12]
- Default endpoint:
/[xml|json|html|jsv|csv]/[reply|oneway]/[servicename]
The preferred way to call the webservice is mostly using the REST endpoint. As you have seen, user-defined REST endpoints can be configured with the
Route attribute for each request DTO.
But you can also call your service by using the default endpoint, without configuring a REST url with the default endpoint. Of course there’s always the option to use the SOAP endpoint.
Sample requests:
The possible requests for the following request DTO are:
[Route("/hello")] public class Hello { public string Name { get; set; } }
Option 1
SOAP endpoint
POST example.org/soap11
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns: <soap:Body> <Hello xmlns: <Name>String</Name> </Hello> </soap:Body> </soap:Envelope>
Rest endpoint:
POST example.org/hello
{"Name":"World"}
Default endpoint:
POST example.org/json/reply/Hello
{"Name":"World"}
Option 2
But you don’t need to pass the
Name of the request DTO in the request body. There’s also the possibility to set the value of
Name with URL parameters (works only with REST and default endpoint of course).
REST endpoint:
POST example.org/hello?Name=World
Default endpoint:
POST example.org/json/reply/Hello?Name=World
You can also combine the two approaches.
Option 3
Last but not least there exists another way to set the value of
Name! But this works only with the REST endpoint:
If you add the following mapping to the request DTO above:
[Route("/hello/{Name}")]
…you will be able to set the name in the URL itself, without any URL parameters:
Rest endpoint:
GET example.org/hello/World
As you can see
{Name} (in the mapping) is the placeholder for the value of the property
Name.
Tip: The last two approaches are mostly used for GET and DELETE requests, because often clients don’t support to attach a request body for these HTTP methods.
Tip: As you may have noticed, ServiceStack is also capable to support different formats (JSON, XML, etc). There exists another separate tutorial about formats. | http://docs.servicestack.net/endpoints | CC-MAIN-2020-34 | refinedweb | 365 | 53.71 |
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Microcontroller Programming » How do I increase the sampling time of my circuit
I have been working on a project, where I would create a simple voltage recording device.I do it by
using the ADC in the ATMEGA 328 microcontroller, and the I2C controlled memory chip (24LC128) and Digital to Analog Converter (MAX518).
I used Fleury's code to write to these chips. My program is supposed to first display the message "Record" on the LCD. When it is in record mode,
you could insert a voltage into the ADC, where it would convert it into a digital number, and then store the digital value into the memory chip.
After a few seconds, the LCD would display the message "Play" and when it is play mode, the memory chip would output its values into the Digital to Analog Converter.
The DAC would of course convert it to an analog signal. So basically an analog voltage is stored and then played back. For example, I first connected a potentiometer
to the input of the ADC so that I could vary the voltage. When I was in record mode, I set the voltage to 0 volts and gradually set it to 5 volts.
When the program was in play mode, the DAC output started at 0 volts and gradually climbed up the same way.
My program technically works but not like I want it to. When I use the potentiometer to vary the voltage, the circuit worked. I also tried another experiment where I
used another ATMEGA 328 to cause an output pin to blink a LED in a certain way. I then connected the output pin of that microcontroller to the ADC input pin of
the other microcontroller. As predicted, the microcontroller copied the signal in record mode and the DAC caused the LED to blink in the same way in play mode.
Basically the circuit works fine if I vary the input voltage slowly. However, it doesn't work so well when the input frequency is faster. For example, I used
the first microcontroller to play music. The easiest way to do that it to connect an output pin to a speaker, and then make the output pin turn off an on at one
frequency to play one note and at another frequency to play another note. Once I knew that the program worked (because I heard my music), I connected the output pin of
the first microcontroller to the ADC input of the other microcontroller. Then I connected the speaker to the DAC output pin. I expected the speaker to play the same tune
when the program was in play mode but it does nothing more than click a few times each second.
My theory of why it didn't work is because my program doesn't sample high enough to capture higher frequencies. Do you think that is the problem or is there anything
else that I am missing? If my program doesn't sample fast enough then how do I fix it? Is there something I could do in the program to speed it up or do I have to get faster
chips?
#define F_CPU 14745600
#include <stdio.h>
#include <avr/pgmspace.h>
#include <inttypes.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/delay.h"
#include "../libnerdkits/io_328p.h"
#define DEV24LC128 0xA0 // device address of EEPROM 24C02, see datasheet
#define MAX518 0x58 //device address for the MAX518 DAC
int j;
int i;
int t;
int16_t z;
int16_t ret;
void intitialvalues ();
uint16_t result;
void memorywrite ();
void memoryread ();
void DAC ();
int ADC1 ();
int main ()
{
while (1)
{
initialvalues ();
lcd_init();
lcd_line_four();
lcd_write_string(PSTR("recording "));
memorywrite ();
lcd_line_four();
lcd_write_string(PSTR("playing "));
memoryread();
}
}
int ADC1 ()
{
ADCSRA |= (1<<ADSC);
uint16_t low = ADCL;
uint16_t high = ADCH;
result = low + (high<<8);
result = result>>2; //result is shifted over so that the 10 digit value becomes two digits.
return result; //The last two digits are cropped
}
void DAC()//sends information to the DAC
{
i2c_start_wait(MAX518+I2C_WRITE);
i2c_write(0x00);
i2c_write(ret);
}
void initialvalues ()
{
i2c_init();
j=0;
i=0;
ADMUX = 0; // set analog to digital converter for external //reference (5v), single ended input ADC0
ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
// set analog to digital converter
// to be enabled, with a clock prescale of 1/128
// so that the ADC clock runs at 115.2kHz.
}
void memorywrite ()//Reads from the ADC and writes to the EPROM
{
j=0; //j is upper address bit for the serial EPROM
i=0; //i is the lower memory bit fot the serial EPROM
for (j=0;j<128;j++)
{
for (i=0;i<256;i+=64)
{
i2c_start_wait(DEV24LC128 +I2C_WRITE); // set device address and write mode
i2c_write(j);
i2c_write(i);
for (t=0;t<64;t++)
{
z = ADC1 (); //read value from ADC
i2c_write(z); //store ADC value in the memory chip
}
i2c_stop();
}
}
void memoryread ()//Reads from the EPROM and sends to the DAC
{
for (j=0;j<128;j++) //j is upper address bit for the serial EPROM
{
for (i=0;i<256;i++)//i is lower address bit for the serial EPROM
{
i2c_start_wait(DEV24LC128 +I2C_WRITE);// set device address and write mode
i2c_write(j);
i2c_write(i);
i2c_rep_start(DEV24LC128 +I2C_READ);
ret = i2c_readAck(); //ret reads the value from the serial EPROM
DAC();// This sends value to the DAC
i2c_stop();
}
}
}
Did you search the forum on 'adc sampling rate'? There are several threads on the subject.
jmuthe-
You haven't provided some fundamental information-- what is the max frequency you're trying to capture/replay?
BM
I think I may not have not been too clear in my first post. When I said that the sampling rate might be to slow, I didn't mean just the ADC sampling rate. When I say the sampling rate in Record mode, I mean the total time it takes for the ADC to read the input voltage and send it to the EPROM. In Play mode, I mean the time the program takes to extract the data from the EPROM, send it to the DAC, and then have the DAC convert it to an analog voltage. The problem with this setup, is that it can only be as fast as its weakest link. For example, if the the ADC and DAC are fast but the EPROM is slow then this won't sample fast enough.
In response to BobaMosfet's question, I eventually want to make a simple recording device that will record sound. Since the maximum frequency that humans can hear is 20,000 Hz, I want to be able to capture and play something up to that frequency. I believe that the sampling rate should be at least twice the frequency so I would like it to be 40,000 Hz. I don't expect to make a perfect recording device that will sound crisp and clear so if some of the higher frequencies are cut off then that is okay. However, I would like it to at least sound close to the sound I am trying to record. Based on the components I am using, and the program I wrote, would I be able to do this or do I need different components for this job.
Says here it takes 3.3ms to write the eeprom so that would be around 300hz. Even if your eeprom could write 3 times faster at 1ms that still only 1khz recording. You need something that can write around 100 times faster. Maybe there is serial interface ram that will work for you.
I am using a serial interface to store my data. I am using the I2C controlled memory chip (24LC128)and I tried the 24LC256.
Your memory chips are eeprom and they still require some amount of time to complete a write cycle. I think that time is close to any other eeprom write which is around a couple of ms. You could write a little test program and see how long it takes to write a byte to your memory chip if you want to know for sure.
jmuthe--
Step away from the protocol and the chips for a moment. Ask yourself one question. How much time do I have to process 1 cycle at the desired frequency? Once you know that, you have your design requirement. Will the protocols and other components work fast enough to give you time to process a cycle at that speed, including obvious overhead.
Anyway to buffer before writing to EEPROM?
Ralph
Please log in to post a reply. | http://www.nerdkits.com/forum/thread/2800/ | CC-MAIN-2020-05 | refinedweb | 1,431 | 68.3 |
angr has moved from python 2 to python 3! We took this opportunity of a major version bump to make a few breaking API changes that improve quality-of-life.
To begin, just the standard py3k changes, the relevant parts of which we'll rehash here as a reference guide:
Strings and bytestrings
Strings are now unicode by default, a new
bytes type holds bytestrings
Bytestring literals can be constructued with the b prefix, like
b'ABCD'
Conversion between strings and bytestrings happens with
.encode() and
.decode(), which use utf-8 as a default. The
latin-1 codec will map byte values to their equivilant unicode codepoints
The
ord() and
chr() functions operate on strings, not bytestrings
Enumerating over or indexing into bytestrings produces an unsigned 8 bit integer, not a 1-byte bytestring
Bytestrings have all the string manipulation functions present on strings, including
join,
upper/
lower,
translate, etc
hex and
base64 are no longer string encoding codecs. For hex, use
bytes.fromhex() and
bytes.hex(). For base64 use the
base64 module.
Builtin functions
exec are now builtin functions instead of statements
Many builtin functions previously returning lists now return iterators, such as
map,
filter, and
zip.
reduce is no longer a builtin; you have to import it from
functools.
Numbers
The
/ operator is explicitly floating-point division, the
// operator is expliclty integer division. The magic functions for overriding these ops are
__truediv__ and
__floordiv__
The int and long types have been merged, there is only int now
Dictionary objects have had their
.iterkeys,
.itervalues, and
.iteritems methods removed, and then non-iter versions have been made to return efficient iterators
Comparisons between objects of very different types (such as between strings and ints) will raise an exception
In terms of how this has affected angr, any string that represents data from the emulated program will be a bytestring. This means that where you previously said
state.solver.eval(x, cast_to=str) you should now say
cast_to=bytes. When creating concrete bitvectors from strings (including implicitly by just making a comparison against a string) these should be bytestrings. If they are not they will be utf-8 converted and a warning will be printed. Symbol names should be unicode strings.
For division, however, ASTs are strongly typed so they will treat both division operators as the kind of division that makes sense for their type.
The memory object in CLE (project.loader.memory, not state.memory) has had a few breaking API changes since the bytes type is much nicer to work with than the py2 string for this specific case, and the old API was an inconsistent mess.
Additionally,
pack_word and
unpack_word now take optional
size,
endness, and
signed parameters. We have also added
memory.pack(addr, fmt, *data) and
memory.unpack(addr, fmt), which take format strings for use with the
struct module.
If you were using the
cbackers or
read_bytes_c functions, the conversion is a little more complicated - we were able to remove the split notion of "backers" and "updates" and replaced all backers with bytearrays that we mutate, so we can work directly with the backer objects. The
backers() function iterates through all bottom-level backer objects and their start addresses. You can provide an optional address to the function, and it will skip over all backers that end before that address.
Here is some sample code for producing a C-pointer to a given address:
import cffi, cleffi = cffi.FFI()ld = cle.Loader('/bin/true')addr = ld.main_object.entrytry:backer_start, backer = next(ld.memory.backers(addr))except StopIteration:raise Exception("not mapped")if backer_start > addr:raise Exception("not mapped")cbacker = ffi.from_buffer(backer)addr_pointer = cbacker + (addr - backer_start)
You should not have to use this if you aren't passing the data to a native library - the normal load methods should now be more than fast enough for intensive use.
Previously, your mechanisms for looking up symbols by their address were
loader.find_symbol() and
object.symbols_by_addr, where there was clearly some overlap. However,
symbols_by_addr stayed because it was the only way to enumerate symbols in an object. This has changed!
symbols_by_addr is deprecated and here is now
object.symbols, a sorted list of Symbol objects, to enumerate symbols in a binary.
Additionally, you can now enumerate all symbols in the entire project with
loader.symbols. This change has also enabled us to add a
fuzzy parameter to
find_symbol (returns the first symbol before the given address) and make the output of
loader.describe_addr much nicer (shows offset from closest symbol).
All parameters in cle that started with
custom_ - so,
custom_base_addr,
custom_entry_point,
custom_offset,
custom_arch, and
custom_ld_path - have had the
custom_ removed from the beginning of their names.
All the functions that were deprecated more than a year ago (at or before the angr 7 release) have been removed.
state.se has been deprecated.
You should have been using
state.solver for the past few years.
Support for immutable simulation managers has been removed.
So far as we're aware, nobody was actually useing this, and it was making debugging a pain. | https://docs.angr.io/appendix/migration | CC-MAIN-2019-51 | refinedweb | 845 | 55.54 |
This action might not be possible to undo. Are you sure you want to continue?
Cat. No. 15000U Department of the Treasury Internal Revenue Service
Contents
Introduction ............................................... Who Must File ............................................ Filing Status ............................................... Exemptions ................................................ 2 2 4 8
Exemptions, Standard Deduction, and Filing Information
For use in preparing
Standard Deduction ................................. 17 1996 Standard Deduction Tables ............................................ 18 Foster Child or Adult ................................ 19 How To Get More Information................ 20 Index ........................................................... 21
Important Changes for 1996
Social security number for dependents. You must provide the social security number (SSN) of any person you claim as a dependent regardless of the dependent’s age. However, a social security number is not required for 1996 for a child born during December of 1996. If you do not list the dependent’s SSN when required or if you list an incorrect SSN, the exemption may be disallowed. Taxpayer identification number for aliens. If you, your spouse, or your dependent is a nonresident or resident alien who does not have — and is not eligible to get — a social security number, file Form W-7 with the IRS to apply for an individual taxpayer identification number (ITIN). You enter this number on your tax return wherever the SSN is requested, and you use it for tax purposes only. An ITIN does not entitle you to social security benefits or change your employment or immigration status under U.S. law. Exemption amount. The amount you can deduct as an exemption has increased from $2,500 in 1995 to $2,550 in 1996. Exemption phaseout. You will lose all or part of the benefit of your exemptions if your adjusted gross income goes above a certain level. In 1996, the income level ranges from $88,475 (for married filing separately) to $176,950 (for married filing jointly) depending upon your filing status. See Phaseout of Exemptions, later. Standard deduction. The standard deduction for taxpayers who do not itemize deductions on Schedule A of Form 1040 is higher in 1996 than it was in 1995. The amount depends upon your filing status. The 1996 Standard Deduction Tables are shown later as Tables 6, 7, and 8. Itemized deductions. The amount you may deduct for itemized deductions is limited if your adjusted gross income is more than $117,950 ($58,975 if you are married filing separately). See Who Should Itemize, later.
1996
Returns
Important Reminders
Election to claim child’s unearned income on parent’s return. You may be able to include your child’s interest and dividend income on your tax return by using Form 8814, Parents’ Election To Report Child’s Interest and Dividends. If you choose to do this, your child will not file a return. Change of address. If you change your mailing address, be sure to notify the IRS using Form 8822, Change of Address. Mail it to the Internal Revenue Service Center for your old address. (Addresses for the Service Centers are on the back of the form.)
Nonresident aliens. If you are a nonresident alien, the rules and tax forms that apply to you may be different from those that apply to U.S. citizens. See Publication 519.
Useful Items
You may want to see: Publication
□
54 Tax Guide for U.S. Citizens and Resident Aliens Abroad 519 U.S. Tax Guide for Aliens 520 Scholarships and Fellowships 533 Self-Employment Tax 555 Community Property 559 Survivors, Executors, and Administrators 596 Earned Income Credit 929 Tax Rules for Children and Dependents
□ □ □ □ □
Self-employed persons. If you are selfemployed in a business that provides services (where products are not a factor), gross income is gross receipts from that business. If you are self-employed in a business involving manufacturing, merchandising, or mining, gross income is total sales from that business less cost of goods sold. To this figure you add any income from investments and from incidental or outside operations or sources. You must file Form 1040 if you owe any self-employment tax. Self-employment tax is discussed later under Other Situations.
Marital status. Your marital status is determined as of the last day of your tax year, which is December 31 for most taxpayers. Your filing status generally depends upon whether you are single or married and whether you maintained a household for at least half the year for yourself and one other person. Filing status and dependents are discussed in detail later in this publication. Age. Age is a factor in determining if you must file a return only if you are 65 or older at the end of your tax year. You are considered to be age 65 for 1996 if your 65th birthday is on or before January 1, 1997.
Introduction
This publication discusses some tax laws that affect every person who may have to file a federal income tax return. It provides answers to some basic questions: who must file; who should file; what filing status to choose; how many exemptions to claim; and the amount of the standard deduction. The first section of this publication explains who must file an income tax return. If you have little or no gross income, reading this section will help you decide if you need to file a return. The second section is about who should file a return. Reading this section will help you decide if you should file, even if you are not required to file. The third section helps you determine what filing status you can use. Filing status is important in determining your filing requirements, your standard deduction, and your tax rate. It also helps determine what credits you may be entitled to. The fourth section discusses exemptions, which reduce your taxable income. The discussions include the social security number requirement for dependents, the rules for multiple support agreements, and the rules for divorced or separated parents. The fifth section gives the rules and dollar amounts for the standard deduction — a benefit for taxpayers who do not itemize their deductions. This section also discusses the standard deduction for nonitemizing taxpayers who are blind or age 65 or older, and special rules for dependents. In addition, this section may help you decide which method — taking a standard deduction or itemizing deductions — is better for you. The last section covers special rules for taxpayers who take care of foster children or adults. You may have to include certain payments in income but may have deductible expenses too.. Page 2
□ □
Form (and Instructions)
□ □ □
1040X
Amended U.S. Individual Income Tax Return
2848 Power of Attorney and Declaration of Representative 4868 Application for Automatic Extension of Time To File U.S. Individual Income Tax Return 8332 Release of Claim to Exemption for Child of Divorced or Separated Parents 8814 Parents’ Election To Report Child’s Interest and Dividends 8822 Change of Address Schedule SE (Form 1040) SelfEmployment Tax
□
Filing Requirements for Most Taxpayers
You must file a return if your gross income for the year was at least the amount shown on the appropriate line in Table 1. Dependents should see Dependents, later.
□ □ □
Deceased Persons
You must file an income tax return for a decedent (a person who died) if: 1) You are the surviving spouse, executor, administrator, or legal representative, and
Who Must File
If you are a U.S. citizen or resident, your filing requirement depends upon your gross income, your filing status, your age, and whether you can be claimed as a dependent. You must also file if one of the situations described under Other Situations applies. Failure to file when required may result in penalties. Willful failure to file may result in criminal prosecution. The filing requirements apply even if you owe no tax. For information on what form to use — Form 1040EZ, Form 1040A, or Form 1040 — see the instructions in your tax package. Gross income. Gross income is all income you receive in the form of money, goods, property, and services that is not exempt from tax. If you are married and live with your spouse in a community property state, half of any income described by state law as community income may be considered yours. For a list of community property states, see Community property states, under Separate Returns, later.
2) The decedent met the filing requirements at the time of his or her death. For more information, see Final Return for Decedent in Publication 559, Survivors, Executors, and Administrators.
U.S. Citizens or Residents Living Abroad
You must include all income earned abroad as gross income to determine whether you must file. This is true even if you qualify for the foreign earned income exclusion. For more information on special tax rules that may apply to you, see Publication 54, Tax Guide for U.S. Citizens and Resident Aliens Abroad.
Sale of Residence
If you are 55 or older and sold a home during the year, part or all of your gain may not be subject to federal tax. However, you must include your entire gain as gross income to determine whether you must file.
Table 1. 1996 Filing Requirements Chart for Most Taxpayers
To use this chart, first find your filing status. Then, read across to find your age at the end of 1996. You must file a return if your gross income** was at least the amount shown in the last column. Filing Status Single Age* under 65 65 or older under 65 65 or older under 65 (both spouses) Married, filing jointly*** 65 or older (one spouse) 65 or older (both spouses) any age under 65 65 or older Gross Income** $6,550 $7,550 $8,450 $9,450 $11,800 $12,600 $13,400 $2,550 $9,250 $10,050
For more information, see Parent’s Election To Report Child’s Unearned Income in Publication 929, and Form 8814.
Other Situations
Some persons must file a tax return even though their gross income is less than the amount shown earlier for their filing status. See Table 3 for other situations when you must file. If you are a U.S. citizen who lived in a U.S. possession or had income from a U.S. possession, different rules apply. Get Publication 570, Tax Guide for Individuals With Income from U.S. Possessions. Self-employment tax. If you are self-employed, you must file a return and pay self-employment tax if you had net earnings from selfemployment of $400 or more. The $400 net earnings figure applies to self-employed persons of any age. You must include your selfemployment income in your gross income for income tax purposes even if your net self-employment income is less than $400. You are self-employed if you carry on a trade or business as a sole proprietor, are an independent contractor or a member of a partnership, or are otherwise in business for yourself. You can be self-employed even if the work you do is part time or in addition to your regular job. Net earnings from self-employment generally is the net income (gross income minus deductible business expenses) from your business or profession. The self-employment tax you must pay is comparable to the social security and Medicare taxes withheld from an employee’s wages. If you are self-employed, report your selfemployment tax on Schedule SE (Form 1040), Self-Employment Tax, and attach it to your Form 1040. See Publication 533 for more information. Nonresident alien and dual-status alien. If you were a resident alien and a nonresident alien during the same tax year, you are a dualstatus alien. Different rules apply for the part of the year you were a resident of the United States and the part of the year you were a nonresident alien. If you were a nonresident alien for any part of the year, see Publication 519.
Head of household
Married, filing separately Qualifying widow(er) with dependent child
* If you turned age 65 on January 1, 1997, you are considered to be age 65 at the end of 1996. ** Gross income means all income you received in the form of money, goods, property, and services that is not exempt from tax, including any gain on the sale of your home (even if you may exclude or postpone part or all of the gain). Do not include social security benefits unless you are married filing a separate return. * * * If you didn’t live with your spouse at the end of 1996 (or on the date your spouse died) and your gross income was at least $2,550, you must file a return regardless of your age.
Residents of Puerto Rico
Generally, if you are a U.S. citizen and a resident of Puerto Rico, you must file a U.S. income tax return if you meet the income requirements. This is in addition to any legal requirement you may have to file an income tax return for Puerto Rico. If you are a resident of Puerto Rico for the whole year, your U.S. gross income does not include income from sources within Puerto Rico. However, include in your U.S. gross income any income received for your services as an employee of the United States or any U.S. agency. If you receive income from Puerto Rican sources that is not subject to U.S. tax, you must make a special adjustment for your standard deduction to arrive at the income level for your requirement to file a U.S. income tax return. For more information, see Publication 570, Tax Guide for Individuals With Income From U.S. Possessions.
part of a scholarship that you must include in your gross income. See Publication 520 for more information on taxable and nontaxable scholarships. Unearned income. This is income such as interest, dividends, and capital gains. Trust distributions of interest, dividends, capital gains, and survivor annuities are considered unearned income also. Election to claim child’s unearned income on parents’ return. You may be able to include your child’s interest and dividend income on your tax return. If you choose to do this, your child is not required to file a return. However, all of the following conditions must be met. 1) Your child was under age 14 on January 1, 1997. 2) Your child had gross income only from interest and dividends (including Alaska Permanent Fund Dividends). 3) The interest and dividend income was less than $6,500. 4) No estimated tax payment was made for 1996 and no 1995 overpayment was applied to 1996 under your child’s name and social security number. 5) No federal income tax was withheld from your child’s income under the backup withholding rules. 6) You are the parent whose return must be used when making the election to claim your child’s unearned income.
Dependents
A person who can be claimed as a dependent by another taxpayer may have to file a return. This depends on whether the dependent has earned income, unearned income, or both. A dependent may also have to file if one of the situations described under Other Situations applies. Earned income. This is salaries, wages, professional fees, and other amounts received as pay for work you actually perform. Earned income (only for purposes of filing requirements and the standard deduction) also includes any
Who Should File
Even if you do not meet any of the filing requirements discussed earlier, you should file a tax return if one of the following applies. 1) You had income tax withheld from your pay. By filing a return, you can get a refund even if another taxpayer can claim you as a dependent. 2) You qualify for the earned income credit. See Publication 596 for more information.
Page 3
Table 2. 1996 Filing Requirements for Dependents
See Exemptions for Dependents to find out if someone can claim you as a dependent.
If your parent (or someone else) can claim you as a dependent, use this chart to see if you must file a return. In this table, unearned income includes taxable interest and dividends. Earned income includes wages, tips, and taxable scholarship and fellowship grants. Caution: If your gross income was $2,550 or more, you usually cannot be claimed as a dependent unless you were under age 19 or a student under age 24. For details, see Gross Income Test under Dependency Tests. Single dependents—Were you either age 65 or older or blind? □ No. You must file a return if— Your unearned the total of that income plus income was: AND your earned income was: $1 or more over $650 $0 over $4,000 □ Yes. You must file a return if any of the following apply. ● Your earned income was over $5,000 ($6,000 if 65 or older and blind), ● Your unearned income was over $1,650 ($2,650 if 65 or older and blind), ● Your gross income was more than— The larger of: This amount: $650 or your earned PLUS $1,000 ($2,000 if 65 income (up to $4,000) or older and blind) Married dependents—Were you either age 65 or older or blind? □ No. You must file a return if either of the following apply. ● Your gross income was at least $5 and your spouse files a separate return and itemizes deductions. ● Your unearned the total of that income plus income was: AND your earned income was: $1 or more over $650 $0 over $3,350
□
Filing Status
Your filing status is used in determining your filing requirements, standard deduction, and correct tax. It is also important in determining whether you are eligible to claim certain other deductions and credits. See Standard Deduction later for more information. Your correct tax is determined by using the Tax Rate Schedule or the column in the Tax Table that applies to your filing status. There are five filing statuses: Single Married Filing Jointly Married Filing Separately Head of Household Qualifying Widow(er) With Dependent Child If more than one filing status applies to you, choose the one that will give you the lowest tax. If you file Form 1040 or Form 1040A, indicate your filing status by checking the appropriate box on lines 1 through 5.
Marital Status
In general, your filing status depends on whether you are considered unmarried or married. Unmarried persons. You are considered unmarried for the whole year if, on the last day of your tax year, you are unmarried or separated from your spouse by a divorce or a separate maintenance decree. Divorced persons. State law governs whether you are married, divorced, or legally separated under a decree of separate maintenance. If you are divorced under a final decree by the last day of the year, you are considered unmarried for the whole year., and you do not remarry, you are considered unmarried for that tax year. You must also file amended returns (Form 1040X, Amended U.S. Individual Income Tax Return ).
Yes. You must file a return if any of the following apply. ● Your earned income was over $4,150 ($4,950 if 65 or older and blind), ● Your unearned income was over $1,450 ($2,250 if 65 or older and blind), ● Your gross income was at least $5 and your spouse files a separate return and itemizes deductions. ● Your gross income was more than— The larger of: This amount: $650 or your earned PLUS $800 ($1,600 if 65 income (up to $3,350) or older and blind)
Table 3. Other Situations When You Must File a 1996 Return
If any of the four conditions listed below applied to you for 1996, you must file a return. 1. You owe any special taxes, such as:
● ●
Social security and Medicare tax on tips you did not report to your employer. Uncollected social security and Medicare or RRTA tax on tips you reported to your employer. Uncollected social security and Medicare or RRTA tax on group-term life insurance. Alternative minimum tax. Tax on a qualified retirement plan, including an individual retirement arrangement (IRA). Tax from recapture of investment credit, low-income housing credit, federal mortgage subsidy, or qualified electric vehicle credit.
● ● ●
●
2. You received any advance earned income credit (AEIC) payments from your employer. These payments should be shown in box 9 of your Form W-2. 3. You had net earnings from self-employment of at least $400. 4. You had wages of $108.28 or more from a church or qualified church-controlled organization that is exempt from employer social security and Medicare taxes.
Page 4
Married persons. You and your spouse may be able to file a joint return, or you may file separate returns. Considered married. You are considered married for the whole year if on the last day of your tax year you are either: 1) Married and living together as husband and wife, 2) Living together in a common law marriage that is recognized in the state where you now live or in the state where the common law marriage began, 3) Married and living apart, but not legally separated under a decree of divorce or separate maintenance, or 4) Separated under an interlocutory (not final) decree of divorce. For purposes of filing a joint return you are not considered divorced.
Married Filing Jointly
You may choose married filing jointly. You may file a joint return even if one of you had no income or deductions. If you and your spouse each have income, you may want to figure your tax both on a joint return and on separate returns (using the filing status of married filing separately). Choose the method that gives you the lower tax. If you file as married filing jointly, you may use Form 1040EZ (if you have no dependents and are under 65 and not blind), Form 1040A, or Form 1040. If you file Form 1040A or Form 1040, show this filing status by checking the box on line 2. Use the Married filing jointly column of the Tax Table, or Schedule Y–1 of the Tax Rate Schedules, to figure your tax. Spouse died during the year. If your spouse died during the year, you are considered married for the whole year and may choose married filing jointly as your filing status. Divorced persons. If you are divorced under a final decree by the last day of the year, you are considered unmarried for the whole year and may not choose married filing jointly as your filing status.
benefited from the substantial understatement of tax. Normal support received from your spouse is not a significant benefit. Another consideration may be whether you were later divorced or deserted by your spouse. This exception applies only if your spouse’s action resulted in an understatement of tax of more than $500.. For purposes of this exception, community property rules do not apply to items of gross income (other than gross income from property). Divorced taxpayer. You may be held jointly and individually responsible for any tax, interest, and penalties due on a joint return filed before your divorce. This responsibility applies even if your divorce decree states that your former spouse will be responsible for any amounts due on previously filed joint returns. Signing a joint return. For a return to be considered a joint return, both husband and wife must generally sign the return. Spouse died before signing. If your spouse died before signing the return, the executor or administrator must sign the return for your spouse. If neither you nor anyone else has yet been appointed, you may sign the return for your spouse and write ‘‘Filing as surviving spouse’’ in the area where you sign the return. Spouse away from home. If your spouse is away from home, you should prepare the return, sign it, and send it to your spouse to sign so that it can be filed on time. Injury or disease prevents signing.. Signing as guardian of spouse. If you are the guardian of your spouse who is mentally incompetent, you may sign the return for your spouse as guardian. Spouse in combat zone. If your spouse is unable to sign the return because he or she is Page 5
Spouse died during the year. If your spouse died during the year, you are considered married for the whole year for filing status purposes. If you did not remarry before the end of the tax year, you may file a joint return for yourself and your deceased spouse. For the next 2 years, you may be entitled to the special benefits described later under Qualifying Widow(er) With Dependent Child. If you remarried before the end of the tax year, you may file a joint return with your new spouse. Your deceased spouse’s filing status is married filing separately for that year. Married persons living apart. If you live apart from your spouse and meet certain tests, you may be considered unmarried. Therefore, you may.
Filing a Joint Return
Both you and your spouse must include all of your income, exemptions, and deductions on your joint return. Accounting period. Both of you must use the same accounting period, but you may use different accounting methods. Joint responsibility. Both of you may be held responsible, jointly and individually, for the tax and any interest or penalty due on your joint return. One spouse may be held responsible for all the tax due even if all the income was earned by the other spouse. Innocent spouse exception. Under certain circumstances, you may not have to pay the tax, interest, and penalties on a joint return. You must establish that you did not know, and had no reason to know, that there was a substantial understatement of tax that resulted because your spouse: 1) Omitted a gross income item, or 2) Claimed a deduction, credit, or property basis in an amount for which there is no basis in fact or law. The facts and circumstances must also indicate that it is unfair for you to pay the tax due. One consideration is whether you significantly
Single
Your filing status is single if you are unmarried or separated from your spouse by a divorce or separate maintenance decree, and you do not qualify for another filing status. Your filing status may be single if you were widowed before January 1, 1996 and did not remarry in 1996. However, you might be able to use another filing status that will give you a lower tax. See Head of Household and Qualifying Widow(er) With Dependent Child to see if you qualify. You may file Form 1040EZ (if you have no dependents and are under 65 and not blind), Form 1040A, or Form 1040. If you file Form 1040A or Form 1040, show your filing status as single by checking the box on line 1. Use the Single column of the Tax Table, or Schedule X of the Tax Rate Schedules, to figure your tax.
serving in a combat zone, such as the Persian Gulf Area, or a qualified hazardous duty area (Bosnia and Herzegovina, Croatia, or Macedonia), and you do not have a power of attorney or other statement, you may sign for your spouse. Attach a signed statement to your return that explains that your spouse is serving in a combat zone. For more information on special tax rules for persons who are serving in a combat zone, get Publication 3, Armed Forces Tax Guide. Other reasons spouse cannot sign. If your spouse cannot sign the joint return for any other reason, you may sign for your spouse only if you are given a valid power of attorney (a legal document giving you permission to act for your spouse). Attach the power of attorney to your tax return. You may use Form 2848, Power of Attorney and Declaration of Representative. Nonresident alien or dual-status alien. A joint return generally cannot be made if either spouse is a nonresident alien at any time during the tax year. However, if at the end of the year one spouse was a nonresident alien or dual-status alien married to a U.S. citizen or resident, both spouses may choose to file a joint return. If you do file a joint return, you and your spouse are both treated as U.S. citizens or residents for the entire tax year. See Nonresident Spouse Treated as a Resident in Chapter 1 of Publication 519.
or was the dependent of someone else, you may not claim an exemption for him or her on your separate return. If you file as married filing separately, you may use Form 1040A or Form 1040. Select this filing status by checking the box on line 3 of either form. You must also write your spouse’s social security number and full name in the spaces provided. Use the Married filing separately column of the Tax Table or Schedule Y–2 of the Tax Rate Schedules to figure your tax.
Joint Return After Separate Returns
You may change your filing status by filing an amended return using Form 1040X, Amended U.S. Individual Income Tax Return. If you or your spouse (or each of you) file a separate return, you may change to a joint return any time within 3 years from the due date of the separate return or returns. This does not include any extensions. A separate return includes a return filed by you or your spouse claiming married filing separately, single, or head of household filing status. For tax years beginning on or before July 30, 1996, if the amount paid on your separate returns is less than the total tax shown on the joint return, you must pay the additional tax due on the joint return when you file it. For tax years beginning after July 30, 1996, you do not have to pay the additional tax as a condition to filing the joint return.
Separate Returns
Special rules apply if you file a separate return.. If you file a separate return: 1) Your spouse should itemize deductions if you itemize deductions because he or she the entire year. 6) You may have to include in income more of your social security benefits (including any equivalent railroad retirement benefits) than you would on a joint return.
Separate Returns After Joint Return
Once you file a joint return, you cannot choose to file separate returns for that year after the due date of the return. Exception. A personal representative for a decedent may change from a joint return elected by the surviving spouse to a separate return for the decedent. The personal representative has one year from the due date of the return to make the change. See Publication 559 for more information on filing income tax returns for a decedent.
Married Filing Separately
You may choose married filing separately as your filing status if you. If you live apart from your spouse and meet certain tests, you may be considered unmarried and may file as head of household. This is true, even though you are not divorced or legally separated. If you qualify to file as head of household, instead of as married filing separately, your tax may be lower, you may be able to claim the earned income credit, and your standard deduction will be higher. The head of household filing status allows you to choose the standard deduction even if your spouse chooses to itemize deductions. See Head of Household, later, for more information. Unless you are required to file separately, you may want to figure your tax both ways (on a joint return and on separate returns). Do this to make sure you are using the method that results in less combined tax. However, you will generally pay more combined tax on separate returns than you would on a joint return because the tax rate is higher for married persons filing separately. If you file a separate return, you generally report only your own income, exemptions, credits, and deductions on your individual return. You may claim an exemption for your spouse if your spouse had no gross income and was not the dependent of another person. However, if your spouse had any gross income Page 6
Head of Household
You may be able to file as head of household if you are unmarried or considered unmarried on the last day of the year. In addition, you must have paid more than half the cost of keeping up a home for you and a qualifying person for more than half the year.
Individual retirement arrangements (IRAs). You may not be able to deduct contributions to your individual retirement account if either you or your spouse was covered by an employer retirement plan, you and your spouse file separate returns, and you lived together during the year. See Deductible Contributions in Publication 590, Individual Retirement Arrangements (IRAs). Rental activity losses. If your rental of real estate is a passive activity, you may generally offset a loss of up to $25,000 against your nonpassive income if you actively participate in the activity. However, married persons filing separate returns who lived together at any time during the year may not claim this offset. Married persons filing separate returns who lived apart at all times during the year are each allowed a $12,500 maximum offset for passive real estate activities. See Rental Activities in Publication 925, Passive Activity and At-Risk Rules. may use either Form 1040A or Form 1040. Indicate your choice of this filing status by checking the box on line 4 of either form. Use the Head of a household column of the Tax Table or Schedule Z of the Tax Rate Schedules, to figure your tax. Considered unmarried. You are considered unmarried on the last day of the tax year if you meet all of the following tests. 1) You file a separate return. 2) You paid more than half the cost of keeping up your home for the tax year. 3) Your spouse did not live in your home during the last 6 months of the tax year. Your spouse is considered to live with you if he
or she is temporarily absent due to special circumstances. See Temporary absences, later. 4) Your home was, for more than half the year, the main home of your child, stepchild, adopted child, or foster child whom you can claim as a dependent. (See Home of qualifying person, later.) However, you can still meet this test if you cannot claim your child as a dependent only because: a) You state in writing to the noncustodial parent that he or she may claim an exemption for the child, or b) The noncustodial parent provides at least $600 support for the dependent and claims an exemption for the dependent under a pre-1985 divorce or separation agreement. The rules to claim an exemption for a dependent are explained later under Exemptions for Dependents.
Parent Grandparent Brother Sister Stepbrother Stepsister Stepmother Stepfather Mother-in-law Father-in-law Half brother Half sister
Brother-in-law Sister-in-law Son-in-law Daughter-in-law, or If related by blood: Uncle Aunt Nephew Niece
of the cost of keeping up the apartment for your mother from January 1 until her death, and she qualifies as your dependent, you may file as a head of household.
Keeping Up a Home
You are keeping up a home only if you pay more than half of the cost of its upkeep. You may determine whether you paid more than half of the cost of keeping up a home by using the Cost of Maintaining a Household worksheet, later. Costs you include. Include such costs as rent, mortgage interest, taxes, insurance on the home, repairs, utilities, and food eaten in the home. Costs you do not include. Do not include the cost of clothing, education, medical treatment, vacations, life insurance, transportation, or the rental value of a home you own. Also, do not include the value of your services or those of a member of your household. State AFDC (Aid to Families with Dependent Children). State AFDC payments you use to keep up your home do not count as amounts you paid. They are amounts paid by others that you must apply against the total cost of keeping up your home to figure if you paid more than half.
You are related by blood to an uncle or aunt if he or she is the brother or sister of your mother or father. You are related by blood to a nephew or niece if he or she is the child of your brother or sister.
Note. A dependent can qualify only one taxpayer to use the head of household filing status for any tax year.
Dependents. If the person you support is required to be your dependent, you do not qualify as a head of household if you can only claim the dependent under a multiple support agreement. See Multiple Support Agreement, discussed later. Home of qualifying person. Generally, the qualifying person must live with you for more than half of the year. Special rule for parent. You may be eligible to file as head of household even if your dependent parent does not live with you. You must pay more than half the cost of keeping up a home that was the main home for the entire year for your father or mother. You are keeping up a main home for your dependent father or mother if you pay more than half the cost of keeping your parent in a rest home or home for the elderly. Temporary absences. You are considered to occupy the same household despite the temporary absence due to special circumstances of either yourself or the other person. Temporary absences due to special circumstances include those due to illness, education, business, vacation, and military service. It must be reasonable to assume that you or the other person will return to the household after the temporary absence, and you must continue to maintain a household in anticipation of the return. Death or birth. You may be eligible to file as head of household if the individual who qualifies you for this filing status is born or dies during the year. You must have provided more than half of the cost of keeping up a home that was the individual’s main home for more than half of the year, or, if less, the period during which the individual lived. Example. You are unmarried. Your mother lived in an apartment by herself. She died on September 2. The cost of the upkeep of her apartment for the year until her death was $6,000. You paid $4,000 and your brother paid $2,000. Your brother made no other payments towards your mother’s support. Your mother had no income. Since you paid more than half
Note. If you were considered married for part of the year and lived in a community property state (listed earlier under Separate Returns), special rules may apply in determining your income and expenses. See Publication 555 for more information. Nonresident alien spouse. You are considered unmarried for head of household purposes if your spouse was a nonresident alien at any time during the year and you do not choose to treat your nonresident spouse as a resident alien. Your spouse is not considered your relative. You must have another qualifying relative and meet the other tests to be eligible to file as a head of household. However, you are considered married if you choose to treat your spouse as a resident alien. See Nonresident Spouse Treated as a Resident in Chapter 1 of Publication 519.
Cost of Maintaining a Household Amount You Paid Property taxes Mortgage interest expense Rent Utility charges Upkeep and repairs Property insurance Food consumed on the premises Other household expenses Totals Minus total amount you paid Amount others paid $ $ ( $ ) $ $
Total Cost
Qualifying Person
Each of the following individuals is considered a qualifying person. 1) Your child, grandchild, stepchild, or adopted child who is: a) Single. This child does not have to be your dependent. However, a foster child must be your dependent. See Claiming an exemption, later, under Foster Child or Adult. b) Married. This child must qualify as your dependent. However, if your married child’s other parent claims him or her as a dependent under the special rules for a Noncustodial parent discussed later under Support Test for Divorced or Separated Parents, the child does not have to be your dependent. If the qualifying person is a child but not your dependent, enter that child’s name in the space provided on line 4 of Form 1040 or Form 1040A. 2) Any relative listed below whom you claim as a dependent.
If you paid more than half the total cost, you meet the requirement of maintaining a household.
Qualifying Widow(er) With Dependent Child
If your spouse died in 1996, you may use married filing jointly as your filing status for 1996 if you would otherwise qualify. The year of death is the last year for which you can file jointly with your deceased spouse. See Married Filing Jointly, earlier. You may be eligible to use qualifying widow(er) with dependent child as your filing status for 2 years following the year of death of your spouse. For example, if your spouse died in 1995 and you have not remarried, you may Page 7
be able to use this filing status for 1996 and 1997. The rules for filing as a qualifying widow(er) with dependent child are explained in more detail later. This filing status entitles you to use joint return tax rates and the highest standard deduction amount (if you do not itemize deductions). This status does not entitle you to file a joint return. If you file as a qualifying widow(er) with dependent child, you may use either Form 1040A or Form 1040. Indicate your filing status by checking the box on line 5 of either form. Write the year your spouse died in the space provided on line 5. Use the Married filing jointly column of the Tax Table or Schedule Y–1 of the Tax Rate Schedules to figure your tax. Eligibility rules. You are eligible to file as a qualifying widow(er) with dependent child if you meet all of the following tests. 1) You were entitled to file a joint return with your spouse for the year your spouse died. It does not matter whether you actually filed a joint return. 2) You did not remarry before the end of the tax year. 3) You have a child, stepchild, adopted child, or foster child who qualifies as your dependent for the year. 4) You paid more than half of the cost of keeping up a home that is the main home for you and that child for the entire year, except for temporary absences. See Temporary absences and Keeping Up a Home, discussed earlier, under Head of Household.
have a high taxable income. See Phaseout of Exemptions, later. There are two types of exemptions: personal exemptions and dependency exemptions. While these are both worth the same amount, different rules, discussed later, apply to each type. You usually may claim exemptions for yourself, your spouse, and each person you can claim as a dependent. If you are entitled to claim an exemption for a dependent (such as your child), that dependent cannot claim a personal exemption on his or her own tax return. How to claim exemptions. How you claim an exemption on your tax return depends on which form you file. Form 1040EZ filers. If you file Form 1040EZ, the exemption amount is combined with the standard deduction and entered on line 5. Form 1040A filers. If you file Form 1040A, complete lines 6a through 6d. Follow the Form 1040A instructions. The total number of exemptions you can claim is the total in the box on line 6d. Also complete line 21 by multiplying the number in the box on line 6d by $2,550. Form 1040 filers. If you file Form 1040, complete lines 6a through 6d. Follow the Form 1040 instructions. On line 36, multiply the total exemptions shown in the box on line 6d by $2,550 and enter the result. If your adjusted gross income is $88,475 or more, may qualify for only one personal exemption for yourself. You may not.
Single persons. If another taxpayer is entitled to claim you as a dependent, you may not take an exemption for yourself. This is true even if the other taxpayer does not actually claim your exemption. Married persons. If you file a joint return, you can take your own exemption. If you file a separate return, you may take your own exemption only if another taxpayer is not entitled to claim you as a dependent.
Your Spouse’s Exemption
Your spouse is never considered your dependent. You may be able to take one exemption for your spouse only because you are married. Joint return. If your spouse had any gross income, you may claim his or her exemption only if you file a joint return., you may be claimed as an exemption on both the final separate return of your deceased spouse and the separate return of your new spouse whom you married in the same year. If you file a joint return with your new spouse, you may be claimed as an exemption only on that return. Final decree of divorce or separate maintenance during the year. If you obtained a final decree of divorce or separate maintenance by the end of the year, you may not take your former spouse’s exemption. This rule applies even if you provided all of your former spouse’s support.
Note. As mentioned earlier, this filing status is only available for 2 years following the year of death of your spouse. Example. John Reed’s wife died in 1994. John has not remarried. He has continued during 1995 and 1996 to keep up a home for himself and his dependent child. For 1994 he was entitled to file a joint return for himself and his deceased wife. For 1995 and 1996 he may file as a qualifying widower with a dependent child. After 1996 he can file as head of household if he qualifies.
Death or birth. You may be eligible to file as a qualifying widow(er) with dependent child if the dependent who qualifies you for this filing status is born or dies during the year. You must have provided more than half of the cost of keeping up a home that was the dependent’s main home during the entire part of the year he or she was alive.
Exemptions for Dependents
You are allowed one exemption for each person you can claim as a dependent. This is called a dependency exemption. A person is your dependent if all five of the dependency tests, discussed later, are met. You may take an exemption for your dependent even if your dependent files a return. But that dependent cannot claim his or her personal exemption if you are entitled to do so. However, see Joint Return Test, later. Child born alive. If your child was born alive during the year, and the dependency tests are met, you can take the full exemption. This is true even if the child lived only for a moment.
Personal Exemptions
You are generally allowed one exemption for yourself and, if you are married, one exemption for your spouse. These are called personal exemptions.
Exemptions
Exemptions reduce your taxable income. Generally, you can deduct $2,550 for each exemption you claim in 1996. If you are entitled to two exemptions for 1996, you would deduct $5,100 ($2,550 × 2). But you may lose the benefit of part or all of your exemptions if you Page 8
Your Own Exemption
You may take one exemption for yourself unless you can be claimed as a dependent by another taxpayer.
Whether your child was born alive depends on state or local law. There must be proof of a live birth shown by an official document, such as a birth certificate. You may not claim an exemption for a stillborn child. Death of dependent. If your dependent died during the year and otherwise qualified as your dependent, you can take his or her exemption.
Your child, grandchild, great grandchild, etc. (a legally adopted child is considered your child) Your stepchild Your brother, sister, half brother, half sister, stepbrother, or stepsister Your parent, grandparent, or other direct ancestor, but not foster parent Your stepfather or stepmother A brother or sister of your father or mother A son or daughter of your brother or sister Your father-in-law, mother-in-law, son-inlaw, daughter-in-law, brother-in-law, or sister-in-law Any of these relationships that were established by marriage are not ended by death or divorce. Adoption. Before legal adoption, a child is considered to be your child if he or she was placed with you for adoption by an authorized agency. Also, the child must have been a member of your household. If the child was not placed with you by an authorized agency, the child will meet this test only if he or she was a member of your household for your entire tax year. Foster individual. A foster child or adult. Your cousin will meet this test only if he or she lives with you as a member of your household for the entire year. A cousin is a descendant of a brother or sister of your father or mother and does not qualify under the relationship test. Joint return. If you file a joint return, you do not need to show that a dependent is related to both you and your spouse. You also do not need to show that a dependent.
Example. Your dependent mother died on January 15. You can take a full exemption for her on your return.
Housekeepers, maids, or servants. If these people work for you, you cannot claim them as dependents.. If you are a U.S. citizen who has legally adopted a child who is not a U.S. citizen or resident, and the other dependency tests are met, the child is your dependent and you may citizenship test. They may not be claimed as dependents. However, if you provided a home for a foreign student, you may be able to take a charitable contribution deduction. See Expenses Paid for Student Living With You in Publication 526, Charitable Contributions.
Dependency Tests
The following five tests must be met for you to claim a dependency exemption for a person: 1. Member of Household or Relationship Test 2. Citizenship Test 3. Joint Return Test 4. Gross Income Test 5. Support Test
1. Member of Household or Relationship Test
To meet this test, a person must live with you for the entire year as a member of your household or be related to you. If at any time during the year the person was your spouse, you cannot claim that person as a dependent. See Personal Exemptions, earlier. Temporary absences. You are considered to occupy the same household despite the temporary absence due to special circumstances of either yourself or the other person. Temporary absences due to special circumstances include those due to illness, education, business, vacation,. Test not met. A person does not meet the member of household test if at any time during your tax year the relationship between you and that person violates local law. Relatives not living with you. A person related to you in any of the following ways does not have to live with you for the entire year as a member of your household to meet this test. may not take an exemption for your daughter.
Exception. The joint return test does not apply if a joint return is filed by the dependent and his or her spouse merely as a claim for refund and no tax liability would exist for either spouse on the basis of separate returns.
Example. Your son and his wife each had less than $2,000 of wages and no unearned income. Neither is required to file a tax return. Taxes were taken out of their pay, so they filed a joint return to get a refund. You are allowed exemptions for your son and daughter-in-law if the other dependency tests are met.
4. Gross Income Test
Generally, you may not take an exemption for a dependent if that person had gross income of $2,550 or more for the year. This test does not apply if the person is your child and is either under age 19, or a student under age 24, as discussed
2. Citizenship Test
To meet the citizenship.
Page 9
Page 10. For this gross income test, gross income does not include income received by a permanently and totally disabled individual at a sheltered workshop. The availability of medical care must be the main reason the individual is at the workshop. Also, the income must come solely from activities at the workshop that are incident to this medical care. A sheltered workshop is a school operated by certain taxexempt. See Foster Child or Adult, later. Child under age 19. If your child is under 19 at the end of the year, the gross income test does not apply. Your child may have any amount of income and still be your dependent, if the other dependency tests are met.
2) A student taking a full-time, on-farm training course given by a school described in (1) above or a state, county, or local government.
Full-time student defined. A full-time student is a person who is enrolled for the number of hours or courses the school considers to be full-time attendance. School defined. The term ‘‘school’’ includes elementary schools, junior and senior high schools, colleges, universities, and technical, trade, and mechanical schools. It does not include on-the-job training courses, correspondence schools, and night schools. Example. James Clay, 22, attends college as a full-time student. During the summer, James earned $2,700. If the other dependency tests are met, his parents can take the exemption for James as a dependent. Vocational high school students. People who work on ‘‘co-op’’ jobs in private industry as a part of the school’s prescribed course of classroom and practical training are considered full-time students. Night school. Your child is not a full-time student while attending school only at night. However, full-time attendance at a school may include some attendance at night as part of a full-time course of study. may take the exemptions for them if they otherwise qualify as dependents.
Example. You are in the Armed Forces. You authorize an allotment for your widowed mother that she uses to support herself and your sister. If the allotment provides more than half of their support, you may take an exemption for each of them, even though you authorize the allotment only for your mother. Tax-exempt military quarters allowances. These allowances are treated the same way as dependency allotments in figuring support. The allotment of pay and the taxexempt.
5. Support Test. See Total Support and Table 4, later. A person’s own funds are not support unless they are actually spent for support.
Example 1. You provide $2,000 toward your mother’s support during the year. She has taxable income of $600, nontaxable social security benefit payments of $1,800, and taxexempt interest of $200. She uses all these for her support. You cannot claim your mother as a dependent because the $2,000 you provide is not more than half of her total support of $4,600. Example 2. Your daughter takes out a student loan of $2,500 and uses it to pay her college tuition. She is personally responsible for the loan. You provide $2,000 toward her total support. You may not claim your daughter as a dependent (AFDC, welfare, food stamps, housing, etc.). Benefits provided by the state to a needy person, such as AFDC (Aid to Families with Dependent Children), generally are considered to be used for support. However, payments based on the needs of the recipient will not be considered as used entirely for that person’s support if it is shown that part of the payments were not used for that purpose.
Home for the aged. If you make a lump-sum advance payment to a home for the aged to
Example. Marie Grey, 18, earned $2,700. Her father provided more than half her support. He can claim her as a dependent because the gross income test does not apply and the other dependency tests were met.
Student under age 24. If your child is a student, the gross income test does not apply if the child is under age 24 at the end of the calendar year. The other dependency tests must still be met. Student defined. To qualify as a student, your child must be, during some part of each of 5 calendar months during the calendar year (not necessarily consecutive): 1) A full-time student at a school that has a regular teaching staff, course of study, and regularly enrolled body of students in attendance, or.
Cost determines support. The total cost, not the period of time you provide the support, determines whether you provide more than half of the support. Year support is provided..
Page 11
Table 4. Worksheet for Determining Support
Income 1) Did the person you supported receive any income, such as wages, interest, dividends, pensions, rents, social security, or welfare? (If yes, complete lines 2, 3, 4, and 5) 2) Total income received 3) Amount of income used for support 4) Amount of income used for other purposes 5) Amount of income saved (The total of lines 3, 4, and 5 should equal line 2) Expenses for Entire Household (where the person you supported lived) 6) Lodging (Complete item a or b) a) Rent paid b) If not rented, show fair rental value of home. If the person you supported owned the home, include this amount in line 20. 7) Food 8) Utilities (heat, light, water, etc. not included in line 6a or 6b) 9) Repairs (not included in line 6a or 6b) 10) Other. Do not include expenses of maintaining home, such as mortgage interest, real estate taxes, and insurance. 11) Total household expenses (Add lines 6 through 10) 12) Total number of persons who lived in household Expenses for the Person You Supported 13) Each person’s part of household expenses (line 11 divided by line 12) 14) Clothing 15) Education 16) Medical, dental 17) Travel, recreation 18) Other (specify) $ $ $ $ $ $ $ $ $ $ $ $
□
Yes
□
No
$ $ $ $
$ 19) Total cost of support for the year (Add lines 13 through 18) 20) Amount the person provided for own support (line 3, plus line 6b if the person you supported owned the home) 21) Amount others provided for the person’s support. Include amounts provided by state, local, and other welfare societies or agencies. Do not include any amounts included on line 2. 22) Amount you provided for the person’s support (line 19 minus lines 20 and 21) 23) 50% of line 19 $ $ $ $ $
If line 22 is more than line 23, you meet the support test for the person. If the person meets the other dependency tests, you may claim an exemption for that person. If line 23 is more than line 22, you may still be able to claim an exemption for that person under a multiple support agreement. See Multiple Support Agreement later in this publication.
Page 12
take care of your relative for life and the payment is based on that person’s life expectancy, the amount of your support each year is the lump-sum payment divided by the relative’s life expectancy. Your support also includes any other amounts that you provided during the year.
Support provided Father Mother Fair rental value of lodging . . . . . . . Pension spent for their support . . . Share of food (1/6 of $6,000) . . . . Medical expenses for mother . . . . Parents’ total support . . . . . . . . . . $1,000 2,100 1,000 $4,100 $1,000 2,100 1,000 600 $4,700
Total Support
To figure if you provided more than half of the members of the household. For lodging, the amount of support is the fair rental value of the lodging.
You must figure the dependency status of each parent separately. You provide $2,000 ($1,000 lodging, $1,000 food) of your father’s total support of $4,100 — less than half. You provide $2,600 to your mother ($1,000 lodging, $1,000 food, $600 medical) — more than half of her total support of $4,700. You may claim your mother as a dependent, are considered to provide the total lodging, determine.
give someone cash to pay those expenses, reduce the total fair rental value of the home by those amounts in figuring that person’s own contribution. Example. You provide $6,000 cash for your father’s support during the year. He lives in his own home, which has a fair rental value of $6,600 a year. He uses $800 of the money you give him to pay his real estate taxes. Your father’s contribution for his own lodging is $5,800 ($6,600 – $800 for taxes). may include the cost of the television set in the support of your child. Example 3. You pay $5,000 for a car and register it in your name. You and your 17-yearold your son as a dependent. Medical insurance premiums. Medical insurance premiums you pay, including premiums for supplementary Medicare coverage, are included in the total support you provide. Medical insurance benefits. Medical insurance benefits, including basic and supplementary Medicare benefits, are not part of support. Page 13:
Fair rental value of lodging . . . . . . . . . . . . . . . . . Clothing and recreation . . . . . . . . . . . . . . . . . . . . Medical expenses . . . . . . . . . . . . . . . . . . . . . . . . . . Share of food (1/5 of $5,000) . . . . . . . . . . . . . . Total support $ 960 1,500 300 1,000 $3,760
Because the support Frank and Mary provide ($960 lodging + $300 medical expenses + $1,000 food = $2,260) is more than half of Grace’s $3,760 total support, and Grace meets the other dependency tests, they can claim her as a dependent by entering the necessary information on their return.. If you help to keep up the home by paying interest on the mortgage, real estate taxes, fire insurance premiums, ordinary repairs, or other items directly related to the home, or may include these payments as support, even if you claim a credit for them. For information on the credit, see Publication 503, Child and Dependent Care Expenses.
year. The remaining 60% of her support is provided equally by two persons who are not related to her. She does not live with them. Because more than half of her support is provided by persons who cannot claim her as a dependent, no one may take the exemption.
months of the year. Your former spouse has custody for the other 2 months. You and your former spouse provide the child’s total support. You are considered to have provided more than half of the support of the child. However, see Noncustodial parent, later.
Example 3. Your father lives with you and receives 25% of his support from social security, 40% from you, 24% from his brother, and 11% from a friend. Either you or your uncle may take the exemption for your father. A Form 2120 or a written statement from the one not taking the exemption must be attached to the return of the one who takes the exemption.
Example 2. You and your former spouse provided your child’s total support for 1996. You had custody of your child under your 1992 divorce decree, but on August 31, 1996, a new custody decree granted custody to your former spouse. Because you had custody for the greater part of the year, you are considered to have provided more than half of your child’s support.
Noncustodial parent. The noncustodial parent will be treated as providing more than half of the child’s support if: 1) The custodial parent signs a written declaration that he or she will not claim the exemption for the child, and the noncustodial parent attaches this written declaration to his or her return, 2) A decree or agreement went into effect after 1984 and states the noncustodial parent can claim the child as a dependent without regard to any condition, such as payment of support, or 3) A decree or agreement executed before 1985 provides that the noncustodial parent is entitled to the exemption, and he or she provides at least $600 for the child’s support during the year, unless the pre1985 decree or agreement is modified after 1984 to specify that this provision will not apply.
Support Test for Divorced or Separated Parents
The support test for a child of divorced or separated parents is based on special rules that apply only if: 1) The parents are divorced or legally separated under a decree of divorce or separate maintenance, or separated under a written separation agreement, or lived apart at all times during the last 6 months of the calendar year, 2) One or both parents provide more than half of the child’s total support for the calendar year, and 3) One or both parents have custody of the child for more than half of the calendar year. ‘‘Child’’ is defined earlier under Gross Income Test. This discussion does not apply if the support of the child is determined under a multiple support agreement, discussed earlier. Custodial parent.. The noncustodial parent is the parent who has custody of the child for the shorter part of the year or who does not have custody at all.
Do Not Include in Total Support
The following items are not included in total support: 1) Federal, state, and local income taxes paid by persons from their own income. 2) Social security and Medicare taxes paid by persons from their own income. 3) Life insurance premiums. 4) Funeral expenses. 5) Scholarships received by your child if your child is a full-time student. 6) Survivors’ and Dependents’ Educational Assistance payments used for the support of the child who receives them. may agree that any one of you who individually provides more than 10% of the person’s support, but only one, may claim an exemption for that person. Each of the others must sign a written statement agreeing not to claim the exemption for that year. The statements must be filed with the income tax return of the person who claims the exemption. Form 2120, Multiple Support Declaration, is used for this purpose. Example 1. You, your sister, and your two brothers provide the entire support of your mother for the year. You provide 45%, your sister 35%, and your two brothers each provide 10%. Either you or your sister may claim an exemption for your mother. The other must sign a Form 2120 or a written Page 14
Example. Under the terms of your 1982 should use Form 8332, Release of Claim to Exemption for Child of Divorced or Separated Parents, or a similar statement, to make the written declaration to release the exemption to the noncustodial parent. The noncustodial parent must attach the form or statement to his or her tax return. The parent for the first year, and a copy of the release must be attached to the return for each succeeding taxable year for which the noncustodial parent claims the exemption. Children who didn’t live with you. You must attach Form 8332 or a similar statement to your return. If your divorce decree or separation agreement went into effect after 1984 and it unconditionally states that you can claim the child as your dependent, you may attach a
Page 15
copy of the following pages from the decree or agreement instead: 1) Cover page (write the other parent’s social security number on this page), 2) The page that states you can claim the child as your dependent, and 3) Signature page with the other parent’s signature and the date of the agreement.
matter if the legal title to the home remains in the names of both parents.
Social Security Numbers for Dependents
You must list the social security number (SSN) of any person you claim as a dependent (except a child born during December of 1996) in column (2) of line 6c of your Form 1040 or Form 1040A. If your dependent was born in December of 1996 and does not have an SSN, enter ‘‘12/96’’ in column (2). You do not need an SSN for a child who was born in 1996 and died in 1996. Write ‘‘Died ’’in column (2) of line 6c of your Form 1040 or Form 1040A.
Phaseout of Exemptions
The amount you can claim as a deduction for exemptions is phased out once your adjusted gross income (AGI) goes above a certain level for your filing status. These levels are as follows:
AGI Level Which Reduces Exemption Amount $ 88,475 117,950 147,450 176,950 176,950
Child support. All child support payments actually received from the noncustodial parent are considered used for the support of the child.
Filing Status Married filing separately Single Head of household Married filing jointly Qualifying widow(er)
Example. The noncustodial parent provides $1,200 for the child’s support. This amount is considered as support provided by the noncustodial parent even if the $1,200 was actually spent on things other than support. Back child support. Even if you owed child support for an earlier year, your payments are considered support for the year paid, up to the amount of your required child support for that year. If the support payments are more than the amount required for this year, any payment for an earlier year is not support provided by the noncustodial parent for either the earlier year or for this year. It is to repay the custodial parent for amounts paid for the support of the children in an earlier year. Example. Under your divorce decree, you must pay $400 a month to your former spouse for the support of your two children. Last year you paid $4,000 instead of $4,800 ($400 × 12 months) due for the year. This year, if you pay the full amount, the entire $4,800 is considered support that you provided. If you also pay any part of the $800 you owe from last year, that amount is not included as support provided by you in either $1 present spouse. The fair rental value of the home provided to the children by your present
If you do not list the dependent’s SSN when required or if you list an incorrect SSN, the exemption may be disallowed. Note. If your dependent does not have and is not eligible to get an SSN, you must list the individual taxpayer identification number (ITIN) instead of an SSN. See Taxpayer identification numbers for aliens, later.
No social security number. If a person whom you expect to claim as a dependent on your return does not have an SSN, either you or that person should apply for an SSN as soon as possible by filing Form SS–5, Application for a
You must reduce the dollar amount of your exemptions by 2% for each $2,500, or part of $2,500, ($1,250 if you are married filing separately), that your AGI exceeds the amount shown above for your filing status. If your AGI exceeds the amount shown earlier by more than $122,500 ($61,250 if married filing separately), the amount of your deduction for exemptions is reduced to zero. If your AGI exceeds the level for your filing status, use Table 5 to figure the amount of your deduction for exemptions.
Table 5. Deduction for Exemptions Worksheet
1. Is the amount on Form 1040, line 32, more than the amount shown on line 4 below for your filing status? No. Stop. Multiply $2,550 by the total number of exemptions claimed on Form 1040, line 6d, and enter the result on line 36. Yes. Complete the worksheet below to figure your deduction for exemptions. 2. Multiply $2,550 by the total number of exemptions claimed on Form 1040, line 6d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3. Enter the amount from Form 1040, line 32 . . . . . . . . . . . 4. Enter the amount shown below for your filing status: ● Married filing separately, enter $88,475 ● Single, enter $117,950 ● Head of household, enter $147,450 ● Married filing jointly or Qualifying widow(er), enter $176,950 3. 2.
}
4.
5. Subtract line 4 from line 3. If zero or less, stop here; enter the amount from line 2 above on Form 1040 line 36 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. Note: If line 5 is more than $122,500 (more than $61,250 if married filing separately), stop here; you cannot take a deduction for exemptions. Enter – 0– on Form 1040, line 36. 6. Divide line 5 by $2,500 ($1,250 if married filing separately). If the result is not a whole number, round it UP to the next higher whole number . . . . . . . . . . . . . . . . . . 7. Multiply line 6 by 2% (.02), and enter the result as a decimal amount. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6. 7. 8. 9.
8. Multiply line 2 by line 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. Deduction for exemptions. Subtract line 8 from line 2. Enter the result here and on Form 1040, line 36. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Page 16 April 15 filing date, you can file Form 4868 for an extension of time to file.. Dependents living in Mexico or Canada. If you claim a dependent who lives in Mexico, enter ‘‘MX ’’instead of a number in column (4) of line 6c of your Form 1040 or Form 1040A. If you claim a dependent who lives in Canada, enter ‘‘CN ’’instead of a number in column (4) of line 6c of your Form 1040 or Form 1040A.
If you can be claimed as a dependent on another person’s return (such as your parents’ return), your standard deduction may be limited. See Standard Deduction for Dependents, later in this section.
Standard deduction amount. The standard deduction amounts for most taxpayers are shown in Table 6. The amount of the standard deduction for a decedent’s final tax may take a higher standard deduction for 1996 if your 65th birthday was on or before January 1, 1997. Use Table 7 to figure the standard deduction amount. Higher standard deduction for blindness. If you are blind on the last day of the year and you do not itemize deductions, you are entitled to a higher standard deduction. Use Table 7. You qualify for this benefit if you are totally or partly blind. Totally blind. If you are totally blind, attach a statement to this effect to your return. Partly blind. If you are partly blind, you must submit with your return each year a certified statement from an eye physician or registered optometrist that: 1) You cannot see better than 20/200 in the better eye with glasses or contact lenses, or 2) Your field of vision is not more than 20 degrees. If your eye condition will never improve beyond these limits, you can avoid having to get a new certified statement each year by having the examining eye physician include this fact in the certification you attach to your return. In later years just attach a statement referring to the certification. You should keep a copy of the certification in your records. If your vision can be corrected beyond these limits only by contact lenses that you can wear only briefly because of pain, infection, or ulcers, you may take the higher standard deduction for blindness if you otherwise qualify. Spouse 65 or older or blind. You may take the higher standard deduction if your spouse is age 65 or older or blind and: 1) You file a joint return, or 2) You file a separate return, and your spouse had no gross income and could not be claimed as a dependent by another taxpayer.
You may not claim the higher standard deduction for an individual other than yourself and your spouse.
Example 1. Larry, 46, and Donna, 43, are filing a joint return for 1996. Neither is blind. They decide not to itemize their deductions. They use Table 6. Their standard deduction is $6,700. Example 2. Assume the same facts as in Example 1, except that Larry is blind at the end of 1996. Larry and Donna use Table 7. Their standard deduction is $7,500. Example 3. Bill and Terry are filing a joint return for 1996. Both are over age 65. Neither is blind. If they do not itemize deductions, they use Table 7. Their standard deduction is $8,300.
How to report. After you find your standard deduction amount, enter it on line 19 of Form 1040A or line 34 of Form 1040. If you use Form 1040EZ, combine your standard deduction with your personal exemption(s) and check the appropriate box on line 5. If the total of your standard deduction and personal exemptions is more than $6,550 ($11,800 if married filing a joint return), you must file Form 1040A or Form 1040.
Standard Deduction
Most taxpayers have a choice of either taking a standard deduction or itemizing their deductions. The standard deduction is a dollar amount that reduces the amount of income on which you are taxed. It is a benefit that reduces the need for many taxpayers to itemize actual deductions, such as medical expenses, charitable contributions, or taxes, on Schedule A of Form 1040. The benefit is higher for taxpayers who are 65 or older or blind. If you have a choice, you should use the method that gives you the lower tax. You benefit from the standard deduction if your standard deduction is more than the total of your allowable itemized deductions. Persons not eligible for the standard deduction. Your standard deduction is zero and you should itemize any deductions you have if: 1) You are married and filing a separate return, and your spouse itemizes deductions, 2) You are filing a tax return for a short tax year on account of a change in your annual accounting period, or 3) You are a nonresident or dual-status alien during the year. You are considered a dual-status alien if you were both a nonresident and resident alien during the year. If you are a nonresident alien who is married to a U.S. citizen or resident at the end of the year, you can choose to be treated as a U.S. resident. (See Publication 519.) You may take the standard deduction.
Standard Deduction for Dependents
The standard deduction for an individual who can be claimed as a dependent on another person’s tax return is generally limited to the greater of (a) $650, or (b) the individual’s earned income for the year (but not more than the regular standard deduction amount, generally $4,000). However, if you are a dependent who is 65 or older or blind, your standard deduction may be higher. If you are a dependent, use Table 8 to determine your standard deduction. Earned income defined. Earned income is salaries, wages, tips, professional fees and other amounts received as pay for work you actually perform. For purposes of the standard deduction, earned income also includes any part of a scholarship or fellowship grant that you must include in your gross income. See Publication 520 for more information on what qualifies as a scholarship or fellowship grant. Where to report your standard deduction. After you find your standard deduction amount, enter it on line 19 of Form 1040A or line 34 of Form 1040. If you use Form 1040EZ, figure your standard deduction on the back of the form and check the ‘‘Yes’’ box on line 5. If your standard deduction is more than $4,000 ($6,700 if married filing a joint return), you must file Form 1040A or Form 1040.
Example 1. Michael, who is single, is claimed as a dependent on his parents’ 1996 tax return. He has interest income of $780 and wages of $150. He has no itemized deductions. Michael uses Table 8 to find his standard deduction. It is $650 because the greater of $650 and his earned income ($150) is $650.
Page 17
1996 Standard Deduction Tables
Caution: If you are married filing a separate return and your spouse itemizes deductions, or if you are a dual-status alien, you cannot take the standard deduction even if you were 65 or older or blind.
Table 6. Standard Deduction Chart for Most People*
If Your Filing Status is: Single Married filing joint return or Qualifying widow(er) with dependent child Married filing separate return Head of household Your Standard Deduction Is: $4,000 6,700 3,350 5,900
Table 8. Standard Deduction Worksheet for Dependents*
If you were 65 or older or blind, check the correct number of boxes below. Then go to the worksheet. You 65 or older □ Blind □ Your spouse, if claiming spouse’s exemption 65 or older □ Blind □ Total number of boxes you checked
□
* DO NOT use this chart if you were 65 or older or blind, OR if someone can claim you (or your spouse if married filing jointly) as a dependent.
1. Enter your earned income (defined below). If none, enter –0–. 2. Minimum amount 3. Enter the larger of line 1 or line 2. 4. Enter the amount shown below for your filing status. ● Single, enter $4,000 ● Married filing separate return, enter $3,350 ● Married filing jointly or Qualifying widow(er) with dependent child, enter $6,700 ● Head of household, enter $5,900 5. Standard deduction. a. Enter the smaller of line 3 or line 4. If under 65 and not blind, stop here. This is your standard deduction. Otherwise, go on to line 5b. b. If 65 or older or blind, multiply $1,000 ($800 if married or qualifying widow(er) with dependent child) by the number in the box above. c. Add lines 5a and 5b. This is your standard deduction for 1996.
1. 2. 3. 4. $650
Table 7. Standard Deduction Chart for People Age 65 or Older or Blind*
Check the correct number of boxes below. Then go to the chart. You 65 or older □ Blind □ Your spouse, if claiming spouse’s exemption 65 or older
□ □
Blind
□
Total number of boxes you checked If Your Filing Status is: Single Married filing joint return or Qualifying widow(er) with dependent child Married filing separate return
And the Number in the Box Above is: 1 2 1 2 3 4 1 2 3 4 1 2
Your Standard Deduction is: $5,000 6,000 7,500 8,300 9,100 9,900 4,150 4,950 5,750 6,550 6,900 7,900
5a.
5b.
5c.
Head of household
Earned income includes wages, salaries, tips, professional fees, and other compensation received for personal services you performed. It also includes any amount received as a scholarship that you must include in your income.
* Use this worksheet ONLY if someone can claim you (or your spouse if married filing jointly) as a dependent.
* If someone can claim you (or your spouse if married filing jointly) as a dependent, use Table 8, instead.
Example 2. Joe, a 22-year-old full-time college student, is claimed as a dependent on his parents’ 1996 tax return. Joe is married and files a separate return. His wife does not itemize deductions on her separate return. Joe has $1,500 in interest income and wages of $3,600. He has no itemized deductions. Joe finds his standard deduction by using Table 8. He enters his earned income, $3,600, on line 1. On line 3 he enters $3,600, the larger of his earned income and $650. Since Joe is married filing a separate return, he enters $3,350 on line 4. On line 5a he enters $3,350 as his standard deduction because it is smaller than $3,600, his earned income. Example 3. Amy, who is single, is claimed as a dependent on her parents’ 1996 tax return. She is 18 years old and blind. She has interest income of $1,300 and wages of $3,000. She has no itemized deductions. Amy uses
Page 18
Table 8 to find her standard deduction. She enters her wages of $3,000 on line 1. On line 3 she enters $3,000, the larger of her wages on line 1 and the $650 on line 2. Since she is single, Amy enters $4,000 on line 4. She enters $3,000 on line 5a. This is the smaller of the amounts on lines 3 and 4. Because she checked one box in the top part of the worksheet, she enters $1,000 on line 5b. She then adds the amounts on lines 5a and 5b and enters her standard deduction of $4,000 on line 5c.
Who Should Itemize
You should itemize deductions if your total deductions are more than the standard deduction amount.. Note: You may be subject to a limit on some of your itemized deductions if your adjusted gross income (AGI) is more than $117,950 ($58,975 if you are married filing separately). See the instructions for Schedule A (Form 1040), line 28, for more information on figuring the correct amount of your itemized deductions. When to itemize. You may benefit from itemizing your deductions on Schedule A of Form 1040 if you: 1) Do not qualify for the standard deduction, or the amount you can claim is limited, 2) Had large uninsured medical and dental expenses during the year, 3) Paid interest and taxes on your home,
4) Had large unreimbursed employee business expenses or other miscellaneous deductions, 5) Had large casualty or theft losses not covered by insurance, 6) Made large contributions to qualified charities, or 7) Have total itemized deductions that are more than the highest standard deduction to which you otherwise are entitled. If you decide to itemize your deductions, complete Schedule A and attach it to your Form 1040. Enter the amount from Schedule A, line 28, on Form 1040, line 34. Itemizing for state tax or other purposes. If you choose to itemize even though your itemized deductions are less than the amount of your standard deduction, write ‘‘IE’’(itemized elected) next to line 34 the other. You both must use the same method of claiming deductions. If one itemizes deductions, the other should itemize because he or she will not qualify for the standard deduction (see Persons not eligible for the standard deduction, earlier).
political subdivisions, or from a tax-exempt child placing agency for caring for a qualified foster individual in your home. A qualified foster care payment is also any payment you receive as a ‘‘difficulty of care payment. ’’ Difficulty of care payments. These are additional payments you receive for providing care to a qualified foster individual who is physically, mentally, or emotionally disabled. The state must have determined that there was a need for the additional payment, and it must be designated as a difficulty of care payment. Excess payments. If you receive qualified foster care payments to care for more than 5 adults, or difficulty of care payments for more than 10 children or for more than 5 adults, you must include a portion of those payments in income. Report as income foster care or difficulty of care payments you receive for each adult after the fifth adult you are paid for. Also report as income difficulty of care payments you receive for each child after the tenth child you are paid for. For purposes of determining excess payments, a child is a person under age 19 and an adult is a person over age 18. Excess expenses. If the expenses you incur to care for foster children or adults are more than the payments you receive, and you have no profit motive in providing foster care, you may take a charitable contribution for the excess expenses on Schedule A (Form 1040) if you itemize deductions. To claim a charitable contribution, you should keep adequate records of the income and expenses of your foster care. Other payments for foster care. If you are paid to maintain space in your home for foster care, in addition to or instead of receiving qualified foster care or difficulty of care payments, you may be considered self-employed and engaged in a business. Include in income all payments received to maintain space in your home. Also include in income payments for additional foster individuals as discussed earlier under Excess payments. Report them as business income on Schedule C or Schedule C-EZ (Form 1040). You can deduct business expenses to care for more than 5 foster adults (or for more than 10 foster children if you receive difficulty of care payments) to maintain space in your home, or for costs you incurred to provide foster care services. If you receive qualified foster care or difficulty of care payments, you can deduct a portion of expenses only if you are required to report these payments as income.
you are required to report as income the difficulty of care payment for the eleventh child, you can deduct a pro rata share of business expenses incurred to care for that child. You cannot claim the child as a dependent because your reimbursed expenses are incurred for the child-placing agency. You incur any unreimbursed expenses in your business.
Example 3. You agreed to provide continuous 24-hour maintenance of three spaces in your home. The spaces are for the temporary and emergency care of children placed there by the local welfare department. You provide the items of support necessary to the children. These include room, board, clothing, personal needs, and spending money. You ask any foster children who come into your home to help with household chores as are normally expected of children in a family. However, they do not perform these chores in return for your support. The welfare department inspects the home periodically to ensure that the foster children placed there receive proper care and gives advice and supervision to you as needed. The welfare department pays you a monthly fee for each of the three spaces maintained for the children, whether or not the spaces are used. You are in an independent business and are not an employee of the agency. A part of each payment you receive is for the space you keep available. You must include in income the part that is to maintain space.
Claiming an exemption. You may be able to claim an exemption for a foster child or adult if you do not receive payments for caring for that individual. However, you must meet the five dependency tests as follows: 1) Member of household — the individual must be a member of your household for the entire year except for death and temporary absences, 2) Citizenship — the individual must be a U.S. citizen or resident, or a resident of Canada or Mexico for some part of the calendar year, 3) Joint return — the individual generally cannot file a joint return (but see Joint Return Test, earlier), 4) Gross income — the individual may not have gross income of $2,550 or more for 1996 unless he or she is under age 19 or a full-time student under age 24, and 5) Support — you must provide over onehalf of the individual’s support for the year. To figure this, compare the amount you provided with the support received by this person from all sources. You may use Table 4 in this publication for this purpose. However, if you receive payments from a foster care agency to care for this person, you may not claim his or her exemption.
Foster Child or Adult
If you receive qualified foster care payments during the year for caring for a qualified foster individual, do not include the payments in your income. However, if you receive such payments, you may not claim that person as a dependent. See Claiming an exemption, later. The payments you receive are reimbursements for expenses you incur on behalf of the agency responsible for the foster individual. Qualified foster individual. This is an individual who is living in a foster family home and who was placed there by:
●
An agency of a state or one of its political subdivisions, or A tax-exempt child placement agency licensed by a state, if the individual is under age 19.
●
Example 1. You receive qualified foster care payments to care for 10 foster children. Since you are not required to include the payments in income, you cannot deduct the excess expenses as business expenses. If you itemize deductions, you can, however, claim the excess expenses as a charitable contribution. Example 2. You receive difficulty of care payments to care for 11 foster children. Since
Qualified foster care payments. These are amounts you receive from a state or one of its
Page 19
How To Get More Information
You can get help from the IRS in several ways. Free publications and forms. To order free publications and forms, call 1–800–TAXFORM (1–800–829–3676). You can also write to the IRS Forms Distribution Center nearest
you. Check your income tax package for the address. Your local library or post office also may have the items you need. For a list of free tax publications, order Publication 910, Guide to Free Tax Services. It also contains an index of tax topics and related publications and describes other free tax information services available from IRS, including tax education and assistance programs. If you have access to a personal computer and modem, you also can get many forms and publications electronically. See Quick and Easy Access to Tax Help the hours of operation.
Page 20
Index
Page 21
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/545367/US-Internal-Revenue-Service-p501-1996 | CC-MAIN-2017-04 | refinedweb | 15,746 | 61.87 |
Gui With Dev C++
Dev-C++ FAQs
Please Subscribe to our Channel for more videos: friends, In this tutorial we will see How to Make Button in Dev C.Code link: ht. To: [email protected] Sent: Thursday, February 26, 2004 4:06 AM. Subject: Dev-C getting started creating a windows gui application. Hi all, I just installed dev-cpp 4.9.8, and want to get started creating a windows application. I was able to generate teh initial c application file via the wizard, but now how do I add. It is a follow up course on our Qt 5 C GUI Development for Beginners course, so you should have completed that course or have similar experience from elsewhere. The course is packed with lots of tips and tricks, to help you master what it takes to build professional GUI applications using C and Qt. The lectures are carefully designed. This demo is for C beginners. It shows how one can use WxDev-C to build a simple GUI app. This IDE, written in Delphi is the right place for beginners. It isn't perfect and it allows you 'holes' and 'bugs' in your program.Thats why its good for beginners. VS2005 wouldnt compile most of the code, which Dev-C does. Information and Download HERE. SOME LINUX IDE's: -Code::Blocks.
When executing my console program, it closes automatically. How I can change this behavior?
You can use an input function at the end of your source, like the following example:
int main()
{
system(“PAUSE”);
return 0;
}
When I compile my dos program and execute it, Dev-C++ minimizes and then restore in a second but nothing appears
When creating a console application, be sure to uncheck “Do not create a console” in Project Options (when working with source files only uncheck “Create for win32” in Compiler Options).
After linking, I get the error “C:DEV-C++LIBlibmingw32.a(main.o)(.text+0x8e): undefined reference to `[email protected]'
You most probably haven’t declared any main() function in your program
When I launch Dev-C++ i get the message saying “WININET.DLL not found”
Install the missing DLL. You can find more information about this issue at this Microsoft support page
When I compile a file, I get a message saying 'could not find <filename>'
Check within Compiler Options if the directories settings are correct. For a default setup, you should have:
C:DEV-C++Bin
c:DEV-C++Include
c:DEV-C++Include
c:DEV-C++Lib
How do I enable Debugging mode?
Go to Compiler Options and click on the Linker sheet. Now check 'Generate debugging information'. Do a 'Rebuild All' and debugging should now be available
The EXE files created are huge. What can I do to reduce the size?
If you want to reduce your executable file size from 330Kb to 12Kb for example, go to Compiler Options, then click on the Linker page and uncheck 'Generate debug information'. This will remove debugging information (if you want to debug, uncheck it). You can also reduce even more by going to the Optimization page and checking 'Best optimization'.
Under Windows NT, every time i launch Dev-C++ i get the message “Failed to set data for”
The is because you are not in Administrator mode, and Dev-C++ tries to write to the registry. To get rid of the error message, log on as the Administrator, or uncheck the file association options in Environment options, Misc. Sheet.
When I try to compile I get: ld: cannot open crt2. o: No such file or directory. What can i do?
Go to Compiler options, and check if the Lib directory is correctly set to:
C:Dev-C++Lib
(for a default installation).
If this still doesn't work, try copying the file Libcrt2.o to your Dev-C++'s Bin directory.
How can I use the OpenGL library and others?
All the libraries that comes with hte installed Mingw release reside in the Lib directory. Powerdirector 8 digit serial key. They are all named in the following way: lib[name].a
To link a library with your project, just add in Project options, Further option files:
-lopengl32
This is for including the libopengl32.a library. To add any other library, just follow the same syntax:
Type -l (L in lowercase) plus the base name of the library (filename without 'lib' and the '.a' extension)
When I compile a file containing references to Windows filename (like <Mydirmyfile.h>), I get an 'unrecognized escape sequence' message ?
The Mingw compiler understands paths in the Unix style (/mydir/myfile.h). Replace the in the filename by /
Is there any GUI library or packages available for Dev-C++?
A lot of different GUI libraries can be used with Dev-C++ and Mingw. Fore a few easy-to-install packages for Dev-C++, visit this page
Why can't I use conio.h functions like clrsrc()?
Because conio.h is not part of the C Standard Library. It is a Borland extension, and works only with Borland compilers (and perhaps some other commercial compilers). Dev-C++ uses GCC, the GNU Compiler Collection.
If you really can't live without them, you can use conio functions this way:
Include conio.h to your source, and add C:Dev-C++Libconio.o to 'Linker Options' in Project Options (where C:Dev-C++ is where you installed Dev-C++).
Please note that conio support is far from perfect. I only wrote it very quickly.
Gui With Dev C++ Code
Toolbar icons are not showing properly
On some screen exotic systems and resolutions, toolbar icons may show up incorrectly. Try changing your screen resolution, or disable toolbars from the View menu in Dev-C++
When attempting to create a setup program, i get the error 'File BinSetup.exe not found'
If you are willing to use the Setup Creator feature of Dev-C++ 4, you need to download and install this file
Gui With Dev C++ Free
How to use assembly with Dev-C++?
The 'GNU as' assembler uses AT&T syntax (not Intel). Here's an example:
// 2 global variables
int AdrIO ;
static char ValIO ;
void MyFunction()
{
__asm('mov %dx, _AdrIO') ; // loading 16 bits register
__asm('mov %al, _ValIO') ; // loading 8 bits register
/*
Don't forget the underscore _ before each global variable names !
*/
__asm('mov %dx, %ax') ; // AX --> DX
}
How do I emulate the MS-DOS pause function?There are two ways. You can do it this way:
#include <stdio.h>
int main()
{
printf ('Press ENTER to continue.n');
getchar(); // wait for input
return 0;
}
Or this way:
Gui With Dev C++ Download
#include <stdlib.h>
int main()
{
system ('pause'); // execute MS-DOS' pause command
return 0;
}
What about a Linux version?
There was a Linux version, but it has been abandoned, mainly because Dev-C++ is written in Delphi, but the first Linux version of Delphi (Kylix) wasn't as promising as required for Dev-C++ to be ported.
How can i provide a .def file for my DLL ?
Put in Project Options, Linker parameters: --def yourfile.def
I am having strange problems under Windows XP
Try to run Windows Update and make sure that you have the Program Compatability updates.
I am using Windows 98 and I cannot compile
Some users reported that you need to apply several patches to your system. Here is the list of them, if you can retrieve them from Microsoft website:
47569us.exe - labeled as Windows98SE shutdown
dcom98.exe). | https://gulshanbotnia.co/gui-with-dev-c/ | CC-MAIN-2022-05 | refinedweb | 1,251 | 65.42 |
This In-depth Tutorial on Recursion in Java Explains what is Recursion with Examples, Types, and Related Concepts. It also covers Recursion Vs Iteration:
From our earlier tutorials in Java, we have seen the iterative approach wherein we declare a loop and then traverse through a data structure in an iterative manner by taking one element at a time.
We have also seen the conditional flow where again we keep one loop variable and repeat a piece of code till the loop variable meets the condition. When it comes to function calls, we explored the iterative approach for function calls as well.
=> Check ALL Java Tutorials Here.
In this tutorial, we will discuss a different approach to programming i.e. the Recursive approach.
What You Will Learn:
- What Is Recursion In Java?
- Understanding Recursion In Java
- Recursion Examples In Java
- Recursion Types
- Recursion Vs Iteration In Java
- Conclusion
What Is Recursion In Java?
Recursion is a process by which a function or a method calls itself again and again. This function that is called again and again either directly or indirectly is called the “recursive function”.
We will see various examples to understand recursion. Now let’s see the syntax of recursion.
Recursion Syntax
Any method that implements Recursion has two basic parts:
- Method call which can call itself i.e. recursive
- A precondition that will stop the recursion.
Note that a precondition is necessary for any recursive method as, if we do not break the recursion then it will keep on running infinitely and result in a stack overflow.
The general syntax of recursion is as follows:
methodName (T parameters…) { if (precondition == true) //precondition or base condition { return result; } return methodName (T parameters…); //recursive call }
Note that the precondition is also called base condition. We will discuss more about the base condition in the next section.
Understanding Recursion In Java
In this section, we will try to understand the recursion process and see how it takes place. We will learn about the base condition, stack overflow, and see how a particular problem can be solved with recursion and other such details.
Recursion Base Condition
While writing the recursive program, we should first provide the solution for the base case. Then we express the bigger problem in terms of smaller problems.
As an example, we can take a classic problem of calculating the factorial of a number. Given a number n, we have to find a factorial of n denoted by n!
Now let’s implement the program to calculate the n factorial (n!) using recursion.
public class Main{ static int fact(int n) { if (n == 1) // base condition return 1; else return n*fact(n-1); } public static void main(String[] args) { int result = fact(10); System.out.println("10! = " + result); } }
Output
In this program, we can see that the condition (n<=1) is the base condition and when this condition is reached, the function returns 1. The else part of the function is the recursive call. But every time the recursive method is called, n is decremented by 1.
Thus we can conclude that ultimately the value of n will become 1 or less than 1 and at this point, the method will return value 1. This base condition will be reached and the function will stop. Note that the value of n can be anything as long as it satisfies the base condition.
Problem-Solving Using Recursion
The basic idea behind using recursion is to express the bigger problem in terms of smaller problems. Also, we need to add one or more base conditions so that we can come out of recursion.
This was already demonstrated in the above factorial example. In this program, we expressed the n factorial (n!) in terms of smaller values and had a base condition (n <=1) so that when n reaches 1, we can quit the recursive method.
Stack Overflow Error In Recursion
We are aware that when any method or function is called, the state of the function is stored on the stack and is retrieved when the function returns. The stack is used for the recursive method as well.
But in the case of recursion, a problem might occur if we do not define the base condition or when the base condition is somehow not reached or executed. If this situation occurs then the stack overflow may arise.
Let’s consider the below example of factorial notation.
Here we have given a wrong base condition, n==100.
public class Main { static int fact(int n) { if (n == 100) // base condition resulting in stack overflow return 1; else return n*fact(n-1); } public static void main(String[] args) { int result = fact(10); System.out.println("10! = " + result); } }
So when n > 100 the method will return 1 but recursion will not stop. The value of n will keep on decrementing indefinitely as there is no other condition to stop it. This will go on till stack overflows.
Another case will be when the value of n < 100. In this case, as well the method will never execute the base condition and result in a stack overflow.
Recursion Examples In Java
In this section, we will implement the following examples using recursion.
#1) Fibonacci Series Using Recursion
The Fibonacci series is given by,
1,1,2,3,5,8,13,21,34,55,…
The above sequence shows that the current element is the sum of the previous two elements. Also, the first element in the Fibonacci series is 1.
So in general if n is the current number, then it is given by the sum of (n-1) and (n-2). As the current element is expressed in terms of previous elements, we can express this problem using recursion.
The program to implement the Fibonacci series is given below:
public class Main { //method to calculate fibonacci series static int fibonacci(int n) { if (n <= 1) { return n; } return fibonacci(n-1) + fibonacci(n-2); } public static void main(String[] args) { int number = 10; //print first 10 numbers of fibonacci series System.out.println ("Fibonacci Series: First 10 numbers:"); for (int i = 1; i <= number; i++) { System.out.print(fibonacci(i) + " "); } } }
Output
#2) Check If A Number Is A Palindrome Using Recursion
A palindrome is a sequence that is equal when we read it from left to right or right to left.
Given a number 121, we see that when we read it from left to right and right to left, it is equal. Hence number 121 is a palindrome.
Let’s take another number, 1242. When we read it from left to right it is 1242 and when read from right to left it reads as 2421. Thus this is not a palindrome.
We implement the palindrome program by reversing the digits of numbers and recursively compare the given number to its reversed representation.
The below program implements the program to check the palindrome.
import java.io.*; import java.util.*; public class Main { // check if num contains only one digit public static int oneDigit(int num) { if ((num >= 0) && (num < 10)) return 1; else return 0; } //palindrome utility function public static int isPalindrome_util (int num, int revNum) throws Exception { // base condition; return if num=0 if (num == 0) { return revNum; } else { //call utility function recursively revNum = isPalindrome_util(num / 10, revNum); } // Check if first digit of num and revNum are equal if (num % 10 == revNum % 10) { // if yes, revNum will move with num return revNum / 10; } else { // exit throw new Exception(); } } //method to check if a given number is palindrome using palindrome utility function public static int isPalindrome(int num) throws Exception { if (num < 0) num = (-num); int revNum = (num); return isPalindrome_util(num, revNum); } public static void main(String args[]) { int n = 1242; try { isPalindrome(n); System.out.println("Yes, the given number " + n + " is a palindrome."); } catch (Exception e) { System.out.println("No, the given number " + n + " is not a palindrome."); } n = 1221; try { isPalindrome(n); System.out.println("Yes, the given number " + n + " is a palindrome."); } catch (Exception e) { System.out.println("No, the given number " + n + " is not a palindrome."); } } }
Output
#3) Reverse String Recursion Java
Given a string “Hello” we have to reverse it so that the resultant string is “olleH”.
This is done using recursion. Starting from the last character in the string we recursively print each character until all the characters in the string are exhausted.
The below program uses recursion to reverse a given string.
class String_Reverse { //recursive method to reverse a given string void reverseString(String str) { //base condition; return if string is null or with 1 or less character if ((str==null)||(str.length() <= 1)) System.out.println(str); else { //recursively print each character in the string from the end System.out.print(str.charAt(str.length()-1)); reverseString(str.substring(0,str.length()-1)); } } } class Main{ public static void main(String[] args) { String inputstr = "SoftwareTestingHelp"; System.out.println("The given string: " + inputstr); String_Reverse obj = new String_Reverse(); System.out.print("The reversed string: "); obj.reverseString(inputstr); } }
Output
#4) Binary Search Java Recursion
A binary search algorithm is a famous algorithm for searching. In this algorithm, given a sorted array of n elements, we search this array for the given key element. In the beginning, we divide the array into two halves by finding the mid element of the array.
Then depending on whether the key < mid or key > mid we limit our search in the first or second half of the array. This way the same process is repeated until the location of the key elements is found.
We will implement this algorithm using recursion here.
import java.util.*; class Binary_Search { // recursive binary search int binarySearch(int numArray[], int left, int right, int key) { if (right >= left) { //calculate mid of the array int mid = left + (right - left) / 2; // if the key is at mid, return mid if (numArray[mid] == key) return mid; // if key < mid, recursively search the left subarray if (numArray[mid] > key) return binarySearch(numArray, left, mid - 1, key); // Else recursively search in the right subarray return binarySearch(numArray, mid + 1, right, key); } // no elements in the array, return -1 return -1; } } class Main{ public static void main(String args[]) { Binary_Search ob = new Binary_Search(); //declare and print the array int numArray[] = { 4,6,12,16,22}; System.out.println("The given array : " + Arrays.toString(numArray)); int len = numArray.length; //length of the array int key = 16; //key to be searched int result = ob.binarySearch(numArray, 0, len - 1, key); if (result == -1) System.out.println("Element " + key + " not present"); else System.out.println("Element " + key + " found at index " + result); } }
Output
#5) Find Minimum Value In Array Using Recursion
Using recursion we can also find the minimum value in the array.
The Java program to find the minimum value in the array is given below.
import java.util.*; class Main { static int getMin(int numArray[], int i, int n) { //return first element if only one element or minimum of the array elements return (n == 1) ? numArray[i] : Math.min(numArray[i], getMin(numArray,i + 1 , n - 1)); } public static void main(String[] args) { int numArray[] = { 7,32,64,2,10,23 }; System.out.println("Given Array : " + Arrays.toString(numArray)); int n = numArray.length; System.out.print("Minimum element of array: " + getMin(numArray, 0, n) + "\n"); } }
Output
These are some of the examples of recursion. Apart from these examples, a lot of other problems in the software can be implemented using recursive techniques.
Recursion Types
Recursion is of two types based on when the call is made to the recursive method.
They are:
#1) Tail Recursion
When the call to the recursive method is the last statement executed inside the recursive method, it is called “Tail Recursion”.
In tail recursion, the recursive call statement is usually executed along with the return statement of the method.
The general syntax for tail recursion is given below:
methodName ( T parameters…){ { if (base_condition == true) { return result; } return methodName (T parameters …) //tail recursion }
#2) Head Recursion
Head recursion is any recursive approach that is not a tail recursion. So even general recursion is ahead recursion.
Syntax of head recursion is as follows:
methodName (T parameters…){ if (some_condition == true) { return methodName (T parameters…); } return result; }
Recursion Vs Iteration In Java
Frequently Asked Questions Recursion used?
Answer: Recursion is used to solve those problems that can be broken down into smaller ones and the entire problem can be expressed in terms of a smaller problem.
Recursion is also used for those problems that are too complex to be solved using an iterative approach. Besides the problems for which time complexity is not an issue, use recursion.
Q #3) What are the benefits of Recursion?
Answer:
The benefits of Recursion include:
- Recursion reduces redundant calling of function.
- Recursion allows us to solve problems easily when compared to the iterative approach.
Q #4) Which one is better – Recursion or Iteration?
Answer: Recursion makes repeated calls until the base function is reached. Thus there is a memory overhead as a memory for each function call is pushed on to the stack.
Iteration on the other hand does not have much memory overhead. Recursion execution is slower than the iterative approach. Recursion reduces the size of the code while the iterative approach makes the code large.
Q #5) What are the Advantages of Recursion over Iteration?
Answer:
- Recursion makes the code clearer and shorter.
- Recursion is better than the iterative approach for problems like the Tower of Hanoi, tree traversals, etc.
- As every function call has memory pushed on to the stack, Recursion uses more memory.
- Recursion performance is slower than the iterative approach.
Conclusion
Recursion is a very important concept in software irrespective of the programming language. Recursion is mostly used in solving data structure problems like towers of Hanoi, tree traversals, linked lists, etc. Though it takes more memory, recursion makes code simpler and clearer.
We have explored all about Recursion in this tutorial. We have also implemented numerous programming examples for a better understanding of the concept.
=> Read Through The Easy Java Training Series. | https://www.softwaretestinghelp.com/recursion-in-java/ | CC-MAIN-2021-17 | refinedweb | 2,343 | 54.52 |
Requirements¶
Kubernetes Version¶
The following Kubernetes versions have been tested in the continuous integration system for this version of Cilium:
- 1.8
- 1.9
- 1.10
- 1.11
- 1.12
- 1.13
- 1.14.
Mounted BPF filesystem¶
This step is optional but recommended. It allows the
cilium-agent to pin
BPF resources to a persistent filesystem and make them persistent across
restarts of the agent. If the BPF filesystem is not mounted in the host
filesystem, Cilium will automatically mount the filesystem but it will be
unmounted and re-mounted when the Cilium pod is restarted. This in turn will
cause BPF resources to be re-created which will cause network connectivity to
be disrupted. Mounting the BPF filesystem in the host mount namespace will
ensure that the agent can be restarted without affecting connectivity of any
pods.
In order to mount the BPF filesystem, the following command must be run in the host mount namespace. The command must only be run once during the boot process of the machine.
mount bpffs /sys/fs/bpf -t bpf
A portable way to achieve this with persistence is to add the following line to
/etc/fstab and then run
mount /sys/fs/bpf. This will cause the
filesystem to be automatically mounted when the node boots.
bpffs /sys/fs/bpf bpf defaults 0 0
If you are using systemd to manage the kubelet,.. | https://cilium.readthedocs.io/en/v1.4/kubernetes/requirements/ | CC-MAIN-2019-39 | refinedweb | 231 | 60.14 |
Touch_Moved in panel view
I've been having troubles implementing custom touch handlers for a view that is presented as a panel or sidebar. Fullscreen, popover and sheet work ok.
While touch_moved does get dispatched once for panel/sidebar, that's it, and after that the window starts to drag (to drag the editor or cinsole back into view)
I'm not sure what the right behaviour should be, but perhaps if a view implements custom touch handling, that handling should take precedence? Or, maybe drag between editor/etc should only be in main title bar? Or maybe some sort of command or property that disables default touch handling?
See the simple example below, which turns green when dragging. It works as expected for sheet, popover, or fullscreen
import ui.View class myview(ui.View): def __init__(self): self.bg_color=(1,0,0) def touch_moved(sender,touch): ui.cancel_delays() sender.bg_color=(0,1,0) def red(): sender.bg_color=(1,0,0) ui.delay(red,0.05) myview().present('panel') | https://forum.omz-software.com/topic/1140/touch_moved-in-panel-view | CC-MAIN-2017-43 | refinedweb | 169 | 67.15 |
Access some data in MySQL database
- fcdionisio last edited by fcdionisio
Is it possible to use the NPM MySQL/MySQL packages on this Quasar Framework…? i try to install NPM just like what i did in Node.Js… i dont know what else i can do to allow it correctly… i need to read and write some data in the existing system (uses MySQL). I hope someone can help me. Thanks
You can use packages with Quasar as much as like you do with Node.js in general.
First, install the packages that you want to use (locally or globally, your choice):
npm install --save mypackage
Then, in the <script> section of your components, import the packages that you want to use:
<script>
import mypackage from ‘mypackage’
…
mypackage.CallFunctionFromMyPackage(…)
</script>
Hope this helps
Quasar is for front-end. Database packages would be for a back-end. You need to build out a back-end to consume MySQL and communicate to/from front-end to back-end.
- fcdionisio last edited by
- fcdionisio last edited by
@hawkeye64 thank you so much | https://forum.quasar-framework.org/topic/3120/access-some-data-in-mysql-database/3 | CC-MAIN-2019-22 | refinedweb | 179 | 72.76 |
view raw
There are a lot of discussion about this and I understand the solution to use the delegate method and check the response "404":
var request : NSURLRequest = NSURLRequest(URL: url)
var connection : NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//...
}
var exists:Bool=fileexists(sURL);
let urlPath: String = sURL;
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?
>=nil
var error: NSErrorPointer = nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
Checking if a resource exists on a server requires sending a HTTP request and receiving the response. TCP communication can take some amount of time, e.g. if the server is busy, some router between the client and the server does not work correctly, the network is down etc.
That's why asynchronous requests are always preferred. Even if you think that the request should take only milliseconds, it might sometimes be seconds due to some network problems. And – as we all know – blocking the main thread for some seconds is a big no-no.
All that being said, here is a possible implementation for a
fileExists() method. You should not use it on the main thread,
you have been warned!
The HTTP request method is set to "HEAD", so that the server sends only the response header, but no data.
func fileExists(url : NSURL!) -> Bool { let req = NSMutableURLRequest(URL: url) req.HTTPMethod = "HEAD" req.timeoutInterval = 1.0 // Adjust to your needs var response : NSURLResponse? NSURLConnection.sendSynchronousRequest(req, returningResponse: &response, error: nil) return ((response as? NSHTTPURLResponse)?.statusCode ?? -1) == 200 } | https://codedump.io/share/YLYmftO1qieb/1/simpliest-solution-to-check-if-file-exists-on-a-webserver-swift | CC-MAIN-2017-22 | refinedweb | 274 | 50.94 |
I'm trying to return a Collection of ValueObjects and I keep getting a Corba Marshal exception.
Take the following instance:
<snip>
public class ValObj {...}
...
public class MyBean {
public HashMap getValueObjects() {
ValObj v = new ValObj();
HashMap hMap = new HashMap();
hMap.put("First", v);
return hMap;
}
}
</snip>
I think this should work, but everytime I call
getValueObjects, I get a Marshal exception. Is there any
reason why this would not work? Or, is my EJB container
just a piece of garbage?
Thanks!
Value Objects and Collections (3 messages)
- Posted by: Greg Blomquist
- Posted on: May 13 2002 16:45 EDT
Threaded Messages (3)
- Value Objects and Collections by Gal Binyamini on May 13 2002 17:04 EDT
- Value Objects and Collections by amit rajaram on May 14 2002 03:54 EDT
- Value Objects and Collections by Greg Blomquist on May 20 2002 15:38 EDT
Value Objects and Collections[ Go to top ]
Is your value object Serializable? If it isn't, then the serialization of the HashMap will fail, and you will get a marshal exception.
- Posted by: Gal Binyamini
- Posted on: May 13 2002 17:04 EDT
- in response to Greg Blomquist
If it is Serializable, and you still get this error, the specific error message and stack trace may help figure out the problem.
Gal
Value Objects and Collections[ Go to top ]
Certainly looks like a serialization problem. Make sure all the fields in your value object are serializable.
- Posted by: amit rajaram
- Posted on: May 14 2002 03:54 EDT
- in response to Greg Blomquist
Value Objects and Collections[ Go to top ]
Thanks for the suggestion, I'll try it out!
- Posted by: Greg Blomquist
- Posted on: May 20 2002 15:38 EDT
- in response to amit rajaram | http://www.theserverside.com/discussions/thread.tss?thread_id=13452 | CC-MAIN-2015-06 | refinedweb | 290 | 66.67 |
How To Solve 403 Forbidden Errors When Web Scraping
Getting a HTTP 403 Forbidden Error when web scraping or crawling is one of the most common HTTP errors you will get.
Often there are only two possible causes:
- The URL you are trying to scrape is forbidden, and you need to be authorised to access it.
- The website detects that you are scraper and returns a
403 ForbiddenHTTP Status Code as a ban page.
Most of the time it is the second cause, i.e. the website is blocking your requests because it thinks you are a scraper.
403 Forbidden Errors are common when you are trying to scrape websites protected by Cloudflare, as Cloudflare returns a
403 status code
In this guide we will walk you through how to debug 403 Forbidden Error and provide solutions that you can implement.
- Easy Way To Solve 403 Forbidden Errors When Web Scraping
- Use Fake User Agents
- Optimize Request Headers
- Use Rotating Proxies
Let's begin...
Easy Way To Solve 403 Forbidden Errors When Web Scraping
If the URL you are trying to scrape is normally accessible, but you are getting 403 Forbidden scraper as follows:
import requests
API_KEY = 'YOUR_API_KEY'
def get_scrapeops_url(url):
payload = {'api_key': API_KEY, 'url': url}
proxy_url = '?' + urlencode(payload)
return proxy_url
r = requests.get(get_scrapeops_url(''))
print(r.text) web scraper and return a
403 error is because you is telling the website you are a scraper in the user-agents you send to the website when making your requests.",
This tells the website that your requests are coming from a scraper, so it is very easy for them to block your requests and return a
403 status code.
Solution
The solution to this problem is to configure your scraper to send a fake user-agent with every request. This way it is harder for the website to tell if your requests are coming from a scraper or a real user.
Here is how you would send a fake user agent when making a request with Python Requests.
import requests
HEADERS = {'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'}
r = requests.get('', headers=HEADERS)
print(r.text)
Here we are making our request look like it is coming from a iPad, which will increase the chances of the request getting through.
This will only work on relatively small scrapes, as if you use the same user-agent on every single request then a website with a more sophisticated anti-bot solution could easily still detect your scraper.
To solve when scraping at scale, we need to maintain a large list of user-agents and pick a different one for each request.
import requests
import random
user_agents_list = [
'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
]
r = requests.get('', headers={'User-Agent': random.choice(user_agents_list)})
print(r.text)
Now, when we make the request. We will pick a random user-agent for each request.
Optimize Request Headers
In a lot of cases, just adding fake user-agents to your requests will solve the 403 Forbidden Error, however, if the website is has a more sophisticated anti-bot detection system in place you will also need to optimize the request headers.
By default, most HTTP clients will only send basic request headers along with your requests such as
Accept,
Accept-Language, and
User-Agent.
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
Accept-Language: 'en'
User-Agent: 'python-requests/2.26.0', to summarize, we don't just want to send a fake user-agent when making a request but the full set of headers web browsers normally send when visiting websites.
Here is a quick example of adding optimized headers to our requests:
import requests",
}
r = requests.get('', headers=HEADERS)
print(r.text)
Here we are adding the same optimized header with a fake user-agent to every request. However, when scraping at scale you will need a list of these optimized headers and rotate through them..
Here is how you could do it Python Requests:
import requests
from itertools import cycle
list_proxy = [
'',
'',
'',
'',
]
proxy_cycle = cycle(list_proxy)
proxy = next(proxy_cycle)
for i in range(1, 10):
proxy = next(proxy_cycle)
print(proxy)
proxies = {
"http": proxy,
"https":proxy
}
r = requests.get(url='', proxies=proxies)
print(r.text)
Now, your request will be routed through a different proxy with each request.
You will also need to incorporate the rotating user-agents we showed previous as otherwise, even when we use a proxy we will still be telling the website that our requests are from a scraper, not a real user.
If you need help finding the best & cheapest proxies for your particular use case then check out our proxy comparison tool here.
Alternatively, you could just use the ScrapeOps Proxy Aggregator as we discussed previously.
More Web Scraping Tutorials
So that's how you can solve 403 Forbidden Errors when you get them.
If you would like to learn more about Web Scraping, then be sure to check out The Web Scraping Playbook.
Or check out one of our more in-depth guides: | https://scrapeops.io/web-scraping-playbook/403-forbidden-error-web-scraping/ | CC-MAIN-2022-40 | refinedweb | 914 | 63.49 |
The Problem
This is often the case when you take over systems; there is a system live on the client's premises, and you are presented with a dump of the code. You hope that when you build the code and restore a backup of the databases that everything will work. But will it? What sort of state is it in? Are all the references OK?
In this post I will be describing some of the steps that you need to take as a consultant when you take over responsibility for someone else's code. It's not pretty, but getting some of the basics right will help you a lot later on.
Step 1: Getting a grip on the code
1a: Get the code in your own repository
There's really nothing else you can do in this situation. You just have to take the code, get it under your own control, build it and then do some serious regression testing against the system on the client's site. There's really nothing else that can be done. If any issues are found then you need to highlight them on day one and if neccessary you have to give the client a cost for fixing them.
Fortunately for me, everything here was OK. I use TFS 2008 as my code repository, and the first thing to do is to get the initial cut of the software into source control. The structure I use is as follows:
Customer
- Application
- - Release Version
What I have done in this case is to put the code I have taken over under a v1.0 branch and built it from there. This then becomes the "reference" version of the system. The 1.0 branch will stay in source control as-is and will not be modified in any way and will be used for reference.
1b: Create your test environments
This is something to do now. NOW. In what is sometimes called the inception phase of the project. Or "iteration zero". Whatever you want to call it. Before you get any further, create the test environments. I am going to have two environments, one that is a "reference" installation that mirrors v1.0 of the system and the other is for my upgraded system, v2.0.
In my case here I have a simple system, in order to deploy each instance of the application I only need a web server and a SQL server. I also need Active Directory so I have created an AD installation as well that will be shared across both of my installations, so 5 servers in all. I have created a set of test users in AD and I am ready to go.
1c: Create the reference deployment
My v1.0 branch has the same code base as the existing system (allegedly), but since I only need to deploy this system once I am not averse to a bt of a manual deployment. The key thing here is to get the correct binaries onto the test system and get the database restored. Tweak the config files to connect to the correct servers and give it a spin.
The main issues I have had in getting the system working are as ollows:
- The data access layer uses NHibernate, so the connection string is in the NHibernate config file which is deployed iThrn the bin directory. This needs to be modified with the correct connection string. [Horror moment #1: The connection string in the config file that I have received form the client has the username and the password included in the connection string! What is more, commented out in the same file are the connection strings for both the UAT and the production environments! All unencrypted! Ouch!]
- As often happens after restoring database backups you have to removed the old users and add in the new service accounts. Note that it's always best to add a service account as a user on your database and then set this service account as your app pool identity in IIS, or use some other form of Windows authentication.
- The system sends out emails to users during the workflow (another big future topic here), and of course the SMTP settings are included in th web.config of the web site, and so these need to be tweaked as well.
- The system needs to save files as part of the process, and these are located on a share. The web config also contains the location of where these files are stored to (yet another post in the making here on file storage, document libraries and file storage services).
These tweaks are crucial for your future deployments. You must note down all of them as they will become the environmental-dependent parameters that your build and deployment process will need to be able to configure on a per-environment basis later on.
1d: Regression test
This does what it says on the tin. When you have got your reference installation you need to regression test it against the expected behaviour. At this point log all known issues or you'll be held accountable for them later!!!
Step 2: Start to sort out the mess
After you have got owenrship of the code and you have been able to establish that the code you have been shipped is actually working, you now need to get to grips with it and sort it out so you don't have a totally flaky foundation.
2a: Create the working branch
At this point we have created the v1.0 branch. What we do now is branch the code to create the new working v2.0 branch so that we can start making changes to the system. This means that if you get latest on the v1.0 branch you will always have a reference of what is there before. All I would do at this point is to use TFS to create a branch of the v1.0 code.
2b: Upgrade to latest version of .Net
This is the ideal opportunity to keept he system current. If you now check out your complete v2.0 branch you should be able to open the solution(s) in Visual Studio 2008 and let it run the upgrade. You don't need ot keep any logs or backups ebcause you will always have your v1.0 branch as a backup.
During this process I had a bit of a nightmare upgrading my website. The intranet site was one of those awful .Net 2.0 websites there the code-behind is deployed along with the web forms. The code behind had no namespaces on it and as the code is designed to JIT compile into temporary assemblies you do not get all of the classes you want to. Also there is further code in the App_Code folder. This is an evil in its own right. If you have this on your dev server even when you have compiled it all into an assembly IIS will keep trying to compile it and you sometimes get namespace / type clashes because of this when the app runs.
What I ended up doing (and I had the luxury of not having a website that had too many pages and controls in it, perhaps 20 web forms and 40 controls) is to create a new web application from scratch and then migrate in the web forms one at a time, by creating new forms of the same names and then copying in first the markup and then the code behind. This is a really tedious process, but in this way you know that you have got a fully compiled, namespaced application. I also tend to rename the App_Code folder into just _Code or soemthing like that so as not to confuse my web server. Remember to set all of the C# files as compile and not as content if thay have come across from the Ap_Code folder.
Step 2b: Tidy up the references
When you have a web site in VS2005 and you add a reference what effectively hapens is that the referenced assembly gets copied into the bin directory of the web site and so it is then avilable to be used. This is no use for a web application project as we must reference all of the assemblies so that the compiler can work out the references.
When creating a code structure, what I usually do is as follows. I will start from the working branch (in this example it is v2.0).
- v2.0
- - Build [More about this in a later post]
- - Referenced Assemblies
- - - Manufacturer X
- - - Manufacturer Y
- - - Manufacturer Z
- - Solutions
- - - Solution A
- - - Solution B
- - - Solution C
So, having got a bin directory full of strange assemblies, I then copy them out into the referenced assemblies folder and then delete them from the bin. I add file references to my projects in my solution for the obvious assemblies and then I use a trial-and-error process of compiling my application until I have referenced all of the assemblies I need to. You'd be surprised how many of the assemblies that are int he bin directory are not direct references of the web site but have ended up then because they are referenced by a dependent project.
OK. After this we are good on the references front. We know what assemblies we have got to deploy and they are all in source control. We're starting to get to the point where we could actually get someone else to do a get latest and see if they can build the beast. In fact that's not a bad idea. Go and ask someone right away. You've nthing to lose.
Step 2c: Tidy up namespaces and assembly names
You'd be surprised (maybe) how often you take a solution, build it and then find look in the bin and find that the assemblies all have different naming standards. Look at the namespaces too and these might all be different. It's a pain in the butt, but you need to decide on your namespace structure, go through each of the projects and set the namespaves and assembly names.
Step 2d: Tidy up versions and strong names
While you're in there don't let me forget that this is also a good time to set your assembly versions. If you are working in a v2.0 branch you might want to make all of your new DLLs v2.0.0.0 as well.
And this is a good tome to create a key file and sign all of your assemblies. Even the one in the website. This is sometimes a moment of truth for your referenceda ssemblies as well, because you can't sign an assembly that references an unsigned assembly. At Solidsoft we have been working with BizTalk so long, which requires you assemblies to be in the Global Assembly Cache (GAC) that we sign all of our assemblies as a matter of routine. More seriously though, there is a code security aspect here as well. You sign assemblies so that they cannot be tampered with. You don't want to be in the situation where one of your assemblies is recompiled by a hacker with some malicious code in it, and signing removes this risk at a stroke.
When I went through the signing process I found that the UIProcess application block hadn't been signed when it was compiled, and the codebase I had only referenced the DLL so I tokk a bit of a risk downloading the source code, signing it and replacing the assembly. There was an issue with the configuration so I had to modify the config schema, but other than that everything went fine and I was all sorted out.
Step 3: Create the build process
This is the time to get this right. A good build and deployment process can seem like it sucks up no end of project time but you get the payback later when you are trying to stabilise and ship your system.
I use TFS and TFSBuild as my build environments now, although I have used MSBuild and CruiseControl.Net in the past. I have two build definitions as a minimum. The first just runs a compile on all solutions and runs unit tests but does not deploy. This is triggered by checkin and so is effectively my "CI" (continuous integration) build. My other build definition is a build / deploy and will push out my build onto a test environment. I use InstallShield to create the MSIs, xcopy them over onto the test server and then use PSExec to install via a command line.
Review
This has been quite a long post, and in real life this part of my project was a real slog, but at the end of it we're in quite good shape now. We have got a repeatable process for delivering our application and this is the minimum level you need to be able to ensure quality. Once you are here, with a build automation process and automated deployment, you can start to overlay automated testing as well as the traditional manual UI testing, but without getting some of the quality in place at this stage you'll never get the results later.
I hope that this has been useful, and that this post has either given you some ideas on organising your solutions or has made you think why you organise your source as you do. Next time I'll be digging into the application and seeing what's in there. I'll warn you - some of it isn't pretty! | http://blog.andrewrivers.co.uk/2009/03/joys-of-legacy-software-2-taking-over.html | CC-MAIN-2017-22 | refinedweb | 2,285 | 68.5 |
sbt-sassify: Sass for SBTsbt-sassify: Sass for SBT
An sbt plugin that enables you to use Sass in your sbt-web project.
This plugin is a reimplementation of sbt-sass. Since I wasn't allowed to install the sass command line compiler on my company's' webserver (damn you corporate IT), I decided to rewrite the plugin to use libsass instead. Due to these changes, the plugin no longer resembled the old plugin, which is why I decided to host it myself.
Sass language versionSass language version
This plugin is based on libsass version 3.5.5, that implements the Sass 3.4 specification.
CompatibilityCompatibility
The sbt-sassify plugin supports the following operating systems:
- OS X 10.8+
- Windows (32/64 bit)
- Linux (32/64 bit)
This plugin has been tested against sbt-web and the Play framework versions 1.4.1 and 2.4.3+ respectively. Additionally, it requires Java 7.
UsageUsage
To use the
sbt-sassify plugin you can include the plugin in
project/plugins.sbt or
project/sbt-sassify.sbt like this:
addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.5.1")
Directory structureDirectory structure
This plugin uses the same conventions as sbt-web. As such all
*.sass and
*.scss files in the
<source dir>/assetsdirectory will be compiled. Depending on the extension of the file, the plugin will decide which syntax should be used to compile the source file.
.sass for the indented syntax and
.scss for the css-like syntax. (Note that the input style can be forced. See the
syntaxDetection option.)
For example, given a file structure as:
app └ assets └ stylesheets └ main.scss └ utils └ _reset.scss └ _layout.scss
With the following
main.scss source:
@import "utils/reset"; @import "utils/layout"; h1 { color: red; }
The Sass file outlined above, will be compiled into
public/stylesheets/main.css, and it will include all the content of the
reset and
layout partials.
Mixing Sass and web-jarsMixing Sass and web-jars
WebJars enable us to depend on client side libraries without pulling all dependencies into our own code base manually.
Compass is a library containing all sorts of reusable Sass functions and mixins. Unfortunately, it is targeted towards the Ruby implementation of Sass. Luckily, there is a number of useful mixins that can be extracted from it. These mixins are wrapped in a WebJar.
Including the compass mixins in your project is as easy as including the WebJar dependency in your library dependencies. For example, within a
build.sbt file add:
libraryDependencies += "org.webjars.bower" % "compass-mixins" % "0.12.7"
sbt-web will automatically extract WebJars into a `lib`` folder relative to your asset's target folder. Therefore, to use the Compass mixins you can import them";
OptionsOptions
Some options can be passed to the Sass compiler. For an overview, see below:
Changing the settings can be done by including the following settings in your build.sbt file:
import org.irundaia.sbt.sass._ SassKeys.cssStyle := Maxified SassKeys.generateSourceMaps := true SassKeys.syntaxDetection := ForceScss
VersioningVersioning
sbt-sassify uses semantic versioning. Given a version number
major.minor.patch, an increment in
majorsignifies a non-backwards-compatible API change;
minorsignifies a backwards-compatible functionality implementation;
patchsignifies a backwards-compatible bug fix/refactoring.
Known limitationsKnown limitations
Issues have been known to occur when a different version of libsass has been installed on your system. This is caused by the c-API changing in libsass version 3.4.5. If your system has a different version installed, this will cause linking errors. Currently, a workaround would be to make sure that the same version of libsass is installed.
Only one Sass syntax style can be used at the same time. So when compiling a .scss file, one cannot include a .sass file. (Well, you can, but it won't compile.)
Due to a lack of testing, this plugin might not work on all 32-bit linux distributions. | https://index.scala-lang.org/irundaia/sbt-sassify/sbt-sassify/1.0.0?target=_2.10_0.13 | CC-MAIN-2020-50 | refinedweb | 645 | 52.26 |
Using GNU getopt toolssuggest change
Command-line options for applications are not treated any differently from command-line arguments by the C language. They are just arguments which, in a Linux or Unix environment, traditionally begin with a dash (
\-).
With glibc in a Linux or Unix environment you can use the getopt tools to easily define, validate, and parse command-line options from the rest of your arguments.
These tools expect your options to be formatted according to the GNU Coding Standards, which is an extension of what POSIX specifies for the format of command-line options.
The example below demonstrates handling command-line options with the GNU getopt tools.
#include <stdio.h> #include <getopt.h> #include <string.h> /* print a description of all supported options */ void usage (FILE *fp, const char *path) { /* take only the last portion of the path */ const char *basename = strrchr(path, '/'); basename = basename ? basename + 1 : path; fprintf (fp, "usage: %s [OPTION]\n", basename); fprintf (fp, " -h, --help\t\t" "Print this help and exit.\n"); fprintf (fp, " -f, --file[=FILENAME]\t" "Write all output to a file (defaults to out.txt).\n"); fprintf (fp, " -m, --msg=STRING\t" "Output a particular message rather than 'Hello world'.\n"); } /* parse command-line options and print message */ int main(int argc, char *argv[]) { /* for code brevity this example just uses fixed buffer sizes for strings */ char filename[256] = { 0 }; char message[256] = "Hello world"; FILE *fp; int help_flag = 0; int opt; /* table of all supported options in their long form. * fields: name, has_arg, flag, val * `has_arg` specifies whether the associated long-form option can (or, in * some cases, must) have an argument. the valid values for `has_arg` are * `no_argument`, `optional_argument`, and `required_argument`. * if `flag` points to a variable, then the variable will be given a value * of `val` when the associated long-form option is present at the command * line. * if `flag` is NULL, then `val` is returned by `getopt_long` (see below) * when the associated long-form option is found amongst the command-line * arguments. */ struct option longopts[] = { { "help", no_argument, &help_flag, 1 }, { "file", optional_argument, NULL, 'f' }, { "msg", required_argument, NULL, 'm' }, { 0 } }; /* infinite loop, to be broken when we are done parsing options */ while (1) { /* getopt_long supports GNU-style full-word "long" options in addition * to the single-character "short" options which are supported by * getopt. * the third argument is a collection of supported short-form options. * these do not necessarily have to correlate to the long-form options. * one colon after an option indicates that it has an argument, two * indicates that the argument is optional. order is unimportant. */ opt = getopt_long (argc, argv, "hf::m:", longopts, 0); if (opt == -1) { /* a return value of -1 indicates that there are no more options */ break; } switch (opt) { case 'h': /* the help_flag and value are specified in the longopts table, * which means that when the --help option is specified (in its long * form), the help_flag variable will be automatically set. * however, the parser for short-form options does not support the * automatic setting of flags, so we still need this code to set the * help_flag manually when the -h option is specified. */ help_flag = 1; break; case 'f': /* optarg is a global variable in getopt.h. it contains the argument * for this option. it is null if there was no argument. */ printf ("outarg: '%s'\n", optarg); strncpy (filename, optarg ? optarg : "out.txt", sizeof (filename)); /* strncpy does not fully guarantee null-termination */ filename[sizeof (filename) - 1] = '\0'; break; case 'm': /* since the argument for this option is required, getopt guarantees * that aptarg is non-null. */ strncpy (message, optarg, sizeof (message)); message[sizeof (message) - 1] = '\0'; break; case '?': /* a return value of '?' indicates that an option was malformed. * this could mean that an unrecognized option was given, or that an * option which requires an argument did not include an argument. */ usage (stderr, argv[0]); return 1; default: break; } } if (help_flag) { usage (stdout, argv[0]); return 0; } if (filename[0]) { fp = fopen (filename, "w"); } else { fp = stdout; } if (!fp) { fprintf(stderr, "Failed to open file.\n"); return 1; } fprintf (fp, "%s\n", message); fclose (fp); return 0; }
It can be compiled with
gcc:
gcc example.c -o example
It supports three command-line options (
--file, and
--msg). All have a “short form” as well (
-h,
-f, and
-m). The “file” and “msg” options both accept arguments. If you specify the “msg” option, its argument is required.
Arguments for options are formatted as:
--option=value(for long-form options)
-ovalueor
-o"value"(for short-form options) | https://essential-c.programming-books.io/using-gnu-getopt-tools-4e1dea7cc7dd44f98edbdf64c729f84a | CC-MAIN-2021-25 | refinedweb | 750 | 53.81 |
Other Math Archive: Questions from July 03, 2008
- Anonymous askedCommunication is a mirror in which everyone shows his image and successful communication brings wond... More »0 answers
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous asked11 answers
- Anonymous asked1 answer
- Anonymous askedthen usingcontra positive... Show moreAssume that and are positive integers andthat m ≤ n. Provethat if m2 = n2,then usingcontra positive method. • Show less2 answers
- Anonymous askedAssignment no 2 ECO401 Virtual University of Pakistan Question no 1: a. Suppose an economy's rea... More »0 answers
- Anonymous askeds primary distributi... Show moreABC Inc. is a manufacturer of ball-point pens, pencils, andstationery. The firm’s primary distribution strategy is tosell in large volumes to office supply stores and large discountchains. Mr. XYZ, CEO of ABC Inc. had hoped to manufacture and sellin large enough quantities that prices could be held low. However,in the first several months, the firm experimented with the priceportion of its marketing mix in an effort to cater number ofmarkets.
1. In starting out with a market-penetration pricing strategy atABC Inc., what assumptions could be made about the market(s), itwas serving?
2. Why might have Mr. XYZ avoided using market-skimming pricingat ABC Inc.?
3. How could optional product pricing be used by ABCInc.?
4. How might product line pricing be initiated at ABCInc.?
5. If ABC Inc., decided to introduce its productsinternationally, what factors may impact a change inprice?
6. Explain how product-form pricing may be a pricing option atABC Inc.,
7. Would quantity discounts be possible for ABC Inc., to offer?Why?• Show less0 answers
- Anonymous asked0 answers
- Anonymous asked2 answers
- Anonymous askedprojects both of which costRs. 1... Show more
AST Company is attemptingto select among the two mutually exclusive
projects both of which costRs. 100,000. The firm has a cost of capital
equal to 13%. After-taxcash inflows associated with each project are
shown in the followingtable :
Year Project A(Rs.) Project B (Rs.)
1 40,000 45,000
2 25,000 25,000
3 35,000 20,000
4 25,000 20,000
5 20,000 20,000
REQUIRED :
(i) Calculate the Payback Period for each project. (4)
(ii) Calculate the Net Present Value (NPV)of each project. (6)
(iii) Calculate the Internal Rate of Return (IRR)for each project.(8)
(IRRmust be calculated by using “Trial & Error Method withInterpolation Formula”. IRR
calculated directly by using Excel or Financial Calculators,will not be awarded full marks.)
(iv) Summarize and compare the above findings for bothprojects and
indicate which project youwould recommend and why?• Show less0 answers
- Anonymous askedAssume that and are positive integers and that . Prove that if , then using contra positive metho... Show more
Assume that and are positive integers and that . Prove that if , then using contra positive method.• Show less1 answer
- Anonymous askedunits.At... Show more
Question 01:
Ambitious Enterprise is currently working at 50% capacityand produces 10,000
units.At 60% working capacity, raw material cost increases by 2% andselling
pricefalls by 2%. At 80% capacity level, raw material cost increases by5% and
sellingprice falls by 5%.
At 50%capacity level, the product costs Rs. 180 per unit and is sold atRs. 200
perunit. The unit cost of Rs. 180 is made up asfollows:
Rs.
Material100
Wages30
Factoryoverheads (40% fixed) 30
Administration overheads (50% fixed) 20
Total per unit Cost 180
Prepare MarginalCost statement showing theestimated profit of the business
when itis operated at 60% and 80% capacities level.0 answers
- Anonymous asked
The two stock investment portfolio data for ABC InvestmentCompany data is given as follows:
The two stock investment portfolio data for ABC InvestmentCompany data is given as follows:
Correlation Coefficient (R) = + 0.9
Required:
0 answers
- Compute the portfolio risk. (5)
- Compute the portfolio return (rp).If we assume a normal probability distribution how will youinterpret the results? (5)
- By using simple weighted average, calculate the portfolio beta(βp).What does it shows? (5)
- Anonymous askedCharts are more effective inattaining attention then others methods of presenting data. Do youagree?... Show moreCharts are more effective inattaining attention then others methods of presenting data. Do youagree? Give reason for your answer. • Show less1 answer
- Anonymous asked1 answer
- Anonymous asked1 answer
- | http://www.chegg.com/homework-help/questions-and-answers/other-math-archive-2008-july-03 | CC-MAIN-2014-15 | refinedweb | 696 | 51.24 |
Hello,
I use opencv in my projects and i would like to upload the image when i press a button.
So, i have a video stream with a webcamera and i would like to save and upload an image when i click a button.
How can i do this?
First im trying to upload an image but it doesnt work. My plan the filename will be the current date.
im trying to use "photos.put(name, f) where the name is the current date and the f is “.jpg” but the terminal write "numpy.ndarray object has no attribute filename.
Hello,
Hi @Laszlo_Sebestyen, welcome to the Streamlit community!
Can you post a full code sample of what you’ve tried? In general, once you have the bytes data, you would add code to write the bytes to a file:
Best,
Randy
Hi @randyzwitch , thanks. Here is the code:
deta = Deta(DETA_KEY)
photos = deta.Drive(“Photos”)
def upload_img(file_name):
return photos.put(file_name)
test = st.button(“Save”)
if test:
upload_img(gray)
Where the gray is an numpy array which i can show in the streamlit platform if i use st.image(gray) | https://discuss.streamlit.io/t/upload-image-to-drive-from-numpy-ndarray/27363 | CC-MAIN-2022-33 | refinedweb | 191 | 77.23 |
Episode #75: pypi.org officially launches
Published Sat, Apr 28, 2018, recorded Wed, Apr 25, 2018.
Sponsored by Datadog: pythonbytes.fm/datadog
- From the numba readme:
- “The easiest way to install numba and get updates is by using the Anaconda Distribution:”
- The need for speed without bothering too much: An introduction to numba
- Can get huge speed up for some computation heavy loops or algorithms.
Michael #2: pip 10 is out!
- Time for:
python -m pip install --upgrade pip
- Features:
-.
Brian #3: Keyword (Named) Arguments in Python: How to Use Them
- Using keyword arguments is often seen when there are many arguments to a function that have useful defaults, and you only want to override the default with some of the arguments.
- Example:
>>> print('comma', 'separated', 'words', sep=', ') comma, separated, words
- You can take positional arguments and require some to be named with various uses of
*
def foo(*, bar, baz): print(f'{bar} {baz}')
- Lots of other useful tricks in this article.
Michael #4: pypi.org officially launches
- Legacy PyPI shutting down April 30
- Listen to talk python 159
- Starting April 16, the canonical Python Package Index is at and uses the new Warehouse codebase.
-.
- If your site/service links to or uses pypi.python.org, you should start using pypi.org instead:
Brian #5: Python Modules and Packages – An Introduction
- In Python, it is, and understanding modules and packages is key to getting a good footing when learning Python. It’s also an area that trips up people when they start trying to create reusable code.
-
Michael #6: Pandas only like modern Python
- From December 31st, 2018, Pandas will drop support for Python 2.7. This includes no backports of security or bug fixes (unless someone volunteers to do those)
- The final release before December 31, 2018 will be the last release to support Python 2. The released package will continue to be available on PyPI and through conda.
- Starting January 1, 2019, all releases will be Python 3 only.
- The full reddit discussion is interesting.
Our news
- Just launched: Python 3, an illustrated tour! talkpython.fm/illustrated | https://pythonbytes.fm/episodes/show/75/pypi.org-officially-launches | CC-MAIN-2018-30 | refinedweb | 349 | 62.98 |
I was curious to how gotoAndStop really functioned, so I ran a few tests. Results are highlighted for easy skim reading.
On each frame, I placed a trace statement, saying which frame is currently displaying.
Then, I messed around putting different kinds of code on frame 1.
Example #1OutputOutputCode:stop(); gotoAndStop(5); trace("I'm still on frame 1, dude!");Now, logically, you should jump to frame 5 before you enter frame 1, but alas, Flash is not as logical.Now, logically, you should jump to frame 5 before you enter frame 1, but alas, Flash is not as logical.Code:I'm still on frame 1, dude! Frame 5, and feeling jive!
First, Flash finishes whatever code it needs on frame 1 (or the frame that called the gotoAndStop()
Then, Flash jumps to whatever frame you told it to go to
This got me thinking... What would Flash do if you told it to go to a certain frame, but since it will finish running all functions for that frame, what if in the rest of that code, you told it to go elsewhere?
Example #2OutputOutputCode:stop(); gotoAndStop(5); gotoAndStop(3); trace("I'm still on frame 1, dude!");If Flash gets more than one "go to frame xx" on each frame, it only jumps to the last frame it was instructed to go to.If Flash gets more than one "go to frame xx" on each frame, it only jumps to the last frame it was instructed to go to.Code:I'm still on frame 1, dude! Frame 3, baby yeah!
If anyone has ever decompiled a SWF (I haven't yet, but it is covered in a very interesting gotoAndLearn tutorial ), you will notice that all the Flash compiler does is add functions to specific frames using the not so commontly known "addFrameScript" function. For example, the above code I wrote would automatically compile to (comments added by me):
Code:package HelloWorld_fla { import flash.display.*; public class MainTimeline extends MovieClip { public function MainTimeline() { addFrameScript(0, frame1); //Remember that really begins numbering at 0, so frame 1 is 0 etc. addFrameScript(1, frame2); addFrameScript(2, frame3); addFrameScript(3, frame4); addFrameScript(4, frame5); } function frame1() { stop(); gotoAndStop(5); gotoAndStop(3); trace("I'm still on frame 1, dude!"); } function frame2() { trace("Terrible frame 2..."); } function frame3() { trace("Frame 3, baby yeah!"); } function frame4() { trace("Have I been on this frame b4?"); } function frame5() { trace("Frame 5, and feeling jive!"); } }
I hope this research has helped someone out there understand the illogical logic of AS3.
Does anyone else have any comments or thoughts they have noticed regarding the frame system of Flash? | http://www.kirupa.com/forum/showthread.php?325891-A-gotoAndStop()-Revelation-Explanation-on-Flash-Frames | CC-MAIN-2014-49 | refinedweb | 443 | 72.46 |
The first step is the replacement of all strings of the form:
"This needs to be translated"
by the following call (interpreted to be a C macro in Gnu's gettext)
_("This needs to be translated")
which is very simple.
The standard way then requires the use of gettextand results in the creation of ".pot" files (Portable Object Templates) to be copied and translated in ".po" (Portable Object) files by a human translator; these are then converted into ".mo" (Machine Object) files by a compiler. Yet, a few more steps, mostly dealing with directory structures and setting up locales, are needed before one can conclude the process.
I present here a simpler way to proceed which, at a later time, can easily be converted to the standard gettext method as it basically uses the same "_()" notation required by gettext. This was inspired by a comp.lang.python post by Martin v. Löwis to a question I asked almost a year ago.
Consider the following simple (English) program [Note: "." are used to indicate indentation as Blogger appears to eat up leading spaces]
def name():The French translation of this program would be
....print "My name is Andre"
if __name__ == '__main__':
....name()
# -*- coding: latin-1 -*-Without further ado, here's the internationalized version using a poor man's i18n method and demonstrating how one can easily switch between languages:
def name():
....print u"Je m'appelle André"
if __name__ == '__main__':
....name()
from translate import _, selectThe key here is the creation of the simple translate.py module:
def name():
....print _("My name is Andre")
if __name__ == '__main__':
....name()
....select('fr')
....name()
....select('en')
....name()
__language = 'en' # leading double underscore to avoid namespace collisionstogether with the language-specific fr.py module containing a single dictionary whose keys are the original English strings.:
def select(lang):
....global __language
....__language = lang
....if lang == 'fr':
........global fr
........import fr
def _(message):
....if __language == 'en':
........return message
....elif __language == 'fr':
........return fr.translation[message]
# -*- coding: latin-1 -*-That's it! Try it out!
translation = {
"My name is Andre" : u"Je m'appelle André"
}
In conclusion, if you want to make your programs translation friendly, all you have to do is:
- replace all "strings" by _("strings")
- include the statement
"from translate import _, select"at the beginning of your program.
- create a file named "translate.py" containing the following:
def select(lang):and leave the rest to the international users/programmers; you will have done them a huge favour!
....pass
def _(message):
....return message | https://aroberge.blogspot.com/2005/07/ | CC-MAIN-2018-13 | refinedweb | 422 | 66.74 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Sills
A Thesis Presented in Partial Fulfillment of the Requirements for the Degree Master of Arts
Arizona State University December 2000
ABSTRACT:
Mass migration flows result from structural causes such as international wage differentials, relative stability of employment in destination countries, relative deprivation in sending countries and historical linkages between sending and receiving nations. Migration is equally a social phenomenon that affects individuals, families and whole communities who build and maintain social webs or networks across great physical and political boundaries, and even generations. Regardless of the kind of migration flow, migrant communities in the destination country maintain real and symbolic connections to their home countries, while simultaneously developing ties that bind them to the receiving country. This study proposes a twofold approach for analyzing these ties. First, by means of secondary data analysis, Mexican migrants in the Phoenix area, there emerges an image of transnational kinship groups, transnational labor circuits, and formation of a transnational community in which migrants have similar social and economic ties, as well as shared symbolic ties to the homeland and host communities.
TABLE OF CONTENTS ABSTRACT............................................................................................................................................2 PART ONE – INTRODUCTION ........................................................................................................6 THEORETICAL VIEWPOINT FOR THE STUDY ..................................................................................... 6 TRANSNATIONALISM AND TRANSNATIONAL SOCIAL FIELDS.............................................................. 7 RECENT STUDIES OF TRANSNATIONAL FIELDS ............................................................................... 10 IMPACT OF TRANSNATIONAL TIES ................................................................................................. 20 O VERVIEW OF THE CURRENT STUDY ............................................................................................. 22 RESEARCH H YPOTHESES............................................................................................................... 23 PART TWO – SETTLEMENT, CIRCULATION AND RETURN: AN ANALYSIS OF SOCIAL AND ECONOMIC TIES .................................................................................................................... 25 INTRODUCTION AND APPROACH ................................................................................................... 25 D ATA AND METHODS ................................................................................................................26 . . . D ESCRIPTIVE ANALYSIS – BACKGROUND CHARACTERISTICS ................................ ........................... 30 D ESCRIPTIVE ANALYSIS – SOCIAL AND E CONOMIC TIES ................................................................. 34 REGRESSION ANALYSIS – D URATION OF STAY ................................ ................................ ................ 40 REGRESSION ANALYSIS – CIRCULATION......................................................................................... 46 REGRESSION ANALYSIS – ACQUISITION OF LONG-TERM LEGAL STATUS ................................ ........... 50 CONCLUSIONS ............................................................................................................................. 52 INTRODUCTION ................................ ............................... ............................... ..........................53 . . . SOURCE OF D ATA................................ ................................ ................................ ......................... 55 THE RECEIVING CONTEXT ........................................................................................................57 . . . Hispanics in the United States.....................................................................................................................................57 Mexican Migrants in the Phoenix Area.......................................................................................................................59 THE MIGRATION E XPERIENCE...................................................................................................... 61 Motivation for Migration and Plans for Settlement, Circulation and Return .................................................................61 Experiences in the Receiving Context ...........................................................................................................................68 SOCIAL AND FAMILY TIES ............................................................................................................. 70 Ties to Mexico .............................................................................................................................................................70 Ties to the United States ..............................................................................................................................................73 E CONOMIC TIES........................................................................................................................... 79 SYMBOLIC TIES ............................................................................................................................ 80 TRANSNATIONAL SOCIAL FIELDS .................................................................................................. 86
4
Transnational Kinship Groups.....................................................................................................................................87 Transnational Circuits .................................................................................................................................................88 Transnational Communities .........................................................................................................................................89 Conclusions ..................................................................................................................................................................91 PART FOUR - SUMMARY AND IMPLICATIONS.......................................................................... 95 REFERENCES.................................................................................................................................... 98 APPENDIX A - TEXT OF FLYER .................................................................................................. 103 APPENDIX B - VERBAL CONSENT SCRIPT .............................................................................. 104 APPENDIX C - QUESTIONNAIRE ............................................................................................... 105 APPENDIX D - US AND MEXICO NETWORK TIES ...................................................................110
PART ONE – INTRODUCTION
Theoretical Viewpoint for the Study Studies show that mass migration flows are set off as a result of structural causes such as international wage differentials, relative stability of employment in destination countries, relative deprivation in sending countries and historical linkages between sending and receiving nations (respectively Todaro and Maruszko 1987; Stark and Bloom 1985; Stark et al. 1986, 1988; Portes and Walton 1981, Petras 1981, Sassen 1988, and Morawska 1990, as cited in Massey et al. 1998). Yet, structural explanations are not sufficient alone to explain the continued and growing global population movements of today. Contemporary theories hold that migration is equally a social phenomenon that affects individuals, families and whole communities who build and maintain social webs or networks across great physical, political boundaries, and even generations (Massey 1987; Massey et al.1993). Moreover, migration is not a fixed and immutable phenomenon, but one that eventually goes through transformations resulting in entirely different forms and processes of population movement (Massey et al.1993; Robert et al.1999). For instance, individuals who initially begin as circular labor migrants, or even refugees, often settle in the host country and propel further migration through family reunification. Likewise, those who may have emigrated with settlement in mind may, upon discovering the receiving context is not as idyllic as originally supposed, return to the home country or relocate to a third country. Regardless of the kind of migration flow, migrant communities in the destination country maintain real and symbolic connections to their home countries, while simultaneously developing ties that bind them to the receiving country. The resulting social structure is what has been termed transnationalism and has come to the fore in recent years as one of the effects of globalization,
7 expansion of modern capitalistic markets into peripheral nations and continued migration to core nations such as the United States.
Transnationalism and Transnational Social Fields Much theoretical debate has occurred around the nature of transnationalism. While some choose to discuss transnationalism as a unique and new social space, distinct from both sending and receiving cultures, this study chooses to treat it as a midpoint between the culture of the homeland and complete acculturation to the majority social group. In this social space created between the two extremes we find both a mixing of cultural activities and the potential for a truly new social space. Whether or not the genesis of this new social field occurs may depend upon the level of continued migration, circulation between homeland and immigration countries, the nature of exit and reception, and the preservation of culture in the future generations. Thus, cultural outcomes in the context of reception have been treated as a continuum with transnationalism occurring somewhere between the extremes of cultural isolation1 and complete assimilation and acculturation. There has always been some level of circular movement between countries and even a few historic transnational communities, resulting from diasporas and expatriate enclaves, that combine elements from the home and host societies (Portes et al. 1999). Recent studies in transnationalism have therefore focused not on whether transnationalism and the emergence of transnational social fields are something new or unique, but rather, if they have become more “regular,” “routinized” and “institutionalized” (Portes et al. 1999). Portes et al. point out that:
1
This outcome would possibly be concentrated in ethnic enclaves if no opportunity for return migration exist.
7
8 For all their significance, early transnational economic and political enterprises were not normative or even common among the vast majority of immigrants, nor were they under girded by the thick web of regular instantaneous communication and easy personal travel that we encounter today (Portes et al.1999). The question then is - how has the migration process changed in recent years such that today’s migrants are no longer simply assimilated into the mainstream, or alternatively isolated from the majority in small enclaves, but rather have options such as “cultural pluralism” (Gordon 1964, as discussed in Alba and Nee 1997) and the development of hybrid transnational identities? This trend has been explained as a result of the growing effects of globalization, including improved accessibility to communication and transportation, as well as the increased scope and complexity of networks of legal and illegal migration. The concept of transnationalism combines historical concepts of cultural blends and hybrids and includes elements such as biculturalism, bilingualism, reinforcement of national identity in the exterior (i.e. trans-local solidarity), as well as social, political, and economic practices that are transacted by migrants across national boundaries (Bamyeh 1993; Glick-Schiller et al.1995). However, debate does exist within the community studying transnationalism as to its exact definition. While Alejando Portes has delimited the study of transnationalism to transnational entrepreneurial activities and other “occupations and activities that require regular and sustained social contacts over time across national borders” (Portes et al. 1999), Steven Vertovec has taken a somewhat broader perspective. Vertovec explains transnationalism as being: A condition in which, despite great distances and notwithstanding the presence of international borders (and all the laws, regulations and national narratives they represent), certain kinds of relationships have been globally intensified and now take place paradoxically in a planet-spanning yet common – however virtual – arena of activity (Vertovec 1999).
8
9 This definition implies the existence of a transnational field or milieu in which transnational identities are shaped. Consistent with this characterization of transnationalism, Bryan R. Roberts et al. operationalize the concept of border-spanning relationships in their study of Mexican migrants communities in Austin, Texas (Roberts et al. 1999). They choose to define transnational communities as “groupings of immigrants who participate on a routine basis in a field of relationships, practices, and norms that include both places of origin and places of destination” (Roberts et al. 1999). By defining a transnational community in terms of its activities, such as the economic activities Portes describes, and interpersonal connections, Roberts et al. are able to apply the concept of transnationalism to the study of migrant communities Thomas Faist further differentiates between forms of transnationalism in his article Transnationalization in international migration: implications for the study of citizenship and culture, by creating a typology of transnational social spaces (Faist 2000b). Faist identifies three categories of social spaces that transcend national boundaries: transnational kinship groups, transnational circuits and transnational communities. Transnational kingship groups, he explains, rely on reciprocity and familial responsibility to maintain ties to the home community. He includes among the activities for these kinship groups the common practice of remittances of earnings to family in the home country and the mutual support networks provided by family members to the newly arrived migrant in the United States. Transnational circuits also rely on social obligations, but often result in the exploitation of the newly arrived co-nationals by the more established and experienced migrants. Common language and cultural practices form the ties that link migrants in transnational circuits. Transnational circuits often include entrepreneurial activities such as formal and informal courier services, money transfers, check cashing, and the establishments that offer goods and services for the consumption of co-nationals (see “ethnic enclaves” Portes 1990; Massey et al. 1994). 9
10 Transnational communities, on the other hand, are characterized by a collective solidarity in which shared “ideas, beliefs, evaluations and symbols” are demonstrated in a common collective identity. In the US context, this solidarity may take the form of what has alternately been called ‘resilient ethnicity,’ ‘reactive formation’ and ‘reactive ethnicity’ (Portes and Rumbaut 1990; Popkin 1999) as well as a mobilization of resources and individuals around abstract symbolic ties to the home country such as nationalism, religion, and culture (Faist 2000b). Thus, transnationalism and transnational social fields are one of the possible outcomes of mass migration in which some form of social, economic or symbolic ties are maintained with the homeland and where some kind of international circulation is present (either by individuals themselves, stand-ins of some kind such as couriers, or “virtual” return through communication technologies). As indicated, these transnational activities and identities may take the form of either ‘hybrids’ of home and destination practices (Glick-Schiller et al.1995) or the creation of an entirely new practices and identities as a response to the receiving community (Popkin 1999; Nagengast and Kearney 1990; Guarnizo 1997). Furthermore, the form, degree, strength, and frequency of contact with the homeland may influence the manifestation of the individual migrant's transnational identity, as well as define the social milieu of the receiving context.
Recent Studies of Transnational Fields In the past two decades specifically, there has been a significant upsurge in the magnitude, complexity, and regularity of transnational communities (Portes 1999; Roberts et al.1999). Consequently, many migration researchers have studied evolving transnational communities such as: Columbian migrants in New York and Los Angeles and their transnational economic, social and 10
11 political involvement (Guarnizo and Diaz 1999), transnational economic enterprises of Salvadoran refugee groups in Los Angeles and Washington D.C. (Landolt et al. 1999), emergence of transnational “social spaces” among Turks living in Germany (Faist 2000), social networks among Salvadoran migrants in San Francisco (Menjivar 2000), Guatemalan Mayan church groups in Los Angeles and connection to home villages via clergy (Popkin 1999) and transnational Mexican labor migrants of rural and urban origin in Austin, Texas (Roberts et al. 1999). These studies endeavor to define the theoretical concepts of transnationalism and transnational social spaces, detail the current practices and activities of transnationals, and understand the macro-structural and micro-level characteristics of migration flows that determine the reality of transnational fields. In their study Transnational migration: a view from Colombia, Guarnizo and Diaz define transnationalism as "a web of patterned and sustained migration-driven relations and activities that transcend national borders and connect Colombians residing abroad with their localities of origin" (Guarnizo and Diaz 1999). Their study is a general accounting of economic, political and sociocultural ties that bind Colombians with their country of origin. Data for their study came from sixty structured and unstructured interviews with informants including: returned, visiting and prospective migrants; relatives, friends and neighbors of migrants in the United States; as well as, local community leaders and national government officials in Columbia. After a preliminary analysis of the data, they have determined that both the sending and receiving contexts, in addition to the initial social capital of the migrant, play a significant role in determining the transnational practices of migrants. These practices are diverse and distinct and are representative of intra-group ties that are divided by class, ethnicity, and origin: The migration experience results in the transnational identity that either facilitates or hinders migrants’ access to business and other opportunities in both countries. Transnational 11
12 migrants that we call ‘successful,’ experience a stronger cultural and legal sense of transnational identity and less successful migrants. In fact, during our fieldwork, we perceived that the former seemed more likely to be dual US-Colombian citizens and be less ' localized' than their less fortunate counterparts... Conversely, we perceived that those of humbler origins, the fluidity of their identity oscillated between the local (caleno, paisa), the national (Columbian), and transnational (dual US – Colombian citizen at most). Apparently, the better-off migrants tend to acquire, as it were, a ‘global,’ less localized sense of identity, whereas the majority seemed to have a more localized, ‘translocal’ sense of identity (Guarnizo and Diaz 1999). Guarnizo and Diaz also note that migrants’ transnational activities depend not only on social capital, but also on the context of reception. They observe differences in the degree and intensity of transnational activities in New York and Los Angeles. Guarnizo and Diaz detailed transnational practices that illustrate economic, political and socio-cultural ties. They listed among economic transnational practices the high level of monetary remittances from migrants in the United States, the lucrative network of the transnational drug trade, and the practices of transnational entrepreneurs. They note that the most successful transnational entrepreneurs were university educated, spoke English well, were lights skinned, and from upper-middle and middle-class families, illustrating the importance of social and human capital. Among the transnational political practices they listed were political rallies in the United States for Columbian candidates, recent changes in Columbian law giving migrants abroad the right to vote and even run in elections in Columbia, and even a push for a ‘special district’ in the United States with representatives to the Senate. In fact, in 1998 Guarnizo and Diaz point out that at least five candidates, who were residents in the United States, ran for seats within the Colombians Senate with one dual citizen winning a spot. Finally, they highlight socio-cultural ties such as the frequent visits by folklore dance groups, professional and amateur soccer teams, popular singers, orchestras, to the United States. They note that maintenance of cultural ties also occurs from the two-way flow of 12
13 visiting relatives and friends during Columbia holidays, the small local radio and TV stations in the United States owned by Columbia networks and the distribution of Colombian newspapers and magazines in the United States. In the article From Hermano Lejano to Hermano Mayor: the dialectics of Salvadoran transnationalism, Landolt, Autler and Baires maintain that the nature of exit and the unsympathetic reception in the United States of Salvadoran refugees helped to determine the “ propensity, complexity and stability” of Salvadoran transnationalism (Landolt et al. 1999). In the case of El Salvador, they explain, circular labor migration to neighboring countries has existed for more than a century. But, it is the circumstances of the departure of almost twenty percent of the population during the civil war of the 1980s and early 1990s that has given migrants "a deep sense of social obligation towards their places of origin" (Landolt et al. 1999, see also Menjivar 2000). These refugees came to the United States with the mentality of one day returning to their home country. Additionally, the xenophobic social climate of the United States and ensuing legal and political battle with the government created a sense of solidarity among Salvadoran migrants: The uncertainties of war and a negative reception in the US conspire to push migrants to maintain ties with their place of origin at a time when the dynamics of the world capitalist system make the maintenance of transnational relations feasible and thus transnational households surprisingly functional (Landolt et al. 1999). In their study, Landolt et al. detail the importance of remittances and other economic ties to the home country. They devise a typology of transnational economic enterprises for use in the analysis of Salvadoran transnationalism. This typology distinguishes between the formal and informal and micro, small and medium-sized transnational entrepreneurial practices. They categorize these practices as circuit enterprises, cultural enterprises, ethnic enterprises, returned 13
14 migrant micro-enterprises, and transnational expansion enterprises. Circuit enterprises are defined as both formal and informal couriers who circulate between the United States and El Salvador carrying letters, cash, goods, and information. The informal viajeros rely on social networks and informal agreements with their customers, while more formal organizations such as ‘Gigante Express’ are primarily known as remittance agencies and shipping services.3 Cultural enterprises on the other hand promote national identity among Salvadorans by providing content and information from the home country. "Cultural enterprises include both ventures the producer distributes Salvadoran mass media such as newspapers, radio and TV programming, and businesses that producer distributes Salvadoran beverages and comestibles" (Landolt et al. 1999). While providing cultural content, many of the mass media venues also provide a stage for political factions with interests in migrants abroad. Ethnic enterprises include primarily small businesses that act as middlemen in ethnic neighborhoods within the United States. This classification includes convenience stores, restaurants, small retail shops, mechanics and street vendors. These businesses rely on a supply of imports from El Salvador to remain economically viable. Returned migrant micro-enterprises on the other hand are businesses located in El Salvador that offer goods in services and are dependent on real economic and human capital acquired abroad. However, as Landolt et al. point out, of include given the incapacity to stimulate capital, the so-called returned migrant entrepreneurs migration cycle is really broken, challenging the conceptual distinction between permanent, returned and cyclical migration" (Landolt et al. 1999). The final category within the typology is that of transnational expansion enterprises. These include new and established Salvadoran companies with transnational marketing and production of goods. These companies are
2
2
Note that all of these enterprises would fall under the category of transnational circuits in Faist’s typology.
14
15 able to take advantage of immigrant settlements in the United States because of their strong cultural and social bonds El Salvador. The practice of what the authors call "targeted globalization" (Landolt et al. 1999). In the case of Salvadorans transnationalism, however, the authors discuss not only an erosion of social boundaries brought about by increase contact between two cultures, such as with other transnational fields, but also a dialectical process between displaced migrants and social elite. Landolt et al. examine how the economic enterprises lead to subsequent political undertakings of transnational entrepreneurs who challenge the established élites and create a discourse that further shapes the nature of a transnational Salvadoran identity: Salvadoran migrants' transnational practices quickly extended beyond the bounds of the household. As transnational economic enterprises and political projects blossomed, they elicited more focused and strategic responses from institutions and power holders in El Salvador. In effect, the case of Salvadoran transnationalism suggests that transnational engagements of grassroots and élites has cumulative transformatory effects because each exchange and interaction appears to sharpen the transnational acumen for dialogue, competition, collaboration, and co-optation of all the players (Landolt et al. 1999). In his article, Guatemalan Mayan migration to Los Angeles: constructing transnational linkages in the context of the settlement process, Eric Popkin explains how the relative ease and affordability of personal travel today is not a universal privilege for all migrant groups, especially as the United States attempts to limit the number of migrants entering the country. He recognizes the recent more prohibitive legal climate for migrants and rising cost of illegal migration and suggests that there is a need, "to explore further the relationship between settlement and transnationalism and determine how migrants maintain transnational connections in contexts in which their physical mobility is limited" (Popkin 1999).
3
See also Itzigsohn et al. Mapping Dominican transnationalism: narrow and broad transnational practices (1999)
15
16 In the case of Kanjobal Mayan migrants in Los Angeles, linkages are maintained through the Mayan Catholic Church4, traditional Guatemalan musical groups, an all-Mayan soccer league, as well as transnational governmental organizations such as the Guatemalan Unity Information Agency (Popkin 1999). Popkin's study implies that there is little need, once the migrant community has reached a critical mass, for physical movement of migrants between home community and host community. Consequently, the importance of continued physical movement of migrants between countries as well as the impact of circular migrants on the development of a transnational identity in future generations of the settled community need to be further explored. He explains: As the Kanjobal migrants increasingly settle in Los Angeles, they cope with extensive discrimination by linking with the growing Pan-Mayan movement and by maintaining connections with their familial households and among. This process generates a response by actors affiliated with the Guatemalan state and church and outcome consistent with Salvadoran case examined by Landolt and associates [1999]. Engaging in dialogue with the consult and AFG [Guatemalan Unity Information Agency] to an interesting extensively with the church in Santa Eulalia [Guatemala], though Kanjobal migrant organizations have more access to Guatemalan state and home country institutions in individual members enjoyed prior to migration. This finding suggests that limits to physical mobility of migrants due to the receiving state immigration policies do not necessarily preclude the establishment of migrant linkages with home country (Popkin 1999). This reaction to the general discrimination against recent migrants in Los Angeles and a distancing from other Latino groups is what has been previously mentioned as ‘reactive ethnicity.’ Popkin finds in his interviews and investigation of the Kanjobal population in L.A. a growing belief that social pressures threaten their identity and existence. As limited Spanish speakers, they are uncomfortable among other Latinos, but are often depicted by majority culture as being “plagued by crime, gang activity and persistent poverty” that affect other Hispanic groups in California (Popkin
for a discussion of formal and informal transnational entrepreneurial activities. 4 Only the priests return annually to the home communities in Guatemala and, with congregational support, organize various relief activities such as fund-raising for hospitals and clinics in the hometowns of the parishioners.
16
17 1999). In reaction to these pressures members of the community have organized to promote the culture, language, and social causes of Kanjobal Mayans and to strengthen ties to the home community. In another study, Transnational migrant communities and Mexican migration to the US, Roberts, Frank and Lozano-Ascencio explain that macro-structural changes in patterns of migration systems, as well as the individual characteristics of today's migrants, have created a new dynamic in transnational fields. After giving a historic account of Mexican - US migration sense the early 1900s, the authors determine that there are three general patterns of migration flows to the United States: a temporary migratory system, permanent settlement patterns, and a growing transnational system.5 They do, however, explain that these three systems are interconnected: The three systems and migration operate simultaneously to shape Mexico-US migration and are by no means mutually exclusive. They are likely to be associated with differences in migrant characteristics... The differences in human and social capital result in disparate rates of access to opportunities in the sending and receiving labor markets, which is reflected in different patterns of migration, such as those embodied in temporary, permanent, or transnational migration systems (Roberts et al. 1999). The temporary migration system, also known as circular labor migration, is based on the structural economic differences of labor markets in the two countries. Characteristic of earlier migration flows from specific sending regions of Central Western Mexico to seasonal agricultural jobs in the United States, the temporary migration system depends on wage differentials and lack of employment opportunity in the home community. As legislative changes during the 1980s and '90s (1986 Immigration Reform Act and 1996 Welfare Reform and Immigration Acts), legalized formerly undocumented, temporary labor migrants they lead to settlement and increased immigration as a result of family unification policies.
17
18 Permanent migration systems also rely on the lack of opportunities in the home country and are a cumulative result (see "cumulative causation" in Massey 1987) of previous migration flows. Roberts et al. explain, "scarcity of jobs and declines in real income for the rural population and for the poorest 40 percent of the urban population make it increasingly difficult to find a stable subsistence base in either countryside or city" (Roberts et al. 1999). Additionally, they make clear that recent increases in border enforcement have also resulted in less circulation, and more permanent settlement as undocumented migrants find the relative risks and costs associated with border crossing are too high to justify frequent return trips. Transnational migratory systems are explained as the result of the "return pull of sending communities and retaining power of receiving communities" (Roberts et al. 1999). The authors explain that this system is dependent on social and economic ties between individuals in the place of origin and destination. Differences exist in the form and degree of transnational activities based on characteristics of the individual migrants such as social and human capital, gender, and the nature of sending receiving communities. Yet, they attribute the growth of these activities to "the ease of communication between Mexico in the US, with a large and relatively permeable land border, good road, rail and air connections, and relatively inexpensive and extensive telecommunication links" (Roberts et al. 1999). After demonstrating the existence of these three systems, which operate simultaneously in today’s Mexico - US migration flows, they turn their attention to a comparison of urban migrants from Mexico City and rural migrants from San Gregorio to Austin, Texas. Here they emphasize the importance of Austin and other cities in the border area as a binational zone of increasing economic and social ties, which has amplified the significance of transnationalism. Paraphrasing other studies (Bustamante 1989; Villa 1994; Veléz-Ibánez 1996; Spencer and Roberts 1998), they explain that: Accounts make clear that the inhabitants on either side of the border are highly interconnected socially and economically, operate internationally, and retain a strong sense of nationality and a difference from the other side. For many inhabitants of these border
5
While temporary and permanent migration systems correspond, in part, to Faist’s transnational kinship groups and circuits, the transnational migration systems of Roberts et al. fits with Faist’s transnational communities.
18
19 communities, their activities and identities are based on a single community, that of the border (Roberts et al. 1999). Consistent with the other studies listed here, they find both small and large-scale transnational entrepreneurial activities, community-based transnational linkages (especially among rule migrants and centered on church activities), and growing transnational political involvement. They find among rural migrants a stronger sense of identity and community: San Gregorians travel back to Mexico frequently, particularly at the end of the year to participate in the Feria Anual. This persistent contact with their town of origin is based on factors such as family commitments, continuing interest in property there, and the possibility of eventual return. There economic and social marginality in Austin reinforces the group identity... The strong linkages among people in San Gregorio's community contrast with the week ties among Mexico City migrants. People from San Gregorio are a homogeneous group in terms of their levels education and types of jobs in Mexico and in the United States. In contrast, migration for Mexico City is heterogeneous in terms of social class, education and labor skills, and internal and international migration experience (Roberts et al. 1999). A further aspect of migration that must be understood in the discussion of transnationalism is the migrant's orientation toward the homeland and propensity for eventual return. In a 1997 report for the California Public Policy Institute, Belinda Reyes analyzed data provided by the Mexican Migration Project (MMP)6, which tracked legal and illegal immigrants from Western Mexico and found that almost 70 percent of all immigrants in the sample returned within 10 years (Reyes 1997). Though intention doesn’t always becomes a reality due to distance, political difficulties in the homeland and simply becoming “established” in the host community (Moltmann 1980; Massey 1987; Schniedewind 1993; Yang 1999), homeland orientation does give the researcher a clue as to the socio-psychological reasons for the development of an identity that is distinct from the receiving context and manifests outwardly many of the cultural and social practices of the homeland. Between
6
The same data set used for the following analysis with focus made on circulation and settlement.
19
20 departure and eventual (intended) return, immigrants to the United States are faced with the complex social negotiations of determining what it is to be the newcomer in an already multicultural and multiethnic country.7
Impact of Transnational Ties Transnational ties have a significant impact on the home community and the receiving locale. The economic ties to the homeland through remittances and savings of labor migrants in the United States have provided capital to bolster the economies of farming villages, allowed migrant families to invest in land or businesses, and afforded relatives the opportunity to join family members in the United States (Massey 1987; Massey et al. 1994; Guarnizo and Diaz 1999; Landolt et al. 1999; Portes 1999). The economic and political power of the transnational populations in the United States has had significant influence on the homeland at the state level as well (Guarnizo and Diaz 1999). In an effort to maintain the strength of ties to the homeland, on March 20, 1998 Mexico granted dual citizenship to its expatriate community, thus allowing them the rights of owning property, traveling back and forth between Mexico and the United States, and voting in national election while acquiring US citizenship (see Roberts et al. 1999 for further implications). Similarly, the Philippines have encouraged emigrants to maintain social and economic ties with the home country, and have come to depend on the earnings of its expatriate community (McCarthy 1994). In yet another case, Taiwan has actively courted well-trained engineers, doctors, scientists and other professionals to either return or to maintain transnational ties with the home country by means of
7
Return rates are actually quite low for most sending countries. As many studies have shown, other factors such as length of stay, economic opportunities in destination country and lack of opportunities in home country, marriage, children, age, home ownership, etc. tend to influence the decision to return or settle more.
20
21 international professional organizations (Swinbanks 1995). These examples illustrate the legitimated status of the expatriate in the homeland. Similarly, transnational communities have provided migrants and their children born in the United States a sense of identity, collective solidarity, and socio-economic mobility while promoting integration into the society of the United States (Landolt et al.1999; Portes 1999). As Roberts et al. explain: Minimally, a transnational field provides immigrants with opportunities and perspectives that are alternatives to committing themselves exclusively either to the new society or to the old. Even those relatively settled in United States retain active ties with their communities and margin to sending remittances back, returning for celebrations, and helping fellow-terms people to migrate (Roberts et al. 1999). As this review of recent studies of transnational fields makes clear, several issues must be considered in future studies of transnationalism. Various categories of transnational economic, social and political activities and practices have been established as well as the growing influences of transnational communities abroad on political and social institutions in the homeland. In the study by Landolt et al., as well as in the piece by Eric Popkin, the progression of a dialogue between grassroots associations and political and social elites has been observed in the dialectical process of the formation of transnational identities. In these articles, the nature of the migrant’s exit from the homeland is also seen as helping to determine his or her orientation toward and solidarity with those left in the homeland. Guarnizo and Diaz, among others, have demonstrated that the success of transnational migrants in the receiving context is determined, in part, by social and human capital as well as the economic and political climate of sending and receiving countries. The context of reception has also been important in shaping the identity of transnational migrants as seen in Popkin’s explanation of reactive ethnicity. Roberts et al. have shown that the urban/rural nature of 21
22 the sending community may be influential in determining the strength of ties among migrants and to their homeland. Roberts et al. also establish the distinctive nature of the border area as a geographic region of strong economic and social transborder ties. Finally, transnationalism has been shown to have implications and influences in both the emigration and immigration countries as it forces governments to deal with the concept of legal and de facto dual-citizenship, political and economic influence of transnationals and the two-way traffic of human talent and economic capital.
Overview of the Current Study Inherent in transnational social fields is a detachment from the spatially bound ties of nationalism and an increased importance of the maintenance of social, economic and symbolic ties across national boundaries. This study proposes a twofold approach for analyzing these ties. First, by means of secondary data analysis using conventional statistical regression techniques, documented and undocumented Mexican migrants, there emerges an image of transnational kinship groups, transnational labor circuits, and formation of a transnational community in which migrants have similar social and economic ties, as well as shared symbolic ties to the homeland and host communities. These symbolic ties, which are manifested in cultural practices, language use and 22
23 the perception of a common identity, bind migrants to communities on both sides of the border and to each other as the form a hybrid culture with elements from the United States and Mexico.
Research Hypotheses Table 1 demonstrates the principal hypotheses that are used in forming the models explored in the analyses of settlement, circulation and return in part two. First, migrants with weak social and economic ties to Mexico and strong social and economic ties in the United States are expected to have longer duration of stay and highest probability of acquiring long-term legal status (H1). According to the second proposition, migrants with both strong or medium social and economic ties to Mexico and strong or medium social and economic ties to the United States will have greater rates of circulation between countries (H2). Finally, return is gauged as the inverse of hypothesis 1: Migrants with strong social and economic ties to Mexico and weak social and economic ties to the Table 1- Social And Economic Ties
Mexico Low High/Mid. High US High High/Mid. Low Outcome Settlement Circulation Return
United States will have shorter duration of stay and lowest probability of acquiring long-term legal status (H3). By comparing the relative strength of real social and economic ties to Mexico with the social and economic relations that bind the individual to the United States, it may be shown which migrants are most likely to assimilate to the dominate culture, seek isolated enclaves (or return migrate), or become members of transnational communities. Once the context of Mexican - US migrant flows has been explored, the study turns, in part three, to a qualitative analysis of transnational fields in the Phoenix area. These social fields are 23
24 observed in interviews with individual cases of migrants who demonstrate varying degrees of social, economic and, most importantly, symbolic ties with Mexico and the United States. Table 2 demonstrates the hypothesis that migrants with relatively weak symbolic ties to Mexico and strong symbolic ties in the United States will have higher propensity for acculturation and social integration (H4), while migrants with strong symbolic ties to Mexico and weak symbolic ties to the United States will have more formulated plans of return and least integration into majority culture (H5). Correspondingly, migrants with both strong/medium symbolic ties to Mexico and strong/
Table 2- Symbolic Ties in Context of Destination
Mexico Low High High/Mid. US High Low High/Mid. Outcome Acculturation Isolation Transnationalism
medium symbolic ties to the United States will have dual modes of social interaction (dependent on setting), higher rates of bilingualism, social integration into both dominant culture and enclave (or homeland) culture (H6).
24
25 PART TWO – SETTLEMENT, CIRCULATION AND RETURN: AN ANALYSIS OF SOCIAL AND ECONOMIC TIES
Introduction and Approach Transnational ties have a significant impact on the home community and the receiving locale. Economic ties such as remittances and entrepreneurial activities influence the dialectical process between transnationals abroad and the emigration country. Moreover, as the economic and political power of the transnational populations in the United States has increased in recent years, a significant influence on the homeland and the on debate about the nature of citizenship, nationality and collective identity has resulted. Contemporary studies hold that migrants are individual actors embedded within social networks and the macro-structural context of international migration flows (Faist 2000a; Massey et al 1998; Portes 1997). Their decisions to permanently or semi-permanently migrate (settle), circulate between countries, and the potentiality for return migration are influenced by the strength of their social and economic ties to their homelands as well as to the receiving contexts in which they now live. In the article, entitled The study of transnationalism: pitfalls and promise of an emergent research field, Portes et al., define the proper unit of analysis for researchers studying transnationalism as, "the individual and his/her support networks." However, they also recognize the importance of larger institutions (communities, economic enterprises, political parties, etc) as having an impact on the construction of a transnational identity (Portes et al. 1999). Portes et al. determine that as a relatively new study, transnational inquiry should focus on the individual level and observe how the aggregate levels are constructed from the micro-level upward (Portes et al. 1999). 25
26 For these reason, this analysis has made use of recent data on Mexican migration that looks at individual migrants within the context of the family and social network. By observing the strength of real social and economic transnational ties that bind individual Mexican migrants to their homeland and to the United States, it may be determined which migrants have a higher propensity for settlement, circulation, or return. The varying degrees of social and economic commitment to Mexico and the definite pragmatic links to the United States, such as relatively higher paying jobs, better living conditions and the presence of family and friends, are found to be impacted by intervening variables such as English ability, educational attainment, and documentation status. Thus, these variables are considered also as this study attempts to better understand the factors that influence the transnational migrant networks and the choice to either settle, circulate or return. As one of the overall goals of this study is to establish the relative importance of various social ties as factors which influence the development of transnational social spaces as they occur somewhere between settlement and potential return, it is vital to establish their importance first in the broader migration flows between Mexico and the United States. By determining which ties are of most relative importance in determining the migration outcomes, analysis of subsequent qualitative data may focus on those ties which are shown to be most significant and, if found to be of importance in the qualitative study, reinforce the explanatory power of both approaches.
Data and Methods Data analyzed in this portion of the study came from the Mexican Migration Project (MMP). The MMP, created in 1982, is an ongoing bi-national research project jointly directed by Jorge Durand of the University of Guadalajara, Mexico and Douglas S. Massey of the University of Pennsylvania. To date, data has been collected from 52 representative sending communities in 26
27 western Mexico [Figure 1] and key receiving locations in United States. During its 18-year history, the MMP has randomly surveyed over 7,000 households in Mexico and an additional 500 households in the United States in non-random "snowball" samples of 10 to 20 out-migrants from each sending community. Surveys in Mexico are conducted in the December and January to capitalize on migrants returning for the holidays. US surveys are completed the following summer in the months of July and August (Mexican Migration Project 1999). Semi-structured interviews are carried out to gather demographic information on family members in a given household and to record migration experiences for each of the family members. Aggregate data on household characteristics including properties, businesses, livestock, and land owned by the families are collected in a database of household information (HOUSFILE). Life histories for all household heads are collected during these interviews. Information on border crossing, social ties in US, and other characteristics of the individual' s migration experience are used to compile a data file of individuals with
27
28 Figure 1- Sending Communities in Western Mexico
migration experience (MIGFILE). Interviews with local informants are used as a means of validating information provided in surveys and additional files on community, regional and national characteristics for use in community level analyses are assembled in supplemental files (Mexican Migration Project 1999). Several problems with this dataset must be acknowledged. First, although it contains a representative sample of select sending communities in western Mexico, the data from the MMP is not representative of all Mexican migrants. Additionally, the principal data file used in this analysis (MIGFILE) relies on information from household heads and therefore over-represents older undocumented male (95.3%) labor migrants [Figure 2]. Moreover, the subset of US interviews is a non-representative sample of migrants from western Mexico who are on average slightly younger (mean age of 38.6 years) than those sampled in Mexico (mean age of 48.1 years). Additionally, this snowball sample is biased toward those who have maintained contact with the sending community. 28
29 As Belinda Reyes points out in her secondary analysis using this dataset, "the snowball sampling techniques used to gather information about immigrants in the United States may systematically under sample people with little connection to the origin location or people living in nontraditional locations in the United States" (Reyes 1997). Initially, bivariate and descriptive statistics were generated to analyze the nature of the sample and examine the correlations between independent and dependent variables. Subsequent analysis, using multivariate linear and logistic regression techniques to control for the effects of age, education, and documentation status, were performed on variables that define the economic commitment of the migrants to family in Mexico as well as economic and social ties to the receiving context. Dependent variables used as indicators of possible outcomes included number of trips as a means of determining circulation and acquisition of legal status and duration of stay to determine settlement. As previously detailed in part one [Table 1] the principal hypotheses used in forming the regression models for this analysis were:
H 1: Weak social and economic ties to Mexico and strong social and economic ties in the United States will result in longer duration of stay and highest probability of acquiring longterm legal status.
H 2: Migrants with both strong or medium social and economic ties to Mexico and strong or medium social and economic ties to the United States will have greater rates of circulation between countries.
29
30 H 3: Migrants with strong social and economic ties to Mexico and weak social and economic ties to the United States will have shorter duration of stay and lowest probability of acquiring long-term legal status.
Descriptive Analysis – Background Characteristics Variables for this analysis were selected after careful consideration of the various theories of international migration and a descriptive analysis of variables available in the MMP data files. Central to the selection were the Network Theory of Migration (Massey et al 1987, 1993, 1994, 1998) and The New Economics of Migration (Stark and Bloom 1985; Stark 1988, 1989). Both of these theories recognize the micro and macro influences on the individual migrant’s decision to move and situate the individual within a broader web of family, community and even national ties. Both theories also recognize (to varying degrees) the agency of the individual in the decision making process, but emphasize the influence of meso-level factors that direct the individual actor to migrate permanently, circulate, return or even not to migrate. Characteristics of individual migrants that have been identified as having influence on propensity to migrate, circulate, or return are: sex, age, education, position
30
31 Figure 3 - Age at Time of First Trip to the U.S.
within the family, relative socio-economic status and access to social and real capital that facilitate the move. As previously mentioned, this dataset is comprised mostly of male head of households. For this reason, the sex of the migrant and role in the household were omitted as control variables. Age of the migrant also becomes problematic as many migrants have returned to settle in Mexico and are no longer involved in the migration cycle. Consequently, controls for age at time of interview [Figure 2] and age at time of first migration experience [Figure 3], an influential variable for determining acculturation, English ability and the development of diverse social ties are included in this study. Education, originally coded as a continuous variable, also posed somewhat of a problem in analysis. Distinct levels of educational attainment were found to have conflicting effects on the dependent variables. Thus, to view these effects more clearly, the variable for number of years of education (EDYEARS) was recoded into five discrete levels of: no education; elementary education 31
32 (one through six years); junior high (seven through nine years); high school (ten through twelve years); and some college (any above thirteen years of education). The majority (62.2%) of respondents in this data file had between one and six years of education (overall mean = 4.6 years). Education was also seen to be negatively correlated with age (Pearson's R of -.406 p<.001). Those migrants who, at the time of the interview, were under thirty-five years old had a mean education of 7.2 years, while those over thirty-five had 3.7 years of education on average. The following cross tabulation [Table 3] explores this relationship in more detail. Another important control variable included in the analysis was English ability, used as a marker for acculturation (in the manner of Gordon 1964 as discussed in Clark 1998 and Alba and Nee 1997). English ability (ENGLISH) was coded as: none (51.9%), understands some English (16.%), understands English well (4.7%), speaks some English (17.7%), and speaks English well (9.0%). Economic success in the host community, acquisition of legal status, and the degree to which the migrant becomes involved in the broader community are all positively related to length of stay, and are all influenced by the level of linguistic proficiency the migrant acquires. However, causal order for English ability and duration of stay in the United States cannot be clearly established as the
Table 3 - Crosstabulation of Educational Attainment by Age
Education None 1-6 years 6-9 years 9-12 years 13+ years % of Total 0-18 -.1% .2% --.1% 18-25 .9% 4.3% 17.9% 18.3% 3.0% 5.9% 25-35 4.5% 20.5% 40.5% 44.5% 50.2% 22.8% Age 35-45 11.2% 26.1% 24.3% 22.5% 31.8% 23.6% 45-55 21.0% 21.3% 10.2% 9.6% 9.5% 18.8% 55-65 27.6% 15.8% 4.4% 4.1% 2.5% 15.2% 65+ 34.9% 11.9% 2.4% .9% 3.0% 13.6% 100.0% 100.0% 100.0% 100.0% 100.0% 100.0%
32
33 dynamic process of learning a language occurs over time spent in the destination country. For this reason, English ability is included in the full model, but omitted in a parallel regression (Model 2 in the multivariate analyses to follow) so that the effects of this variable may be observed. Additionally, English was found to be highly correlated with years of education (Pearson’s R of .416 p<.001), a variable that clearly precedes in temporal order. 8 Thus, the argument may be made that those with a higher educational attainment are better equipped with the human capital to master the task of learning a new language and negotiate the complex social/legal landscape of the destination country. Documentation status on last or current trip (DOCUSL) is the final control variable. Documentation clearly influences the length of stay in the United States. In the case of permanent residence or citizenship, documentation could lengthen the time it is possible to spend in the United States, while visas granted by the earlier Bracero program, limited the amount of time and even number of trips that the migrant may make to the United States. Documentation status was thus defined as: undocumented (56.5%), Bracero (10.7%), SAW (6.5%), tourist visa (6.1%), amnesty (5.0%), permanent resident (14.3%), and citizen (0.9%). Differences in documentation status by place of interview must also be noted. While interviewees in Mexico and the United States were most likely to be undocumented (60.1% and 38.7% respectively), there are higher rates of long-term documentation among migrants interviewed in the US sample [Table 4]. Additionally, there is a problem of null cells in the US sample as those migrants who were last documented under the Bracero program, which lasted from 1942 until 1964, have all returned to Mexico or are presently in the United States under another status. Thought was given to collapsing this group with the SAW program category, as both are short-term labor visas.
33
34 However, as SAW granted legal status to previously undocumented workers in 1986, the relationship between these legal categories and the outcome variables are found to be quite distinct. In fact, whereas Bracero is negatively correlated with the duration of stay (Pearson’s R of -.199 p<.001), SAW program documentation is
Table 4 - Crosstabulation: Documentation by Place of Interview
Documentation Status Place of Interview Mexico US % of Total Undoc. 60.1% 38.7% 56.5% Bracero 12.8% -10.7% Tourist 6.7% 2.7% 6.1% US Citizen Amnest y .5% 3.1% 2.7% 14.8% .9% 5.0% SAW 6.2% 8.3% 6.5% Perm. Resident 10.6% 32.9% 14.3% 100.0% 100.0% 100.0% Total
positively correlated (Pearson’s R of .041p<.001). Therefore these categories were left as independent, discrete designations.
Descriptive Analysis – Social and Economic Ties The research hypothesis for this portion of the analysis is that the greater the real economic and social ties to the host country, the higher the propensity to settle as shown in longer total durations of stay and by acquisition of legal status. Conversely, strong real ties to the home community may result in higher rates of circulation as revealed by the number of trips the migrant has made between countries. Therefore, the variables selected that demonstrate these bonds to both home and host countries are: sum of all family owned land, lots, buildings in Mexico; sum of family owned vehicles in Mexico; sum of family owned businesses in Mexico; monthly remittance to
8
Interaction variables computed for English and Education and were found to be significant. However, high
34
35 Mexico; migrant had US bank account; US monthly wage; monthly Rent in US; spouse of migrant on trip to US; kids on trip; total of all relatives in US; number of friends from Mexico in US; migrant membership in formal social groups; diversity of non-familial social ties in US. Strong family ties in Mexico may indicate forces that pull the migrant home and also press the migrant to go abroad so as to “maximize excepted [family] income, but also to minimize risks and to loosen constraints associated with various kinds of market failures” (Stark 1991, as paraphrased by Massey et al. 1998). Measurement of the strength of these family ties becomes difficult with the dataset at hand.9 Thus, family owned property, vehicles and businesses along with remittances from the United States must act as proxies for these attachments. The rationale is that migrants with economic and social obligations in Mexico will remit more money and be more likely to return migrate or circulate if they, or their family, own real property in the home community.10 At the same time, the maintenance of this property, as well as the acquisition of new properties “relative to other households,” may increase the total duration of stay in the country of destination (Stark 1991, in Massey et al. 1998). Descriptive statistics for each of these variables are provided in Table 5. In addition, the following bar chart [Figure 4] also provides some understanding of the degree of monetary commitment the migrant makes to the homeland. With 72.1% of the sample sending remittances (19% of whom remit more than half their monthly earnings), it can be seen as a common aspect of the migration experience.
Variance Inflation Factors (VIF>2.0) indicated model instability. 9 For this reason a companion qualitative study on Mexican immigrants’ symbolic ties to homeland is currently being conducted.
10
This is the same rationale used by the Immigration and Naturalization Service in granting tourist visas.
35
36 Table 5 - Descriptive Statistics for Control Variables
Variable Sum of all family owned land, lots, buildings in Mexico Sum of family owned vehicles in Mexico Sum of family owned businesses in Mexico Monthly Remittance to Mexico in dollars Migrant had US bank account Average monthly income in US in dollars Monthly Rent in US in dollars Spouse of migrant on trip to US Kids on trip Number of all family members in US Number of friends (from Mex.) in US Migrant membership in formal social groups in US Diversity of (non-familial) social ties in US Mean 1.13 .69 .45 169 .15 995 146 .18 .27 3.78 6.74 .16 1.55 Std. Deviation .99 .95 .75 275 .35 985 254 .39 .41 4.23 13.77 .42 1.45
Economic ties to the host community were measured by the establishment of a bank account in the United States, average monthly wage in the United States, and the monthly rent while living in the United States. Only 15.3% of the sample reported having established a US based bank account. However, as the above crosstabulation [Table 6] shows, long-term legal migrants had higher frequencies of establishing a bank account than short-term and undocumented migrants. Monthly wages (computed from reported hourly wage on last/current trip times reported number of hours worked per week times 4.33 weeks), and to a lesser extent monthly rent, have great variability. While the mean monthly earnings were around $995, the range extended from $0 to $8184. This broad range and large standard deviation ($985) were due in part to the possible imprecision in the wages provided by the retrospective data as respondents, whose last trip to the United States may have been decades in the past, provided figures that may have been inflated or inaccurate.11
11
Belinda Reyes points out, “ Retrospective data, unlike longitudinal data, may be more accurate at representing recent events than past events. For example, people may be very precise at estimating their current wages, but may inflate or deflate the wages they earned 20 years ago. This will lead to a downward bias in the estimates” (Reyes 1997).
36
37 Figure 4 - Remittance as a Percentage of Income
40 35 30 25 20 15 10 5 0
No Remit Less than 25% 25 to 50% 50 to 75% More than 75%
36 28
17 12 7
Finally, US based social ties and the diversity of those ties were measured using variables from the migrant’s last trip to the United States including: spouse (if married) accompanied the migrant, children accompanied the migrant, the sum of all family in the United States 12, the number of friends from Mexico in the United States, membership in formal social groups in the United States, and association with various other ethnic groups as a measure of diversity of ties. Most of these variables were fairly straightforward in their coding and do not need further explanation. Some descriptive statistics of interest in US social ties include:
37
38 20.4% of migrants were accompanied by their spouses 27.5% had one or more children in the United States 24.4% had no family members while 65.6% had one to ten family members in the United States 51.5% did not have friends from Mexico, 42.2% had one to twenty friends. 11.3% belonged to formal social groups, clubs, or organizations. 13.8% had Chicano, Black, Anglo and other (non-Mexican) Latino friends.
Table 6 - Crosstabulation of U.S. Bank Account by Documentation
US Account Yes No % of Total Perm. Resident 41.2% 58.8% 14.2% Undoc. 8.6% 91.4% 56.8% Bracero .2% 99.8% 10.8% Tourist 13.6% 86.4% 5.5% US Citizen 50.0% 50.0% .9% Amnesty 40.0% 60.0% 5.1% SAW 19.2% 80.8% 6.7% Total 15.3% 84.7% 100.0%
12
To avoid giving too much weight to large extended families and more importance to closer family ties, sum of family ties was computed using the mean of all uncles, aunts, cousins, and in-laws in the US, then added them to the number of siblings, parents, and grandparents in the US.
38
39 Table 7 - OLS Regression Predicting Duration of Stay
Model 1
Constant Background Measures: †Interview takes place in US (N= 677) 27.632 61.447 2.548 -2.365 29.679 44.935 45.568 87.733 10.068 -1.815 -11.762 -19.702 -1.597 -61.906 25.653 52.113 74.181 109.210 *** *** *** *** *** * ** *** *** *** *** *** *** *** *** **
Model 2
11.613 35.911 2.432 -2.430 --------10.922 3.140 -6.519 -14.629 -1.641 -52.164 22.286 48.967 64.093 112.142 *** *** *** *** *** * ** *** *** *** ***
Model 3
11.155 29.042 2.499 -2.270 22.615 32.207 29.247 49.131 8.042 -4.133 -16.117 -23.450 -4.673 -50.175 18.208 43.218 58.799 104.544 *** *** *** *** *** ** *** *** *** *** *** *** *** *** *** *
---------
2.216 -.171 -2.974 1.364 * ***
1.938 -.806 -3.389 1.043 ** ** R2 .596
------------------***
30.426 .923 5.026 12.858 11.931 1.507 -.243 6.472 5.973 .635
*** *** *** ** *** *** ** * *** ***
25.899 .804 4.583 11.379 11.296 1.388 -.203 3.625 3.540 .650
*** *** *** ** *** *** **
*** ***
* p .05; ** p .01; *** p .001 Unstandardized regression coefficients † This variable is highly correlated with English ability (Pearson’s R = .386, p<.001).
N=3014
39
40 Regression Analysis – Duration of Stay Table 7 shows ordinary least squares regression explaining the variance in the population for the variable - duration of stay (USEXP), the total number of months of all trips combined. Age at time of interview and age of first trip have been centered on the mean to allow for a more interpretable constant. As previously indicated categorical variables have been recoded into dummy variables to clarify the effects of each level of English ability, education, and documentation status as well as having bank account, spouse on trip, or children on trip. The reference group, is undocumented migrants, with no education, and no English ability, had no bank account in the United States, who were interviewed in Mexico and either have no spouse or children or whose spouse and children stayed in Mexico. In other words, those with the fewest ties to the United States and the lowest socio-economic indicators. Model 1 establishes a baseline by including only the control variables for place of interview, age at time of interview, age at first trip to the United States, English ability, educational attainment, and documentation status. This model alone is quite strong in explaining the variance in the population (R2=.596 p<.001) and, with the exception of only a few discrete categories (junior high education and tourist status on last trip), all variables are highly significant. Those who were interviewed in the United States are a distinct group who has spent much longer in the receiving context. As demonstrated earlier in the descriptive statistics, these migrants are generally younger, better educated, and yet, by nature of the sampling procedure, more likely to have maintained contact with the sending community. While migrants older than the mean age (46.5 years) at time of interview, are more likely to have stayed longer in the United States, this may be the result of simply having had the opportunity to spend more years abroad. For this reason the variable defining age at first trip to US was introduced to offset the effects of age on duration of stay. 40
41 Migrants who came later than 25.5 years (mean age of first trip), stayed for shorter total durations, thus canceling the effect of an elevated age at time of interview. English ability has a significant and powerful effect (second only to documentation status) on the total number of months the migrant stays in the United States. As the literature suggests, one of the first steps to economic assimilation and successful transnational entrepreneurial activity is the ability to speak English. However, as previously mentioned causal order is difficult to establish in this relationship. Thus, for purposes of comparison, English ability has been omitted in Model 2. Documentation status is the most important variable in determining length of stay. Tightening restrictions on employers and hostile social environment toward undocumented workers, including some legal migrants toward their undocumented co-nationals, has provided greater rewards for those with legal status and thus longer stays in the United States. It must be noted that those migrants who, on their last trip to the United States were on the Bracero program were found to stay far less total time in United States. Though documented, the legal restriction of their visa limited the amount of time spent here. Also of importance is the fact that many Bracero workers later returned to the United States under other documentation status or as undocumented migrants so those respondents who indicated Bracero status on their last trip are then most likely to be older men no longer participating in the migration system. Finally, there is a progression from special agricultural worker status (SAW) to amnesty, to permanent resident and finally to citizenship in terms of length of stay and apparent settlement. However, as this dataset is built from a longitudinal study, rather than a cross-sectional sample at a given time, the documentation status of individual migrants who were interviewed in later years may not be exactly comparable to migrants from earlier waves. The effect of documentation status appears to be fairly constant in all three models and are, with the exception of tourist status, highly significant in determining length of stay. 41
42 Model 2 is also very robust (R =.635 p<.001) and adds the effects of economic ties to Mexico, economic ties to the United States and finally social ties to the United States, but removes the effects of English ability. Variables describing the economic commitment of the migrant to Mexico demonstrate the fact that, with the exception of family owned businesses, strong economic ties compel the migrant to stay for longer periods in the United States. This finding seems to fit the theory that the family unit will offset market risks by sending members abroad to take advantage of wage differentials and greater availability of employment. Most significant is the association between monthly remittances and duration of stay: for every hundred dollars the migrant sends home, his stay is lengthened by more than a month, perhaps to offset this cost. Business ownership, on the other hand, has a negative relationship to length of stay in the United States. This may be due in part to the need for family laborers to stay in Mexico to work and also to a lesser demand for remittances from abroad to sustain the family. Real property, such as vehicles, land, houses, etc. seem to have the least effect and were found not to be of statistical significance. US economic ties are added in the following block. Most prominent is the relative importance of having a bank account in the United States. This variable demonstrates the symbolic commitment toward settlement that the migrant has made by negotiating the legal and social barriers to getting the account (i.e. genuine or counterfeit photo identification, social security number, etc.). As a result of this economic commitment, the total length of stay is predicted to increase by more than two years. Though not as powerful as having a bank account, the monthly rent the migrant pays also symbolizes a commitment to the destination. A migrant whose only goal is to work for a few months, save money, and return will spend less on the physical comforts of having a nicer place to live. This variable, however, may be influenced heavily by the city in the United States where the migrant is residing and if his children and spouse have come to the United States as well. Of relative 42
2
43 importance too is the effect of monthly wage on the duration of stay. All else being equal, it is predicted that the migrant stay an additional month for every one hundred dollars earned monthly. While Mexican economic ties were found to have only a marginal overall effect in Model 2 (R2 change for block =.014, p<.001), the effects of US economic ties were especially influential (R2 change for block =.057, p<.001). Though more important than Mexican economic ties in explaining the variance in the population, US social ties are not as powerful a predictor as US economic ties (Model 2 R2 change for block =.019, p<.001). Of most importance are the conditions in which the spouse and children accompany the migrant to the United States. Having spouse and children along lengthen the predicted stay by an estimated 2 years. Together spouse and children by far outweigh the effects of other social ties of extended family, friends, formal social ties and diversity of ties. Notably though is that for every family member in the United States the migrant is predicted to stay an additional month and a half. This may have a significant cumulative effect if the migrant has many relatives here and demonstrates the importance of family ties in determining settlement. Interestingly, the effect of having friends from the homeland is slightly negatively related to the length of stay. This may be evidence of the existence of transnational circuits, which are further explored in part three. Lastly, model 3 reintroduces the effects of English ability (R2=.650 p<.001). This model explains some of the overlap of place of interview, educational attainment and social ties with English ability. In model 2, when economic and social ties were considered, the effects of the place of interview were observed to be far weaker than in model 1. Controlling for language ability in model 3 further reduces these effects. Educational attainment, on the other hand, has the opposite effect. When controlling for English ability, the benefit of having a high degree of education decreases the duration of stay especially when unaccompanied by high English ability. Yet, 43
44 regardless of language ability the reward for educational attainment is not present in the United States for the Mexican migrant, as human capital is not easily transferred. The influence of US economic and social ties were also somewhat mitigated by the addition of English ability. Of particular interest is the slight shift (-4.5 months) in the effect that having a US bank account has on duration of stay, indicating that English ability accounts for some of the power of this variable. Similarly, diversity of non-familial ties, as measured by associations with other nonMexican ethnic groups, is diminished by inclusion of English ability. Thus, strength of social and economic ties become slightly less important, though still significant, in determining length of stay as English ability “explains” some of the variation in length of stay. The results show that while economic ties to the homeland lengthen the period of time abroad, these effects are overshadowed by economic and social ties to the receiving context. Most important is the symbolic commitment toward settlement by having opened a bank account and having been accompanied by spouse or children to the United States. These results tend to support the hypothesis that strong ties to the United States lengthen the time spent abroad and, perhaps, indicate a propensity to settle. On the other hand, variables that demonstrate social ties to Mexico were not available in this dataset. As a result, hypothesis three, which estimates shorter duration in the United States, is not clearly proven or disproved. Better measures of symbolic ties to home and host communities, would be helpful in gauging this commitment toward settlement or eventual return as the variables analyzed herein can only hint at the emotional and psychological bonds of the migrant.
44
45 Table 8 - OLS Regression Predicting Number of Trips 3.241 -2.812 .119 -.153 1.319 1.394 1.637 .274 .462 -.432 -1.180 -1.451 .697 -2.569 5.697 5.312 5.444 1.289 --------*** *** *** *** * ** *** *** *** *** *** *** *** Model 2 2.608 -2.884 .113 -.153 --------.467 -.246 -1.136 -1.221 .478 -2.310 5.475 5.132 4.989 .927 .181 .197 -.105 .143 *** *** *** *** *** * ** *** *** *** *** Model 3 2.415 -3.111 .118 -.149 1.195 1.178 1.453 .116 .341 -.458 -1.170 -1.334 .366 -2.174 5.203 4.912 4.844 1.066 .195 .179 -.096 .125 *** * *** *** *** *** ** ** *** *** *** *** *** ** ***
-------------------
-.856 .029 -.088 .041 1.339 .084 .020 -.243 .005
** **
-.803 .029 -.064 -.044
** **
*** *** **
1.322 .081 .020 -.186 -.090
*** *** **
R
2
.336 Unstandardized regression coefficients
***
.349
***
.359 N=3005
***
* p .05; ** p .01; *** p .001
45
46 Regression Analysis – Circulation Analysis of circulation between Mexico and US [Table 8] utilizes the same ordinary least squares regression models described above. The full model, though explaining 35.9% of the variance in the population (p<.001), is not as strong as that of duration of stay (R2=.650 p<.001). Nonetheless, patterns do emerge that tend to support the hypothesis that strong social and economic ties to the homeland and to the host country produce more circulation between countries. In all three models, there is a reduction in total number of circulations if the respondent was interviewed in the United States (bringing estimated total circulations to zero, indicating that this is most likely the first and only trip). Since these subjects are more recent arrivals, this may be a reflection of the effects of strengthened border enforcement, which have increased the relative risks of circulation. The current context may create longer stays and fewer circulations as the cost of border crossing (emotional and psychological as well as financial) has increased disproportionately to the ties that induce and deter circulation. As this dataset only includes interviews up to 1997, and is comprised of a majority of undocumented migrants who have returned to Mexico, it is difficult to attribute all of the effect of this variable to increased border enforcement. Future analysis of data for 1997 to present may confirm the causal relationship between decreased circulation, lengthened stay, and border enforcement. Age, although statistically significant, has only a minor role in determining the number of circulations. At ten years above the mean (or about 56.5 years), the migrant is only estimated to have circulated once more than those at the mean age, when controlling for all other variables. Conversely, as age of first trip increases, the number of circulations decreases at a rate similar to that of age at time of interview. For example, if the age at first trip is ten years above the mean (35.5 years), the migrant is expected to have experienced 1.4 fewer trips, all else being equal. 46
47 Interestingly, English ability (models 1 and 3) has a relatively constant effect on the number of circulations except for those who are highly proficient in English. This indicates that those with average English ability, relative to other migrants in the dataset, are more likely to circulate than those with no English ability. Likewise, those with higher relative proficiencies are better able to find permanent employment and are more likely to be citizens in the United States. However, it can only be surmised that it is a very small group or that the number of circulations is so close to that of the omitted group so as not to be significantly different. There is a negative relationship between education and total number of trips. In all three models, increased education results in fewer trips. Those with more than a high school education are estimated to circulate once less than those with no education, all else being the equal. An explanation may be the same as that with duration of stay: migrants with a higher than average education will stay for shorter periods and then return migrate to Mexico where their education will have a greater relative recompense than in the United States. Documentation status, again, is the strongest variable in the regression. Unlike duration of stay, those with special agricultural worker status, amnesty and permanent residence as having the highest rates of circulation while those with citizen-ship are only marginally above undocumented. This may be due, in part, to the fact that until the mid 1980s when SAW and Amnesty were granted, many migrants found it easiest to maintain a home in Mexico and simply return during holidays or (in the case of seasonal agricultural workers) during the winters, thus increasing their total number of circulations. Permanent residents also may have been undocumented workers in the labor circulation at one time or they might be those with stronger ties to Mexico who were included in the sample when they returned to visit family during the holidays.
47
48 It appears that, in the current environment and with this particular dataset, social and economic ties to Mexico and the United States have far less of an influence on circulation than the control variables (overall R2 change from model 1 to model 3 = .023, p<.001). This may be due, to some extent, to the variables used as measures of these ties, as well as the greater sway of the macrostructural impediments to circulation mentioned before (border enforcement, relative cost and risk). However, there is evidence that having family in the United States, especially children (Model 3 b = 1.322, p<.001), will influence circulation. Likewise, having made a stronger financial commitment to the receiving context checks circulation (Model 3 US wage b = -.803, p<.001), whereas having a greater family financial responsibility in Mexico encourages circulation (Model 3 monthly remit b = .125, p<.01). Although legal status, education, and place of interview have the greatest influence, social and economic ties do play a role in determining number of circulations between countries. Data reflecting more recent migration and including more migrants currently in the United States may yield stronger evidence to support Hypothesis Two (strong ties to both home and receiving countries produces greater circulation) or demonstrate the change in migration flows as a result of intensified border enforcement.
48
49 Table 9 - Logistic Regression of Acquisition of Long-term Legal Status Nagelkerke R2 Cox & Snell R
2
Model 2 *** *** *** *** -3.030 .259 .019 -.041 .901 .711 1.372 1.319 * .268 -.224 .190 -.044 .089 ** ** *** .153 -.223 .073 * *** *** *** *** *** *** *** *** ***
-2.906 .498 .014 -.046 --------.392 .009 .403 .234 .097 .180 -.210 .084
.478 .056 -.033 -.111 .868 .063 .006 .088 .033 .327 .230 2866.650 787.771 20 Unstandardized regression coefficients
*** ***
.349 .049 -.035 -.173
* ***
*** ***
.847 .059 .007 .052 -.063 .362 .254 2771.008 883.413 24
*** *** *
-2 Log likelihood Model Chi-square df * p .05; ** p .01; *** p .001
N=3014
49
50 Regression Analysis – Acquisition of Long-term Legal Status Acquisition of long-term legal status (LLS) signifies an intention to settle permanently or semi-permanently in the United States and supports hypothesis one (high US ties result in circulation or settlement) as well as hypothesis three (high Mexican ties result in circulation or return). This outcome variable was produced by collapsing citizen, permanent resident, amnesty and special agricultural worker status (another designation of amnesty) into long-term legal status. At the same time, undocumented, Bracero and tourist were consolidated into non long-term legal status. Analysis was then made using binary logistic regression to estimate the probabilities of acquiring long-term legal status [Table 9]. Model 1 shows the effects of age, education, Mexican economic ties, US economic ties and US social ties on the probability of acquiring LLS. This model predicts 78.7% of cases, representing an improvement of 5.3% over the dependent variable marginal (an overall increase of 20% of the maximum possible improvement). Model 2 adds the control of English ability, affecting the power and influence of economic and social ties to the United States and Mexico. Model 2 is able to predict 79.4% of cases and represents a gain of 6.0% over the dependent variable marginal, or an additional 3% of the maximum possible. Thus, English ability adds to the predictive power of the overall model. Place of interview was significant in determining length of stay and circulation between the United States and Mexico. In model 1, place of interview is highly significant (p<.001) and US based interviews increase the odds that the respondent will have LLS by 1.65. This may also be expressed as a 65% increase in the probability that the migrant interviewed in the United States is more likely to have long-term legal status.13 However, when controls for English ability are introduced, this
13
Transformation of the log it coefficient to percentage change in odds calculated using: 100* (eb –1).
50
51 variable is found to be statistically insignificant (model 2). As these variables are highly correlated, establishing causal order is problematic. Age follows the same pattern established in the previous ordinary least squares regressions. Respondents who were older at the time of interview were more likely to have acquired LLS: an increase of 1.9% for each year above the mean. Similarly, being older on the first trip decreases the odds of attaining long-term legal status. For every year above the mean age at first migration, the respondent is estimated to have a decrease in the probability of having established LLS by 4.1%. English ability has the greatest correspondence to predicting the attainment of long-term legal documentation. Simply understanding some English increases odds of LLS acquisition by almost 146%. Likewise, being highly proficient in English increases those odds by 274% demonstrating the importance of English ability in being able to negotiate the legal and social barriers to gaining legal status. Of the measures indicating social and economic ties, the most significant are having family owned business in Mexico, having a US bank account, and being accompanied by children in the United States A family owned business has the consequence of drawing the migrant back to the homeland. Those migrants with family owned businesses are 20% less likely to acquire LLS. In contrast, US economic ties symbolized by having a US bank account are seen to increase odds of establishing long-term legal status: an increase in probability of 41.7%. Finally, having children in the receiving context improves the outcome of having LLS by 133.4%, thus indicating the importance of family ties in the United States.14
51
52 Conclusions The results of descriptive, ordinary least squares and logistic regression analyses of this dataset have supported the primary hypotheses that strong social and economic ties to the United States will result in longer duration of stay and increased circulation. Findings are ambiguous as to the effect of ties to the homeland as only proxies for economic ties were represented in the dataset. Most significant were the variables that could be interpreted as representing the greatest symbolic ties to home or destination: having established a US bank account (strong economic commitment to the destination) and bringing children to the United States (strong social/familial commitment), versus having a family owned business in Mexico (strong social/economic tie to homeland). Identification of these variables and the concepts that they represent help to define the context in which Mexican transnational communities exist. They also help to establish that there are multiple trajectories that a migrant may take in the migration process. These trajectories are neither exclusive nor entirely linear as they provide migrants different opportunities throughout their migration life history. Further exploration of the strength of these ties and, more importantly, an analysis of symbolic ties to the homeland among permanent and semi-permanent settlers will allow for an explanation of the causal mechanism in the creation of transnational fields. Thus, this analysis has provided a perspective on the nature of recent migration flows, establishing patterns of settlement, circulation and return as they relate to homeland ties. This study is useful in establishing a viewpoint for the following analysis and may yield an explanatory model for processes such as complete assimilation, blending (i.e. transnationalism), and formation of separate enclaves within a framework of cultural pluralism.
14
Note too that an additional family member in the US increases odds by 6.1%, and friends from Mexico increases odds by 1.0%. Though individually small, these variables have a substantial cumulative effects.
52
53 PART THREE – TRANSNATIONAL FIELDS: A STUDY OF SYMBOLIC TIES
Introduction While the results of the Mexican Migration Project analyses suggest some support for the importance of economic and social ties on Mexican migration patterns, in depth interviews conducted for this study establish the direct role of these ties to Mexico on the development of a transnational identity that encompasses cultural elements of both home country and the receiving context. This study, then, focuses on the symbolic ties of documented and undocumented Mexican migrants to the home community in Mexico and on the influence of these ties in the membership and participation in transnational fields in the Phoenix area. This analysis utilizes the typology of transnational social spaces of Thomas Faist as it investigates the respondents’ membership in transnational kinship groups, transnational circuits, and transnational communities (Faist 2000b). The individuals interviewed in this study act as members of several of these categories at once and often to divide their loyalties between pragmatic economic concerns in the United States and a symbolic orientation toward the homeland. This study builds on the previous analysis by examining social and economic relations with sending and receiving countries, the importance of human and social capital, and the intentions of migrants to settle, circulate and return migrate. Symbolic ties, defined as the more elusive emotive bonds to a nation that may be observed in the daily cultural practices, use of cultural icons, language preference, and self-reported observations of the respondents’ connections to the home country, were added to the previous theoretical models and analyzed using qualitative analysis techniques such as network analysis and coding of narrative data (Coffey and Atkinson 1996). 53
54 As with the analysis in part two, real social and economic ties were explored. The survey instrument covered questions on earnings and expenses, savings, and both familial and social ties to Mexico. In addition to the strength of ties to the home community, as indicated by frequency of contact (telephone calls, letters, visits) and remittances, this study observed symbolic cultural ties such as:
Language use at home, work, and with peers. Preference in music, food, and entertainment. Usage of cultural icons such as the Guadalupana telephone card. Membership in formal and informal social groups. Ethnic diversity of social ties as a measure of social distance between groups. Family ties in the United States; intended plans for settlement or return. The definition of abstract concepts such as national identity, patriotism, emotional connection to the homeland. Exploration of the feelings of being the “other” in the host community.
As explained in Part One, the research hypothesis guiding this qualitative analysis involve an exploration of assimilation and acculturation, enclaves and isolated social groups, and finally transnational social spaces. Migrants with relatively weak symbolic ties to Mexico and strong symbolic ties in the United States will have higher propensity for acculturation and social integration (H4). On the other hand, migrants with strong symbolic ties to Mexico and weak symbolic ties to the United States will have more formulated plans of return and least integration into majority 54
55 culture (H5). Finally, migrants with both strong/medium symbolic ties to Mexico and strong/medium symbolic ties to the United States will exhibit evidence of occupying transnational social spaces by having dual modes of social interaction (dependent on setting), higher rates of bilingualism, and social integration into both dominant culture and enclave (or homeland) cultures (H6).
Source of Data Comprehensive, semi-structured interviews with documented and undocumented migrants from Mexico now living in the Greater Phoenix area were conducted during the summer of 2000. The twenty-eight respondents for this analysis were found using non-random, “snowball” sampling techniques (Biernacki and Waldorf 1981; Granovetter 1976; Massey 1987). Initially, approximately 20 flyers were posted in various community gathering places in an area of high concentrations of Mexican migrants [Appendix A]. Shopping centers, laundry facilities, restaurants and apartment complexes known to be used frequently by migrants were targeted for postings. From these flyers, a core group of contacts or informants emerged. Following the interviews, respondents were asked to provide two more contacts (first name and phone numbers), or as an alternative to pass along contact information for the interviewer. Even though the majority of respondents were in a delicate legal position (23 of the 28 respondents were undocumented), the reference of someone known personally to them provided entrée in most cases.15 An additional group of five respondents came from an informant who is a member of a neighborhood Catholic Church with a high Mexican membership.
15
Only two direct referrals declined to be interviewed.
55
56 Each interview, conducted entirely in Spanish, lasted for about one hour and explored social, economic, and cultural ties to the home country. In addition, these interviews detailed the migrants’ individual migration experiences from their home communities to the United States, documented information regarding their human and social capital and observed the role of support networks in the immigration process. A laptop computer utilizing SurveyGold software was used to record responses to preliminary structured interview questions and to record notes during more open-ended, subjective responses. Additionally, interviews were taped so that responses to probing question on the nature of symbolic ties could later be transcribed and analyzed. To protect the identity of the migrants, respondents were instructed to select a pseudonym to be used on the tapes, databases, and in reports.16 Following the research proposal agreement with the Institutional Review Board of Arizona State University [Appendix B], all notes with real names and any other materials that could be used to identify the subjects were destroyed following interviews. It must be noted that although snowball sampling techniques are quite useful for providing respondents in highly sensitive social research, the results cannot be said to be representative, in this case, of the population of all Mexican migrants. Furthermore, as the initial informants were a selfselecting group, bias may be introduced from the outset toward individuals who are more socially integrated, have higher levels of social and human capital, and are less fearful of negative legal consequences of responding to advertising that solicited recent migrants regardless of legal status. This sample does, however, provide an image of an interconnected network on both family and community levels and may be used to illustrate findings of the quantitative research presented in part two.
16
As two migrants selected the same name (Hector), one was arbitrarily reassigned the name Jorge.
56
57 The Receiving Context Hispanics in the United States The most recent figures of the Current Population Survey (CPS) indicate that Hispanics of Mexican origin (both native and foreign-born combined) account for 65.2% of the 31.7 million Hispanics in the United States (Ramirez 2000). This figure represents almost 12% of the entire US population and, as the Population Projections Program at the US Census Bureau estimates, the Hispanic population is projected to grow to more than 43.6 million by 2010 assuming midlevels of immigration (Population Projections Program 2000). According to the same 1999 CPS data, 56.1% of Hispanics have a high school education or more (as compared to 87.7% of non-Hispanic Whites and 84.7% of Asians)17, they are three times more likely to live below the poverty level than Whites, and Hispanics participate in the labor force in equal proportions as non-Hispanic Whites.18 These figures are indicative of the social context within the United States where economic and educational assimilation is not occurring as rapidly for Hispanics as perhaps for other immigrant groups (Alba and Nee 1997; Clark 1998). In fact, in the CPS report Educational Attainment in the United States, the authors point out that: The educational attainment of young Hispanics (ages 25 to 29) was substantially lower, however, than for other groups. Moreover, during the past decade, the young adult Hispanic population showed no significant change at the high school level and no significant change at the bachelor’s or more level (Newburger and Curry 2000). Spatial assimilation of Hispanics also seems to be limited in the US context. As William Frey points out, there is a demographic divide between cities in the United States that are magnets for
17
Only 49.7% of Hispanics of Mexican origin have completed high school or more.
57
58 immigrants on the one hand and the destinations of domestic migrants on the other (Frey 1999). Figures produced from the 1999 CPS show that the foreign-born are twice as likely to live in urban areas, and are concentrated in the West (39.3% of all foreign-born) and South (26.5%). The top two intended destinations for legal migrants in 1996, as reported by the immigration and Naturalization Service, were: California, with 201,529 legal migrants of whom more than 25% settled in Los Angeles; and New York, with 154,095 legal migrant, almost all of whom were within New York City (INS 1997). More telling perhaps is that 40% of the estimated 5 million undocumented migrants in the United States are concentrated in California (INS 1999) Frey has called the urban-rural, regional, and racial/ethnic divisions the demographic “Balkanization of America” fueled by immigration from Latin-American and Asia. Arizona historically has been a state with high numbers of Hispanics. While Arizona is only the seventeenth most common destination of all legal migrants, it is the seventh most frequent destination among undocumented migrants (INS 1997 and 1999). Approximately 22.1% of the estimated 4,778,332 Arizona residents are Hispanic, compared to 11.2% nationally (US Census Bureau 2000) and 1998 estimates place the Hispanic population of Maricopa County at approximately 20%. In the Phoenix area, the spatial divide that Frey spoke of in is clearly evident in a map of census tracts with percentage Hispanics [Figure 5]. Hispanics can be seen as concentrated in pockets within the southern and western portions of the city.
18
Though this averaged figure does not reflect clearly the gendered aspect of labor force participation: Hispanic men participate at a rate 4.1% higher than non-Hispanic white men, while Hispanic women work outside of the home at a rate 4.5% lower than non-Hispanic white women
58
59 Figure 5 – Percent Hispanic in the Phoenix Area
Mexican Migrants in the Phoenix Area The sampling technique yielded a group of 16 males and 12 females from 15 sending communities throughout Mexico. Best represented were migrants from Mexico City (35.7%) and Oaxaca (14.3%). The ages of migrants ranged from 17 to 61 with a mean of 31 years. Educational attainment also was quite broad with respondents having from none to 18 years of education. Mean education was 10.4 years and illustrates the selection bias introduced in the snowball sample, as well as the youthfulness of this sample (85% were under 35 years old). This was the first trip to the United States for 50% of the sample, while one respondent had made more than 40 trips (though 59
60 this respondent was born in Ciudad Juarez). The mean was 4.1 trips, however when the one border resident was omitted the mean number of circulations dropped to 2.4 trips. 82.1% (23 respondents) were undocumented, 14.3% (4) had permanent residence and only one had acquired US citizenship. Respondents were identified as being members of the core network, the church group network, or non-network individuals for purposes of analysis of social ties in the United States. Although similar in some demographic respects to the migrants interviewed by the Mexican Migration Project, this survey interviewed both males and females in almost equal proportions. This was due in part to the sampling technique (rather than using head-of-households, all Mexican migrants were included) and to the desire to understand the nature of symbolic ties as they differed by gender. This works, however, to the exclusion of single male labor migrants as they are less likely to be integrated into the networks captured in the sample, more likely to circulate and less likely to permanently settle in the United States.
60
61 The Migration Experience Motivation for Migration and Plans for Settlement, Circulation and Return The respondents expressed various reasons for coming to the United States, yet the predominate trends fit into two general classifications: labor migration and family unity. These categories are not mutually exclusive as many respondents expressed economic and familial motivations for migrating. These classifications are, though, reflective of the gender of the respondents. A majority of male migrants stressed economic factors when discussing reasons for migrating, while most of the females came either as the spouse of the male labor migrant or in attempt to improve the living conditions of their children. Miguel, for example, has only been in the United States for eleven months. He is single, twenty-two and from a small town in Guerrero State in Southern Mexico. Miguel has a high school education and a certificate from a vocational school in heating and air-conditioning repair. Miguel has perhaps among the clearest plans, which fit into Landolt’s classification of a return migrant micro-enterprise (Landolt et al. 1999). He is saving approximately $400 a month, of his $950 income at a junkyard where he works with his cousin disassembling automobiles, to complete his plans: I have some friends who are working there [Virginia]. They have been my friends since I was very little. They are living there… I think they are working in construction… They invited me to come and I said okay. But, when I got here [Phoenix], my aunt said “No. It is too far.” So, I stayed here with them and, well, here I am… I am saving to buy equipment to send to Mexico. Since I’m a professional [heating and air conditioning repair] I want to build my own shop. So, after a time I will return to work there in my own shop… I have the plan of another three years. It is possible that it would be a little more or a little less depending… In addition to his aunt and cousins living in Phoenix, his father and two uncles live in California near Los Angeles. He says his father and his father’s brothers all came to the United States over six years
61
62 ago to find work. His mother, four brothers and sisters, as well as the rest of his extended family, still live in various cities in Mexico. Hector, on the other hand, is a thirty-one year old father of two who brought his wife and children with him to the United States. He is from Mexico City, has a high school education, and has been in Phoenix working at a car wash for the past two years. He came here following his brother who migrated to the area in 1994. As he explains, he had to sever many symbolic and social ties in making his primarily economic decision to move: I come from Mexico. Right? I had to leave my homeland, my city, and my parents. Right? I had to leave them, because my economic situation there in Mexico was a little difficult and I had to leave that place so that I could come here...Right. To leave all these things, in my case to better my living condition and to be here with my wife and children. Raquel is a good example of a migrant who came only to be with her family. She is a fiftytwo year old homemaker who has never worked in the United States. Though she now has permanent residence status, she initially came without documentation. As she explains, the decision to come here had only to do with reuniting with her oldest son and husband who were working in the United States: For a mother, the first thing is her son. And for me, I wasn’t interested in anything. Nothing, nothing, interested me [about coming here] because of the process that I had to go through. And even as I was bringing a daughter, three daughters, because I was bringing the youngest. But I wasn’t interested [didn’t care], because he [Son in US] came with papers, and he had left us. But, I said, I think every day ...God, do you know, do you know, what pain I carry now in my heart. And you will get us past [the border] God, because I want for you to help us pass. And asking God and asking God, and it was something completely unknown to me. Nothing, even if I had wanted to, could I have imagined. I never imagined anything. I can tell you I never imagined things that were really beautiful… what I imagined was the worst. Because he [son in US] had told me ‘you won’t be able to even go out in the street. And where would you go’ because he didn’t want for me to carry money. [Recounting conversation with son] ‘That’s how it will be. That’s how it will be.’ ‘Me with my son and 62
63 that’s it.’ ‘Through the window is all you will see out. Do you still want to go?’ ‘Even so, I still want to go. I want to go to you.’ Only the simple thing of seeing my son. Only this. Guille, on the other hand, is a thirty-two year old housecleaner who completed college in Mexico by periodically working in the United States to save funds. She also exemplifies this love of a mother for her child. However, her motivation was to make it easier for her daughter to work in the United States in some distant future and to provide some capital for a more comfortable life in Mexico. Guille had no plan to stay in the United States, though she has now been here for almost three years, and still plans to return to Mexico within the next year. Well, I’ve always wanted the best for my family and in this case I said to myself if one doesn’t have too many problems here [US]…if there is enough desire, one can rise very quickly. Earning what one wants. I noticed [in her previous trip], that without papers it is very difficult. Very difficult, but equally as possible. So, I said to my self, I want for my children to be born here, so that they won’t have the same problems that I had, because if one day they want to come here… I want for them to be raised in Mexico, educated in Mexico , because I think the education there is a little better. So I said to myself, well, I want my child to be born here, and I said to my husband, ‘you know here [Mexico], we don’t have a house’ we have to live with his parents and family members, ‘I want my house, my own car, everything. And, I want for my baby to be born there [US].’ And he said, ‘well, go and as soon as she is born we’ll come back.’ But, no, I came much before him. He came almost when the baby was born. These four cases exemplify the trend within this local sample in differences of motivation for migration based on gender. Both Hector and Miguel demonstrate the more predominately male motivation to take advantage of the wage differential between the United States and Mexico. Raquel and Guille express the more female rationale of family unification and need to provide for their children. This is not to say that family unity was not important for males and economic motivations were not influential for females. Hector, though he initially expresses his motives in economic terms, does articulate the need to preserve family cohesiveness. Likewise, Guille, though her intent was to 63
64 provide her child with the legal privileges of American citizenship, is motivated by the wage differential to work in the United States for a time before returning to Mexico. Plans for return varied greatly throughout the sample. Reflecting the findings of the previous analysis of the Mexican Migration Project, respondents were found to be a different points along their migration trajectories of settlement, continual circulation, or eventual return migration and permanent re-settlement in Mexico. Their individual plans varied by gender, age, documentation status and motivation and were found to be as unspecified as Andres, a 17 years old hotel custodian, who said, “I would like to return in three or four years to my country...” or as specific as Maribel, a 34 dishwasher, who explains, “I have always planned to return… I will go home in December [six months hence]… I’ll go back by land, using the same system. We can’t go any other way….” Juan is single, twenty-five, and has been working as an inspector in a factory that fabricates parts for aircraft for one and a half years. He came to the United States five years ago from Acapulco, Mexico. Before coming to the United States he had completed his first year of law school, owned a car, and had a job in his father’s company. While in school one of his friend invited him to come to the United States. He contacted his older brother, who was then living in Texas, and decided he would give it a try. He explains, though, that he is torn between settlement and return:
Juan: My plan right now is to save, save, for tomorrow so that I may buy a house. It’s that I don’t know… Interviewer: Here in the US? Juan: Here in the United States. Frankly, I am thinking, I’m in a situation in my life where I don’t know where to stay. My father needs for me to go there to…, you know he’s a little tired and needs someone to help out. My brother is there, but my brother doesn’t like this business… and he [father] says I would like for you to come and advance this business, take it forwards. For this reason I am undecided to stay here or go there. Do you understand? But, I don’t know, I don’t know really what kind of life I would have here. I don’t know, because 64
65 what I have seen and what I have been assimilating and thinking about in my future, I think I would be doing the same thing [work]. Do you understand? How long is it going to be before I have papers. Am I going to keep on being illegal for ten more years? It’s going to be the same. Still at the same factory. And there I could be the boss because my father is the owner of the business. I can be the boss, I could order, I could pay, it would be different… Interviewer: And without papers here? Juan: And without papers, exactly. [There] I would be speaking my own language. Do you understand? I’d have a better life there because my mother is there and my brothers [siblings]. But, I also have to consider that here I can have my own life. Do you understand? But, I don’t know. The truth is that I think it will be ok here. I think it will be ok because the situation in Mexico now is very difficult. The economic crisis is very difficult. The truth is there are a lot of very poor people. Many people here in the North, on the border don’t have enough to even buy a gallon of milk. You know it. There are children who don’t have enough even to bathe, they don’t have clothes. It makes you think, to reflect, how can you return to that country? Here I’ve had opportunity. Juan is perhaps unlike most migrants. He comes from a relatively upper middle-class family, has had some college education, speaks English well and has found his way into a well-paying job. This economic success can be seen as the effect of his high degree of social and human capital, as well as his ambition. As he makes clear, “ I am a very secure person. I see something I want and I get because I believe I can.” Yet, like others, he feels the pull of familial obligation and the push of an uncertain future without legal status in the United States. Hector also is undecided, but very pragmatic about settlement. Unlike Juan, he has a wife and children here. He sees these family ties to the United States as well as his economic ties (income and expenses) as fortifying his US ties: I don’t know. I don’t have plans right now. I don’t think I will be able to return...I feel a little firmer here now. More firm [stable] in being here. Because, it is like, there are two things here. When a person doesn’t have family here. When all their family is in Mexico, this person has the probability of returning because there he has his family, his children, he has to be sending money there so his family can survive there. And I don’t. I don’t because I have my family here. I have my wife, my children. I am here incurring expenses like paying for rent, and light, and the telephone, and things that one needs to buy. I have to buy gasoline. They 65
66 are thing that everyone has to buy. But they are expenses that I have here in the US. And it would be better if I could have the same quality in Mexico. I miss the family [relatives] and I care for them a lot because they are my family. But I am a big person and here I have my wife and I have to look out for my children. I have to watch out for them now…. Hector’s brother, Raul, is a married thirty-four year old with some vocational training. He too is here with his wife and children. In his narrative, he discusses the nature of the transnational labor circuit and how he and his family have made the symbolic transformation of orientation from a mentality of return to one of settlement: Raul: A Mexican who comes here to US many, many times, many times he comes here, of course, to work. To save up money, and that’s it. Right? But, I think there is something more, there is something more. Because, simply if we take notice that many times if a Mexican comes here to work, he works, he saves money and returns to our country until the money runs out then anew he returns here to earn more money and return again. It is like something in our thinking is not right… we have to decide if we want to stay here or there, right? For me it is like saying were going to go there, and then make a change and continue on. And for me, when I came here for the first time and became familiar with this place, I said this is good for my family and me and we can try to open a store. Interviewer: So you do not plan to return? Raul: No, no I don’t think of returning. I plan to stay here. In contrast, Alan (Guille’s husband), who like Juan has some college education in Mexico but came to assist his wife while she was having her child, finds that his time here has altered his plans. His original intent to simply have the child (so that she would have legal status in the United States) and then return was not as easy to complete as expected. He has found that as he has expanded his experience of the world to a more international level (he now reads Japanese comics in Spanish on the internet), he wants more than to simply return to a life in Mexico: … I do want to return to finish school because here [school is] very expensive, very expensive, very difficult... In my life here, I'm trying to give the best effort I can to together 66
67 enough money to return someday. But, I would also like to travel and have another child, she (points to wife) would like another child, but I would like to go in see other places. England maybe. I know it's really far away. So I want to be here, but also want to return. Paulina, a twenty-eight year old mother of three who works evenings cleaning offices, originally came to the Phoenix area to be with her consensual union partner. However, when they separated several years ago (after he physically abused her) she remained. She expresses her desire to return, but is economically unable: I would like to return there, but in what form would I be able to maintain my children? There is no work. And if there is work it only pays 35 pesos [about $3 US] a day. With this, one can’t eat. A kilo of beans is ten pesos, and tortillas are six pesos. Do you believe there would be enough to feed my children? With three children? It is difficult… My plans for the future are to help my children as much as possible so that they may have a career here, so that they are not like us [Mexican migrants]. More than anything I want, not that they earn more or anything, but that they will be respected. It is not important that they will be Chicanos, but that they will be respected. And that they will feel this because they will be able to say I am this and I have a career. Not like me being a janitor… Her concern for her children outweighs her own personal desires to return. In this case, the obligation of providing for children in the United States is the driving motivation for settlement. The most she hopes for is a general amnesty that will allow her to find work more easily. She says, “for myself, I want no more than to look for more work so I can keep up, so that they [children] don’t go without the indispensable things…If God allows, I will try to get a visa.” Thus, while the initial motivation to migrate to the United States may have been for purposes of personal economic improvement or family unification, these plans are often altered by new opportunities and experiences in the receiving context. In all, there were eighteen respondents who expressed some plan to return eventually, while nine said they would never go back to Mexico (one was completely undecided). Plans did range from an intangible “someday” or “ when I retire” 67
68 to “in two months.” Yet, as Belinda Reyes indicates in her report on return migration to Mexico, factors such as labor market participation, documentation status, transferable human and social capital, and characteristics of the receiving location have great influence in determining the probability of return (Reyes 1997). These structural influences are perhaps stronger ultimately than the migrant’s intent to settle or return. Nonetheless, these plans for settlement or return do indicate a general orientation of symbolic ties and a personal commitment to the United States, Mexico, or both countries.
Experiences in the Receiving Context The respondents have had varied experiences in the receiving context from little or no difference in the quality of their lives to many hardships including lack of hospitality by the majority culture, lack of financial or social support, and outright racism. Leticia, for example, sees little change in the quality of her life. As a homemaker, she is not directly confronted with cultural differences. She says, “If I am here, I am here. If I go there, I am there. There is no difference except to be on the other side [of the border].” However, more often were indications of a diminished satisfaction with their personal lives in trade for better economic prospects. Andres (who has been here for only a few months), Alan (here for more than a year), and Rosa (with more than thirty-five years as a US resident, but only recently moved to Phoenix) all found the local context lacking in sociability and have experienced racial discrimination: Andres - I am from Mexico and in the land of 'gringos,' I still feel Mexican and don't let go of my customs even though I am in another country.... Well, I think it is difficult because for Mexicans... sometimes we spend a lot of energy in our work because it is very difficult here and there isn't a lot of support for us. Sometimes there is a lot of racism, racism toward us Mexicans…. 68
69 Alan - Well, it is very difficult [being Mexican in the US] because you must break with all of your social group. You really feel different. One can't feel as if you are truly North American because you just aren't. And, he really can't feel Mexican either because you are not within your circle. It's very difficult for me. I try to act like what I see. Do you understand ? But, it takes a lot of effort.... For me, well, here people don't like to chat a lot, people don't like to live together. For this reason, I try not to bother them too much when it isn't necessary. In Mexico you can go up to any house and they will receive you, and talk with you, and embrace you... here no. Rosa - It is hard. Very hard. For a Mexican, there is discrimination… In El Paso there wasn’t as much as here. I have traveled a little in the US, and the discrimination that I saw was most in Nashville and Dallas and here. It is very strong here…It has caused me a lot of trouble here at work. Even after a few months here… It is difficult, very difficult. Gregorio adds that some of the lack of hospitality is the result of legislation and a political environment on both sides of the border that has to date lacked support for peasants and workingclass Mexicans: For me personally it is a little sad because, it's to say, that the people here, la migra [INS], they don't want the Mexicans and don't even give the opportunity for amnesty, for example in the case of the amnesty before [1986]... I don't know why, maybe because of how we are, our demeanor… Possibly if the United States would help, and also if Mexicans would unite, it is possible that it would get better, that there would be more force for Fox [recently elected president of Mexico]. But he alone as president can't do it. But we don't know, we hope that he'll work... This perception of the receiving context as inhospitable may act to strengthen bonds between co-nationals as a survival strategy. Likewise, strengthened solidarity as the result of common adversity has the effect of helping to define a community as a unique group. This community, with its strengthened sense of common identity, will then engage in the production and preservation of the home culture (see ‘ethnic resiliency’ in Portes and Rambaut 1990). At this point, a transnational community emerges in the sense of a “collective representations” with symbolic ties of common language, cultural practices, religion, nationality, and ethnicity (Faist 2000b). 69
70
Social and Family Ties Ties to Mexico As previously expressed by several of the respondents, migration involves a departure from the home community and a separation from one’s social and family ties. All respondents had extended family in Mexico and three respondents, all involved in transnational labor circulation, have a spouse and children still in the home country [See Appendix C]. Moreover, only two respondents, of the twenty-eight, have no close social ties (as measured by immediate family or closest friends) in Mexico. When social ties were explored in the interviews, the theme of longing to be with the family and friends, coupled with an inability to return due to economic circumstances, emerged. Gregorio (33, married, prep-cook in a restaurant), Andres (17, single, hotel custodian), and Maribel (34, married, dishwasher) all expressed similar views: Gregorio - …in my case I am the oldest in the family and I never thought I would be so far from my family. And, in reality, when I think about it, I feel strange like, how can I say it, like I'd want to return. But, one can't do that. Perhaps because of pride, or because returning is expensive. [One must] try and save [the amount of money] you have focused on, focused on like your fixed goal. Andres - Well, the emotional connection is somewhat that of dissatisfaction because we are not together with our families and with our friends that are in another country and we can't see them…. Here, well, we make more money and all, but our friendships and family are in another country and there are times when one feels very sad being here and out of one's country. Maribel - It is difficult. It is difficult because we are so far from our loved ones. For this it is very difficult. It is beautiful because here one works here so one can send money there. It benefits them a lot. Horrible is our money [Mexico]. One sends money and they exchange it. On that side they are content because one is here working but it is also sad…. 70
71 Jorge, a single twenty year old working as a carpenter, adds that it is not only an economic issue, but also one of the increased difficulties in border crossing: “It is a little difficult, being here and the family there. Of course, one feels sad. And I am here for some time without seeing them, and can’t go there… you know the problem of not going there without the problem of coming back. With improvements and reduced costs in international communications technologies, many of the respondents continue to maintain ties while abroad, even if they cannot visit. Table 10 shows the frequency and method of contact with relatives and friends in Mexico. Twenty-three (82%) interviewees in the sample are in touch on a monthly basis, with relatives or friends, by either telephone or letters (note that only two respondents used the internet to contact friends in Mexico). Telephone was the preferred means of contact, and the growing availability of inexpensive prepaid telephone cards was evident as twenty-two respondents used them to pay for calls.
71
72 Table 10 –Frequency and Method of Social Ties with Homeland
Name Gender Male Male Male Male Female Male Female Male Male Female Male Male Male Male Male Female Female Female Female Female Male Female Female Male Male Male Female Female Frequency Call Monthly 2-3 times week 2-4 times year Monthly Monthly Never Weekly 2-3 time month 2-3 time month 2-3 time month 2-4 times year < Once year Monthly Monthly Weekly Monthly Weekly 2-3 time month 2-3 times week > 3 times week Monthly 2-3 times week Monthly Monthly 2-3 time month Monthly Never 2-4 times year Whom Call Relatives Friends/ Relatives Relatives Relatives Relatives N/A Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Relatives Spouse/ Relatives Relatives N/A Friends/ Relatives Frequency Write Monthly < Once year Never < Once year < Once year < Once year 8-10 time year < Once year < Once year 2-4 times year 5-7 times year Never Monthly 5-7 times year Never 2-3 time month 2-4 times year < Once year < Once year Monthly Never Never < Once year < Once year < Once year Never Never 2-3 time month Whom Write Friends Relatives N/A Friends/ Relatives Relatives Relatives Friends/ Relatives Relatives Relatives Friends/ Relatives Relatives N/A Friends/ Relatives Relatives N/A Relatives Friends Relatives Relatives Friends/ Relatives N/A N/A Relatives Relatives Relatives N/A N/A Friends/ Relatives
72
73 Ties to the United States All of the respondents showed strong family and social ties in the United States. This may be due to the nature of the sampling procedure, as most respondents were found by referrals of friends and family members. All of the respondents, therefore, had some close social or family tie in the United States (though not always in the Phoenix area). Thirteen of sixteen married migrants (81%) were accompanied by their spouse, a rate that is much higher than that of the findings of the Mexican Migration Project. This may be a result of the network sample or a change in migration pattern as migrants move toward settlement rather than circulation. Of the respondents only two had no immediate family ties in the United States: Gregorio, whose wife, children and other family members remain in Mexico while he works here sending 40% of his earnings home; and Refugio, who also has a wife, children and family in Mexico and sends more than 60% of his income to Mexico. Both men are examples of the traditional labor circuit, relying on social contacts in the United States (they each have close friends from their hometown here in Phoenix) to provide job referrals, shared housing, and other resources. Both have made multiple trips (Refugio has been here six times and Gregorio three), circulating between homeland and employment opportunities in the United States. Both have plans to return to Mexico. Alternatively, migrants who were most integrated and assimilated into US culture were found to be distinct from others. Francisco, for example, is a twenty three year old university student originally from a town in Chihuahua, Mexico. His family moved to New Mexico when he was a baby, but only stayed for two years. They returned, permanently, about sixteen or seventeen years ago. He was granted permanent residence status four years ago after the family applied for the general amnesty. His youngest two siblings (out of five) are citizens as they were born here. Francisco’s extended family on the paternal side live mostly in the United States (Arizona, New 73
74 Mexico and Texas), while most of his mother’s family lives in Mexico. He is only infrequently in contact with these relatives. He is, however, an active member of various social and recreational groups in the United States. These groups include a softball team, a racquetball club, a Hispanic rights group, and a local business association for students, etc. in addition to his church youth group and choir. Thus he demonstrates strong social and family ties to the United States and weak ties to his home country. Francisco characterizes his identity as being pan-Hispanic. He points out: “I don’t really label anyone Chicano or Mexican, I see myself as a person, I see every person of Hispanic background, of Latino background, as one people even though they’ve been here for a long time. It’s like an extended family….” He does say that he has a different relationship with his friends who are of Hispanic background than with his Anglo friends, but points out that it is more a matter of language and culture. Interestingly, though as a Mexican migrant who has lived here for most of his life, he says his identification as a Mexican or as a Chicano is dependent upon his social situation: “I believe I have no real identification... I am able to adapt, from Latino to Hispanic to Mexican-American, depending on the situation and who are the people I am talking to. Actually, I have been able to take on all of those identities.” This practice of shifting between identities has been noted in the literature (for example Glick Schiller and Fouron 1999) and is especially important in our understanding of transnational fields as one strategy for negotiating a culturally pluralistic environment. Francisco also associates frequently with Anglos and to a lesser degree Asian American. His position as a student worker puts him in contact with many people and he has formed friendships beyond the Hispanic community. He describes the frequency of his associations as approximately 50% with Hispanics, 30% with non-Hispanic Whites, and about 20% with Asians. All of his friends, 74
75 he says, live in the United States either in Phoenix or in California and Texas. He only has indirect contact, through family members, with extended family in Mexico. As he moved here at a very young age, he has no friends who reside in Mexico. Diversity of ethnic ties was used in the earlier analysis as a measure of acculturation. Following assimilation theory (Gordon 1964, as cited in Alba and Nee 1997; Clark 1998), social boundaries begin to break down following economic and spatial assimilation. While Francisco is exemplary of this assimilation pattern (he lives in a primarily Anglo neighborhood, attends university, and has a diversity of social ties), it was found that on the whole migrants in this sample had very little association with other Table 11 – Ethnic Diversity of Social Ties in US
Racial/ Ethnic Group Has friends/ Good relations 3 7 10 10 14 No friends/ Neutral 24 21 18 15 14 Poor relations
African-American Asian Latino (non-Mexican) Chicano Non-Hispanic White
1 0 0 3 0
ethnic groups, especially Asians and African-Americans [Table 11].19 There was only slightly more association with non-Mexican Latinos and Chicanos. Moreover, the most association beyond coethnics occurred with non-Hispanic Whites. However, as Hector indicates, whom one defines as a friend is a bit problematic: Well, in the car wash where I work there are two people [Chicanos] there, two people, with whom I get along well. Like co-workers, we get along well. No, I don’t have any problem with them…It is difficult to say really who a friend is though. You might introduce someone as ‘this is my friend.’ But, there are so many things that really defines one as a friend….
19
This may be reflective of the fact that only 2.4% of Maricopa County residents (which includes greater Phoenix metro area) are Asian and only 4.2% African-American (US Census Bureau 2000).
75
76 There were several reports of problems between ethnic groups, primarily with Chicanos. The perception (however erroneous) among several of the respondents was that many Chicanos are involved in criminal activities or have a sense of superiority over Mexican immigrants. Refugio explains why he does not associate with Chicanos: I haven’t had much to do with Chicanos. In reality they are a little bit problematic in some occasions. I’ve tried to distance myself a little from them so that I wouldn’t have any problems with them. So, now I practically have no problems with them…there are problems like they are associated with crimes, and if you are with them you might be associated with this type of person and have a problem. The strongest response was from Juan. With a disdainful expression and passionate tone, he explained his viewpoint slipping back and forth between English and Spanish: Interviewer: What kind of relationship do you have with Chicanos? Juan: None! None! The truth is they don’t sit well with me. The truth is they don’t sit well with me, because I have the idea that, I have the idea, well not all are the same, but I have a very different idea than they do. They know that their families are from Mexico. That they were illegal. But, they were born here and they feel very big, very big like they are more than you are even though the face is the same. It is completely a Mexican [face]. But they say ‘I’m born here. I’m from the United States. I’m an American Citizen.’ I know that you are born here but ‘look at your face bro’ you’re like me.’ So, you don’t have to be like that if you are Mexican. Look at your father. For this reason I don’t have any relations with… Interviewer: So, you don’t have any Chicano friends. Juan: The truth is, no… In conclusion, the migrants in this sample were found to have family and social ties in both Mexico and the United States. The ties, especially to family in the homeland, were maintained with varying but regular frequency. While ties to Mexican family and friends usually were equated with a sense of longing or sadness at having to be apart, the economic and legal structures of the migration 76
77 process limit the migrants in their ability to return or to circulate. Ties in the United States were strongest with family and co-ethnic friends from the homeland. With few exceptions, there was little diversity of ties other than necessary contact with co-workers and employers. Whereas most informal associations were with co-nationals, differences between US born and foreign-born coethnics were especially apparent.
77
78 Table 12 – Economic Ties Name Gender Monthly Remittance as % of Income Monthly US Income Monthly Owns Vehicle in US US Rent Male Male Male Male Female Male Female Male Male Female Male Male Male Male Male Female Female Female Female Female Male Female Female Male Male Male Female Female 1% 25% 0% 50% 0% 0% 8% 40% 0% 5% 0% 9%* 0% 44% 0% 2%** 0% 0% 60% 5% 11% 0% 0% 0% 63% 0% 0% 0% $2500 $800 $2000 $1500 $200 $300 $1200 $1000 $1200 $1000 $900 $1600 $0 $900 $1500 $0 $0 $0 $920 $500 $950 $500 $0 $2200 $1600 $1800 $400 $1500 $150 $100 $0 $200 $600 $70 $300 $127 $600 $150 $600 $500 $0 $200 $400 $600 $0*** $0 $150 $0 $100 $184 $0 $605 $100 $570 $440 $300 Yes No No No No Yes Yes Yes No Yes Yes Yes Yes Yes No No No No No No No Yes No Yes No Yes Yes Yes Yes No Yes No No No No No No Yes Yes Yes No No Yes No No Yes No No No No Yes No No No No No US Bank Account
* Remittance was reported by wife Raquel, but income is made by Javier. ** Leticia is a homemaker, but sends approximately 2% of her husband’s earnings. He was not interviewed. *** Recently broke her arm and is unable to work. She is living with friends from hometown and hopes to return to work soon.
78
79 Economic Ties Economic ties to the United States were by far the strongest bonds preventing some who would return to Mexico from doing so while helping to cement others to the receiving context. In several cases, individuals with strong familial and social ties in Mexico remain in the United States only to earn money to remit to the homeland. In contrast, those with weak social and familial ties to Mexico also had weak economic ties to their country and very low levels of remittances [Table 12]. Levels of remittance varied from zero to more than 60% of monthly earnings. In the cases of very high levels of remittance (40% of income or more), there is a correspondence with strong family ties and plans for eventual permanent return settlement in Mexico. Likewise, in cases of no remittance, only weak to medium family ties in Mexico. And in those few cases of strong family ties in Mexico, but no remittance, there is a lack of need for money to be sent from abroad. For example, Juan’s entire family lives in Mexico but he sends no money: “No, I don’t send money, the truth is my parents don’t need money. My father has a business in Mexico…and my mother sells clothing. She has her own store selling clothing. So, they don’t need anything from me. All that I make is for me.” Economic ties to the United States took the form of both income and expenses. As saw previously shown, in Hector’s case, expenses in the United States act to keep the migrant here longer or even permanently. Guille and Alan originally intended to return after the birth of their daughter and they had saved enough to return and have a home of their own. However, they have had to extend their trip after her car broke down and then they were forced to find a new apartment. These economic obstacles have delayed return as they had to start saving for a second time. Generally, economic ties were indicative of the larger structural influences of the migration system. Wage differentials and employment opportunities draw migrants to the United States, while 79
80 relative costs of circulation (both real and perceived) hold them here. Migrants with weak or no social and family ties in the United States, and strong economic ties to the home country, all had definite plans for eventual return. Likewise, there is a propensity for migrants, with many close family members residing in the United States, to settle in the United States regardless of the strength or direction of their economic ties.20
Symbolic Ties Transnational symbolic ties have been defined in the literature as public and private activities, which include: language use; popular cultural practices (such as sports, music, dance, arts, foods, and social customs); maintenance of norms and values; attentiveness to national media; and usage of cultural or national icons (for example, flags, emblems, portraits of national heroes, etc.) (Faist 2000b). Itzigsohn et al. have
Table 13 – Orientation of Cultural Practices
Name Alan Andres David Diego Fatima Francisco Graciela Gregorio Guicho Guille Hector Javier
20
Music Mexican Mexican Mexican Mexican Mexican Both Both Mexican Mexican Mexican Mexican ---
Radio US Mexican --Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican ---
TV US Both Mexican Both Mexican Both Both Mexican Mexican US Both Mexican
Movies US US Mexican US Mexican US US US US US US Mexican
Actors US US US US US --Mexican US US US Mexican Mexican
Food Mexican Mexican US Mexican Mexican Mexican Mexican Mexican --Mexican --Mexican
Restaurant US --Mexican Mexican US Both Both Mexican International US Both ---
Calling Card Mexican Both --Mexican Both ----Both Both Mexican --Mexican
Of the four migrants with weak economic ties in the US, all had very strong family and social ties holding them here.
80
81
Joel Jorge Juan Leticia Lucia Maria Maribel Martina Miguel Paulina Raquel Raul Refugio Rodolfo Rosa Roxana Mexican Mexican US Both Mexican --Mexican Mexican Mexican Mexican Mexican Both Mexican Mexican Both Both Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican US Mexican Both Both US Mexican Mexican Mexican Mexican Mexican Both Both US --Mexican Mexican US Both US US US US US Mexican --Mexican US US US US US US Both US Mexican US US US US Mexican --Mexican US Mexican --Mexican US --Both Both US Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican Mexican US Mexican Mexican Mexican Mexican US US --US US US US ----Mexican --US Both --Mexican US Both Mexican Mexican Both Both --Mexican Both Mexican Mexican Mexican --Mexican Both --Mexican
81
82 further delineated symbolic ties to “narrow” and “broad” transnational cultural practices (1999). In their study of Dominicans in the United States, they define narrow practices as those in which migrants participate in the production and preservation of homeland cultural practices while abroad. In turn, broad practices are those in which an individual identifies with the homeland, while participating in the cultural practices of the United States (Itzigsohn et al. 1999). In this survey, questions were asked regarding the migrant’s cultural practices, language use, use of icons, and nationalistic self-identification [see Appendix B for survey questions]. Individual responses were coded and then collapsed into the categories Spanish, English, both or Mexican, American, both (in the case of food the category - international – was also used) [Table 13]. Summative figures indicate that orientation of symbolic ties of the majority of individuals in the sample were toward both Mexico and the United States, indicating perhaps the existence of a transnational social space [Table 14]. On the extremes, were five individuals whose primary cultural ties were to the United States and five whose ties were oriented toward Mexico. This range of orientation indicates a continuum of cultural ties that, when considered together with economic and social ties may indicate a level of acculturation, isolation or participation in transnational fields. As Faist points out: Immigrant culture cannot be seen as baggage or a template, not as something to be figuratively packed and unpacked, uprooted (assimilationists) and transplanted (cultural pluralists). Instead, an analytical approach looks for structures of
Table 14 – Relative Orientation and Strength of Social, Economic and Symbolic Ties Male Mean language Use Spanish Only 7 Female Total 7 14 82
83 Mostly Spanish Both - More Spanish Both – Equal Usage English Only Relative Orientation of Symbolic Ties Mexico Both USA Relative Family and Social Ties – Mexico Weak Medium Strong Relative Strength of Homeland Ties Weak Medium Strong Relative Family and Social Ties - USA Weak Medium Strong Relative Economic Ties - Mexico Weak Medium Strong Relative Economic Ties - USA Weak Medium Strong TOTALS 5 3 1 0 2 14 0 2 12 2 3 13 0 3 12 1 9 1 2 1 0 15 16 2 2 1 0 3 9 0 3 8 1 1 8 3 1 8 3 6 3 2 4 3 5 12 7 5 2 0 5 25 0 5 20 3 4 21 3 4 20 4 15 4 4 5 3 20 28
83
84 meaning engendered by and expressed in private and public behaviours, images, institutions, and languages (Faist 2000b). As follow-up to the questions regarding cultural practices, respondents were asked to define, in their own terms, their personal sense of patriotism and national identity. Some respondents were initially confused by these concepts, perhaps as there is no one “Mexican” identity but rather many regional identities with few commonalities other than language and religion. Mexico is yet a country with few universal symbols, recognized landmarks, and unifying cultural traditions. Each region has had a separate history of conquest, numerous ethnic differences, distinct cultural practices, and even regional linguistic differentiation. Maribel, for example, points out that national identity is for her the culture of her region:
Identity for me is, well, for example our traditions in Oaxaca. We have many traditions. One of them is the third Monday of the month of July, in which we have a very big celebration. It is called ‘Third Monday’ and is celebrated all over the state of Oaxaca. It is a big festival. Within the state, there are dances and many things to do. There are other celebrations we have like Dia de los Muertos. It is the first of November, where all Oaxacans hold a very beautiful celebration. We celebrate death and the spirits of ancestors. We decorate a big table with many fruits, all the fruits, apples, avocados, nuts, and vases with yellow flowers. Later people prepare mole and tamales and frijoles because it is the tradition to eat tamales with mole. There are many festivals that are very beautiful. For example, there is Christmas. Christmas there is very beautiful with all of the six posadas reenacting the birth of the child God. One identifies with these celebrations…. Well, it is very beautiful there. Very beautiful….the traditions, the culture that they have. The way of working to improve and move ahead. They work there in crafts, this is their way of living. I like everything. I like it there a lot… Similarly, Refugio refers to his hometown also when explaining what it is to be Mexican: I am from Guanajuato, Mexico, this is my identity…there are many differences from one state to the next. The way of speaking, the way of living… there are even problems of how one state associates with another. We have different festivals… Even if I had legal status here in the US, I would still be Mexican… My emotion for my land is that it is where I was born and raised. I grew up learning the ways of my homeland. I am called by my homeland…. We [Mexicans] are always thinking in our country. We know that our country exists, but what we are doing here is for one’s individual benefit, to get ourselves ahead a 84
85 little… but we know we are living in two parts. We are working here so we will have an easier life in Mexico… This idea of working hard to create a better future emerges again in several other narratives. Paulina, for instance, believes it is part of the national character of Mexicans to work hard, but feels that it is the lack of opportunity to work hard that brings them here: Sincerely I believe that Mexicans are the hardest workers and the most sincere… also I think it is Machismo… For us women, we are very hard workers. Even though we have very little education because we don’t have the money to study, for this reason I am here cleaning buildings and there are those people working in the fields here in the US. People who work construction, they are doing work that can pay well, but for us [Mexicans] they don’t pay as well because we don’t have much education. You know that we can’t argue for more pay either because they would say “get out I have other workers…” For as much of a Mexican that I am, for as much a Mexican citizen that I am, there is nothing for me. This [US] is the country that gives me my food, it gives me more opportunities for everything, including for my children. In yet another case, Alan describes Mexicans as being sacrificing and suffering, but not necessarily hard working: “Being Mexican, for me, means, uh, well, we are a race that possibly is very sacrificing, maybe very suffering also. And, well many are advancing but it is very costly…. Well, um, I feel good being Mexican, but I feel that Mexicans, well, some of us, well many of us, are very flojos [lazy].” This perception may be shaped, in part, by the receiving context. The dominant society, in the border area especially, defines ‘Mexicaness’ as something less than equal to majority culture. With the recent debate over bilingual education21, growing acrimony toward undocumented migration, and increased restrictions on legal migrants, combined with much media coverage of the so-called ‘social problems’ associated with migration, the Southwest has become a less than receptive environment for the maintenance of narrow cultural practices and symbolic transnational ties. Rosa,
21
Measures passed in both California and now Arizona to eliminate bilingual education in favor of English immersion programs.
85
86 in fact says she has purposively discarded many of her cultural practices in an attempt to integrate more easily: I am Mexican. Firstly, I was born in Mexico and have family and ancestors in Mexico. My blood is Mexican…my language, more than anything my language… I have tried to get rid of Mexican traditions a little. If I compare myself with my mother and my sisters I am completely different… because, unfortunately, in my life it is better in the US than in Mexico and if we talk about culture only, Mexico is good and all, but for my children it was better in the US. In summary, symbolic ties are found in both daily cultural practices and in broader identification with a particular national group. In this sample, cultural practices were found to be oriented in a continuum from home country to receiving context, with a preponderance displaying orientation toward the popular cultures of both countries. On the other hand, personal identity for the migrant appears to be strongest for the native region of Mexico and as a reaction to the receiving context possibly as a result of reactive ethnicity (Portes and Rambaut 1990; Popkin 1999). Further investigation into the direction of cultural practices, personal identification and, perhaps more importantly, changes in norms and attitudes would be useful in gauging the shift from local to translocal and even transnational identities.
Transnational Social Fields The core group that emerged from the sample was comprised of twenty-one individuals that were connected in a web of formal and informal social ties and direct family bonds. There were three principle informants who independently contacted me and then provided referrals to other members in the network. Occupying a central spot in the network was a couple from Mexico City 86
87 (Guille and Alan) who each provided three contacts and was acquainted with the other two informants. In the analysis of network ties, a strong picture of transnational kinship groups becomes apparent from this core group [see Appendix D]. And, from the sub-group of Oaxacan migrants, who were known to each other in Mexico and live in the same apartment building (Maribel, Lucia, Gregorio, Andres, and Hector), an image of transnational circuits can be seen. An additional network of more formal ties was found from the informant in the local Catholic Church group (Francisco). Though unknown to one another in the home country, these five individuals represent the power of formal social groups to build a sense of community that transcends social and political boundaries. Individuals in this group included several immigrants with long-term legal status, as well as members who had arrived as little as six months prior with no documentation. As all of the members of this network were participants in the youth choir, a somewhat different picture of a transnational social space emerges. It is a space that tends to combine or blend Mexican and American cultures.
Transnational Kinship Groups Faist identifies transnational kinship groups as a form of social space that relies on reciprocity and the maintenance of social norms of providing for relatives. Faist contends that remittances are the primary example of this type of transnational social space (2000b). Just under half of the migrants remit earnings to the home country. However, reciprocity is also an element in the decision of migrants to choose a particular destination for settlement or even temporary migration. For instance, many of the migrants in this sample chose Phoenix because of family ties in
87
88 this area. In this context they would have a support network to aid them in housing, job referrals, and emotional support.22 Guille, who came to have her child here and then return, had been to the United States twice before. In deciding the destination for this trip, she chose not to return to California where she had been before, but to come to Phoenix where her sister has lived with her husband for the past four years. Likewise, Fatima, Raquel, Martina, Roxana, and Maria all came to be with their husbands, siblings and children. The men, too, chose their destination by presence of family members. Diego, Juan, Raul, Hector, Rodolfo, Andres, and Jorge all have siblings or other relatives in the Phoenix area. This trend clearly illustrates the nature of migration for purposes of family reunification and mutual support. In the cases of the women, however, it appears that migration to follow one’s spouse is a significant occurrence. In contrast, men, with perhaps the exception of Alan who followed his wife here, often come first to establish a residence and job before sending for their wives and children (see also Massey 1986, 1987; Massey et al. 1987).
Transnational Circuits Transnational circuits are identified by the mechanism of mutual exchange between peers. The sub-group of social network associations between Gregorio, Jorge, Lucia, and Maribel is a superb example of a transnational circuit. Each of the respondents was known to the others in their hometown Oaxaca, Mexico. Although several have other family members (siblings and cousins) in the United States, they chose to come to Phoenix because of these social ties. They share an apartment, split utilities and other expenses, have helped one another with job leads, and presently
22
This notion may be disputed in some cases. See Menjivar (2000) for the case of how these social support networks based on reciprocity hinder, rather than help Salvadoran migrants.
88
89 are all sharing in supporting Lucia who recently fractured her arm and is unable to work. These mutual obligations are clearly shared and responsibility falls equally on all parties. Importantly they also provide support for each other in more symbolic ways. As Maribel explains, they have relied on one another for emotional support as well as financial support: Precisely today, we are all from the same town [people in room], and today we feel a little sad because today is the festival of our town. So, we are all made to think about the festival and what we are missing - the fireworks, the foods, and everything - because we are not there… but also, we say it is good since they [our families] have received our earnings that we sent them. We do all we can to send it to them and so they would have it [money] for this festival. It is difficult, but on the contrary it is also good… there are various ways to look at it.
Transnational Communities Faist explains transnational communities as collectives that act in the preservation of symbolic ties to the homeland and creation of new transnational identities (Faist 2000b). Although many of the members of the core network are involved in the continuation of traditions and customs of their homeland, the respondents from the Church group were most clearly the strongest proponents of creation of a unified identity. Moreover, the identity that emerges in this particular collective is an amalgamation of US and Mexican elements. It is important to note that the Church group meets at a charismatic Catholic mission. The evangelical movement has been spreading throughout Latin America (as well as Asia and Africa) in the past few decades. Fueled by missionaries from the United States and the changing orientation of developing countries away from tradition and toward Western culture (possibly as a by-product of modern global capitalism), evangelical and charismatic movements are acquiring new followers at a significant rate. This movement within the Catholic Church may be viewed as a blending of cultures: 89
90 traditional Catholic doctrine of Latin American countries and a more ‘American’ evangelism growing out of Protestantism. Thus, the Catholic Renewal Mission creates a transcultural space within which participants may experience two worlds. The members within this network were all under thirty, had more than a secondary education, and most had at least some extended relatives in the area (the exception was Juan who had followed his friend here). They were equally divided between documented and undocumented and all of those who were undocumented were on their first and only trip to the United States [see Appendix E]. From the extremes that are represented within the group (Francisco and Miguel) a similarity in dual orientation of symbolic ties can be observed. While Francisco has been here for almost twenty years and has the strongest family and social ties to the United States, he also had strong symbolic ties to both Mexico and the United States. He is a fluent bilingual and prefers Mexican cultural practices in most cases. Nevertheless, as mention before, he does not restrict himself categorically to labels such as Latino, Mexican, Chicano, or Mexican-American. Similarly, Miguel, who has only been here for one year and has only weak family ties to the United States, was found also to have symbolic ties to both the United States and Mexico. He attends a community college program to improve his English skills, prefers US most entertainment and has many fiends at the church. However, Miguel plans to one day return and establish a business in Mexico and is saving to do so. While individuals within the group have varying levels of ties to the United States and Mexico, observations of the group during their weekly meetings generated a depiction of community creation of culture of a hybrid culture. The group meets a neighborhood ministry located in a long flat industrial building connected to a paint supply company and a Protestant evangelical revival 90
91 church. Unlike other light industrial use buildings in the area, the exterior is freshly painted, the small parking area is free of debris, and the walk in front to the building is freshly washed. The façade of the building is dominated by the image of the Virgin de Guadalupe a cultural icon clearly indicating ties to the homeland. On any given Friday, there are about a half dozen males and females who use keyboards, microphones, electric guitars, mixing board, drums, and all of the equipment typically associated with an American rock and roll band. Dress is casual, although robes might be worn on special occasions. The majority of the members of the group are Mexican born. Consequently, the predominate language is Spanish although there was some mixing with English (especially technical vocabulary regarding musical equipment). The members of the youth choir compose songs during choir practices that are reflective of their personal lives here and their religious expression. The music is upbeat, almost rock and roll, with Spanish lyrics and themes. They also are involved in creating decorations for the mission (often blending cultural and religious icons from Mexico with an American style of presentation), visiting other parochial missions, attending revivals, and going on informal outings. These solidarity-building activities produce a strong sense of identity as a member of a community with strong symbolic ties to the homeland, practical linkages with the United States, and blending of cultural practices of the two.
Conclusions In this study, social, economic, and most importantly symbolic ties are shown to be related to a continuum of outcomes from acculturation and isolation to membership in transnational social fields. Individual migrants are demonstrated as belonging to various social spaces depending upon such factors as: their motivation for migration; plans for return; presence of social and timely ties in 91
92 the local receiving context; involvement in preservation of cultural practices of the homeland; and activities which create new or hybrid culture. Migrants, whether as a reaction to racism, segregation, a lack of equal opportunities, or a longing for the mythical homeland, do maintain symbolic ties with Mexico, even when social and economic ties have been cut. Hypothesis Four stated that strong symbolic ties to the U.S. would result in greater acculturation. However, this premise is not been entirely supported by the Phoenix sample. While spatial, economic, educational and social integration with majority culture (assimilation) was observed in many cases, they did not preclude symbolic ties to the homeland. In fact, no migrants were observed to have an overall orientation of symbolic ties toward the United States. Even those who had spent considerable time in the receiving context (e.g. Rosa, Francisco, Refugio, Graciela) showed preference for cultural practices of the homeland or both sending and receiving contexts, but never for the United States alone. It is apparent that the age at which the migrant came to the United States and a number of years here are the greater determinants of assimilation as those most integrated into American life had been here for the longest time. As well, the receiving context may play an important role in the process of acculturation. In the Phoenix area, there are many resources for Mexican migrants that enable them to maintain symbolic as well as social ties to the homeland (Spanish language TV and radio, eateries, shopping centers, churches, etc). In another locale, which lacks any of these resources, migrants may be more inclined to adopt cultural practices of the majority. Hypothesis Five, in contrast, posited that strong symbolic ties to the homeland and weak ties to the United States would result in the least social integration into American society. This hypothesis is supported by the cases in the sample. Javier, Maria, Maribel, Martina and Rodolfo all have strong symbolic ties to Mexico. Although Javier (landscape gardener) and his wife Raquel 92
93 (homemaker) have settled in the United States and even raised their six children here, almost all of their cultural practices and preferences indicated unyielding symbolic ties to the homeland. Although Javier works outside the home, he remains isolated from American culture as he works entirely with other Mexicans and associates very little with individuals from other ethnic groups. Like Raquel, Maria and Martina are homemakers. Both followed their husbands and have no ties outside of the family. Thus, they are generally cut off from American cultural influences. Although both of their families live in racially integrated apartment complexes, they say, due to legal status and lack of English skills, that they stay to themselves. Martina in particular says she dislikes living here and wishes to return to her hometown in Sonora. She is held here by her husband’s job and the economic welfare of her two daughters. Maribel, who has four children who have been living with their grandmother in Oaxaca since their father disappeared, is here also for economic reasons. Her symbolic and social ties are all oriented toward Mexico and toward her hometown specifically. She has definite plans for return and no intention to settle here. These cases demonstrate that for a variety of reasons and under various conditions when symbolic ties are strongly in favor of the home country, the migrant will be socially and culturally isolated from the mainstream. Strongest perhaps is evidence in support of hypothesis six: strong symbolic ties to both the United States and Mexico will create a transnational social space where migrants may mix or blend cultural practices. The majority of migrants interviewed demonstrated dual symbolic ties: bilingualism, entertainment preferences from both countries, use of cultural icons from Mexico while residing in US, and other cultural practices that indicated a bifurcation of symbolic ties. More importantly, many of the respondents were actively involved in the maintenance of homeland culture and creation of hybrid transnational cultures. Beyond the example of those respondents from the church group sample, other hybrid cultural practices included: 93
94 Membership in a predominately Mexican Amway group (Raul and Hector). Active participation in Evangelical Christian Church groups (Fatima, Guille, Alan, Raquel). Membership in Movimiento Estudiantil Chicano de Aztlan (Francisco).23
These symbolic ties, especially when combined with social and familial bonds to Mexico, create transnational social fields in which migrants maintain connections to the homeland while living abroad. These transnational fields may take the forms of transnational kinship groups, transnational circuits or transnational communities and are maintained by the mechanisms of reciprocity, obligation, and solidarity. Moreover, these social fields are not unambiguous, discrete categories as individual migrants may belong to one or all of the categories. Equally, individual participation in transnational social fields are represented by a continuum of involvement as members have varied social and symbolic bonds to the United States and Mexico. Thus, the degree of embeddedness of the migrant in both cultures will determine their overall commitment to a transnational identity.
23
Aztlan Chicano Student Movement: A group that grew out of the Chicano rights movement of the late 1960s and is committed to the community, connection to culture and history of Mexican-Americans, and to aiding students in their educational progress.
94
PART FOUR - SUMMARY AND IMPLICATIONS
This thesis has combined the results of a general secondary data analysis of a large dataset collected for over ten years with a more qualitative study of individual Mexican migrants in a particular receiving locale. The intent of this triangulation of methods was to show a more comprehensive depiction of Mexican migration as it relates to the creation of transnational social spaces than is possible by either method of analysis alone. The statistical analyses established patterns of migration flows as they relate to social and economic ties in both countries. The results indicated that strong economic and social ties to the United States, in the absence of strong ties to the homeland, increased the odds for long-term legal status and overall duration of stay, indicative of a propensity for settlement. Conclusions regarding the results of the strength of homeland ties were less certain as few variables were found to be representative of economic and social ties to Mexico. However, the results did indicate that obligation to individuals left in the homeland (as measured by remittance) combined with strong economic or familial ties in the United States did increase the rate of circulation between countries. Nevertheless, it was determined that these results may have been true for the period in which the data was collected, but may not hold true as today’s border enforcement has increased the potential for long-term stay as the risks associated with border crossing have increased the relative cost of circulation. Clearly though, social and economic ties were shown to be statistically significant in these migration patterns. The local interviews provided abundant material on the nature of the migration process for particular Mexican migrants and insight into the relative power of social, family, economic and symbolic ties as they relate to the migrant’s decision to settle, circulate, or eventually return migrate.
96 Migrants, though found to have differing social and economic ties to the United States and having come here for various reasons, were all found to have some connection to the receiving context. Similarly, even those migrants who had the strongest bonds to the United States were found to have symbolic ties to the homeland. As predicted, migrants having strong ties to both homeland and the host country were involved in various transnational fields including transnational kinship groups, transnational circuits and transnational communities. Of these social fields, transnational communities are most important for the production of new or blended culture and require strong symbolic ties to the homeland. It is in this space that a genuine sense of transnational identity emerges and is sustained as a common product of migrant solidarity and unity. These findings are, however, preliminary and tentative as the non-representative snowball sample is quite small and limited to one geographic area. As a result, the nature of those migrants who have few social ties is unknown, as they are not reflected in the sample design. Similarly, comparison between receiving contexts would be beneficial as this research only reflects migrants to the Phoenix area. By repeating this study, preferably with a greater sample size, in various urban and rural locations throughout the United States, the effects of receiving context on acculturation, isolation and development of a transnational identity may be gauged. Additional investigation into participation of migrants in more formal social groups may also produce more information on the processes of the creation of a transnational identity. Though in need of further testing, this study does indicate a strong relationship between the strength of ties and transnational fields. By establishing the role of transnational ties in the migration process, this thesis has demonstrated the importance of familial, social and economic bonds in determining the migration trajectory of an individual. More importantly findings have supported the premise that strong symbolic ties to both the United States and Mexico, especially when combined 96
97 with other strong ties, creates a social milieu in which a community may from a transnational identity.
97
98 REFERENCES
Alba, Richard; Nee, Victor. 1997. “Rethinking assimilation theory for a new era of immigration,” International Migration Review. 31: 826-74. Bamyeh, Mohammed A. 1993. “Transnationalism” Current Sociology Trend Report. 41: 1-95. Biernacki, P. and Waldorf, D. 1981. “Snowball sampling: problems and techniques of chain-referral sampling,” Sociological Methods and Research 10:141-163. Brittingham, Angela. 2000. “The Foreign-Born population in the United States,” Current Population Reports March 1999. US Department of Commerce, Economics and Statistics Administration; US Census Bureau. Available online at: accessed November 2000. Cinel, Dino. 1991. The National Integration of Italian Return Migration, 1820-1929. New York: Cambridge University Press. Clark, William A.V. 1998. “Assimilation versus separation: Immigrants’ future trajectories.” California Cauldron: Immigration and the Fortunes of Local Communities. New York: The Guilford Press. Coffey, Amanda and Atkinson, Paul. 1996. Making Sense of Qualitative Data: Complimentary Research Strategies. Thousand Oaks: Sage Publications. Cohen, Robin ed. 1996. The Sociology of Migration. Brookfield: Edward Elgar Publishing . Faist, Thomas. 2000a. “Transnationalization in international migration: implications for the study of citizenship and culture.” Ethnic and Racial Studies. 23: 189-222. ---. 2000b. The Volume and Dynamics of International Migration and Transnational Social Spaces. London: Oxford University Press.
98
99 Frey, William H. 1999. “Immigration and Demographic Balkanization: Toward One America or Two?” in America’s Demographic Tapestry: Baseline for the New Millennium. edited by James W. Hughes and Joseph J. Seneca. New Brunswick: Rutgers University Press. Glick-Schiller, Nina and Georges E. Fouron. 1999. “Terrains of Blood and Nation: Haitian Transnational Social Fields.” Ethnic and Racial Studies. 22: 340-66. Guarnizo, Luis Eduardo; Arturo Ignacio Sanchez; and Elizabeth M. Roach. 1999. “Mistrust, Fragmented Solidarity, and Transnational Migration: Columbians in New York and Los Angeles.” Ethnic and Racial Studies. 22: 367-96. Immigration and Naturalization Service. 1997. Table 4. Immigrants Admitted By Major Category of Admission and State and Metropolitan Area of Intended Residence: Fiscal Year 1996. on line at: accessed November 2000. ---. 1999. Illegal Alien Resident Population. Online at: accessed November 2000. ---.1999. Annual Report. Office of Policy and Planning, Statistics Branch. Massey, Douglas S. 1986. “The Settlement Process Among Mexican Migrants to the United States,” American Sociological Review. 51: 670-84. ---. 1987. “Understanding Mexican Migration to the United States” American Journal of Sociology. 92: 1372-1403. ---. 1995. “The New Immigration and Ethnicity in the United States,” Population and Development Review. 21: 631-52. Massey, Douglas; Alarcón, Rafael; Durand, Jorge; and González, Humberto. 1987. Return to Aztlan: The Social Process of International Migration from Western Mexico. Berkeley: University of California Press.
99
100 Massey, Douglas; Arango, Joaquín; Hugo, Graeme; Kouaouci, Ali; Pellegrino, Adela; and Taylor, J. Edward. 1993. “Theories of International Migration: A Review and Appraisal,” Population and Development Review. 19: 431-66. Menjivar, Cecilia. 2000. Fragmented Ties: Salvadoran Immigrant Networks in America. Berkeley: University of California Press. Mexican Migration Project. 1999. Documentation of Data Files. Philadelphia: Population Studies Center, University of Pennsylvania. ---. 1999. MIGFILE. Philadelphia: Population Studies Center, University of Pennsylvania. ---. 1999. HOUSFILE. Philadelphia: Population Studies Center, University of Pennsylvania. Migration News. 1995. “U.S. Taiwanese Return to Homeland,” Migration News – Asia. Online at: accessed November 2000. Newburger, Eric C. and Andrea Curry. 2000. “Educational Attainment in the United States,” Current Population Reports March 1999. US Department of Commerce, Economics and Statistics Administration; US Census Bureau. Online at: accessed November 2000. Popkin, Erik. 1999. “Guatemalan Mayan Migration to Los Angeles: Constructing Transnational Linkages in the Context of the Settlement Process,” Ethnic and Racial Studies. 22: 267-89. Portes, Alejandro. 1984. “The Rise of Ethnicity: Determinants of Ethnic Perceptions Among Cuban Exiles in Miami,” American Sociological Review. 49: 383-97. ---. 1999. “Conclusion: Towards a new world – the origins and effects of transnational activities,” Ethnic and Racial Studies. 22: 463-77. Portes, Alejandro; Luis E. Guarnizo; and Patricia Landolt. 1999. “The study of transnationalism: pitfalls and promise of an emergent research field,” Ethnic and Racial Studies. 22: 217-37.
100
101 Portes, Alejandro and Rubén G. Rumbaut. 1990. Immigrant America: a portrait. Berkeley: University of California Press. Ramirez, Roberts R. 2000. “The Hispanic Population in the United States: Population Characteristics,” Current Population Reports March 1999. US Department of Commerce, Economics and Statistics Administration; US Census Bureau. Online at: accessed November 2000. Reyes, Belinda. 1997. Dynamics of Immigration: Return Migration to Western Mexico. San Francisco: Public Policy Institutes of California. Online at: accessed November 2000. Roberts, Bryan R., Reanne Frank, and Fernando Lorenzo-Ascencio. 1999. “Transnational Migrant Communities and Mexican Migration to the US.” Ethnic and Racial Studies 22: 238-66. Sassen, Saskia. 1994. Cities in a World Economy. Thousand Oaks: Pine Forge Press. ---. 1998. Globalization and Its Discontents. New York: The New Press. Schniedewind, Karen. 1993. “Migrant’s Returning to Bremen: Social Structure and Motivations, 1850 to 1914,” Journal of American Ethnic History. 12: 35-55. Skeldon, Ronald. 1990. Population Mobility in Developing Countries: A Reinterpretation. New York: Belhaven. ---.1996. “Migration from China,” Journal of International Affairs. 49: 434-55. Stark, Oded and David E. Bloom. 1985. “The New Economics of Labor Migration,” American Economic Review.75: 173-78. Stark, Oded and J. Edward Taylor. 1991. “Relative Deprivation and International Migration,” Demography. 26: 1-14.
101
102 Stalker, Peter. 1994. The Work of Strangers: A Survey of International Labour Migration. Geneva: International Labour Organization. Stillwell, John and Congdon, Peter eds. 1991. Migration Models: Macro and Micro Approaches. New York: Belhaven Press. Swinbanks, David. 1995. “Taiwan Welcoming Home Top Ph.D.s from U.S.” Research Technology Management. 38: U.S. Census Bureau: Population Projections Program, Population Division. 2000. Projections of the Resident Population by Race, Hispanic Origin, and Nativity: Middle Series, 2006 to 2010 - Publication NP-T5-C. ---. 2000. State and County QuickFacts Data derived from Population Estimates, 1990 Census of Population and Housing, Small Area Income and Poverty Estimates, County Business Patterns, 1997 Economic Census, Minority- and Women-Owned Business, Building Permits, Consolidated Federal Funds Report, 1997 Census of Governments accessed October, 2000. Online at: accessed November 2000.
U.S. Visa Association. 2000. Tips for Obtaining Visitors Visas- Business and Pleasure. Online at: accessed November 2000. Yang, Phillip Q. 1999. “Sojourners or Settlers: Post-1965 Chinese Immigrants,” Journal of Asian American Studies. 2: 61-91.
102
APPENDIX A - TEXT OF FLYER Busco Sujetos Para Entrevistas
Soy sociologo de la Universidad de la Universidad del Estado de Arizona (ASU). Hago estudios sobre la migracion Mecicano a los Estados Unidos. Busco sujetos para participar en algunas entrevistas para este estudio. Las entrevistas durarán alrededor de una hora y forman una parte de mi proyecto de tesis. Toda la informacion acerca los sujetos sera privada y no se utilizará para identificación. Si Ud. O alguien que le conconce es de Mexico y le gustaría participar en este estudio, porfavor llamame al numero telefonico abajo.
Gracias:
Stephen
104 APPENDIX B - VERBAL CONSENT SCRIPT Proyecto de Tesis: Depto. De Sociologia Communidades Transnacionales Aviso Verbal de Permiso Soy un estudiante graduado bajo la dirección del Professor Agadjanian en el Departamento de Sociología a la Universidad del Estado de Arizona. Estoy haciendo un informe sobre communidades migratorias transnacionales. Esta entrevista, que durará aproximadamente entre una hora y una hora y media, sera grabada. Las cintas solo se usarán mientras dure el estudio y serán destruídas al terminarse investigación. Su paraticipación es estrictamente voluntaria. Si UD. Decide no participar, pued dejar la entrevista en cualquier momento sin consecuencia. Es possible que los resultados de la investigación sean publicados, pero no usaré su nombre. Para proteger su privacidad, Ud. Pueda seleccionar un seudónimo que yo usaré en mis notas y publicaciónes. No hare referencia al lugar, nombre del grupo u organización a que pertenece, y los nombres de contactos que me provee en las notas de la investigación, ni en los ensayos o publicaciones. Si tiene alguna pregunta sobre este investigación, pueda llamar a mi (Stephen Sills) al número: XXX-XXX-XXXX, o al Profesor Agadjanian al número: XXX-XXX-XXXX (oficina del Depto. De Sociologia al ASU).
104
105 APPENDIX C - QUESTIONNAIRE Questionnaire for Interviews in Phoenix Area
105
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38.
Nombre que quiere usar por el estudio? Cual es su sexo? Cual es su fecha de nacimiento? Ciudad donde nacio Estado de nacimiento Pais donde nacio Estado civil Education (años) Direccion permanente/direccion ahora - Ciudad Direccion permanente/direccion ahora - Estado Documentacion Cuando vino al EEUU la primera vez (año)? Cuantas veces ha viajado a los EEUU (total)? Destino principal - la primera vez? Como llego (modo de transportacion) la primera vez? Documentacion - la primera vez? Paso con coyote - la primera vez? Cuanto pago al coyote - la primera vez? Quien pago - la primera vez? Con quien mas cruzo - la primera vez? Por donde entro - la primera vez? Describe la experiencia (la primera vez): Como consiguio documento - la primera vez? En base a? Occupacion - la primera vez? Salario por hora - la primera vez? Duracion del viaje - la primera vez? Cruces intentados sin lograr pasar - la primera vez? Le deportartaron? Describe la experiencia: Destino principal - la segunda vez? Como llego (modo de transportacion) la segunda vez? Documentacion - la segunda vez? Con quien cruzo - la segunda vez? Paso con coyote - la segunda vez? Cuanto pago al coyote - la segunda vez? Quien pago - la segunda vez? Por donde entro - la segunda vez?
39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77.
Describe la experiencia (la segunda vez): Como consiguio documento - la segunda vez? En base a? Occupacion - la segunda vez? Salario por hora - la segunda vez? Duracion del viaje - la segunda vez? Cruces intentados sin lograr pasar - la segunda vez? Le deportartaron? Describe la experiencia: Destino principal - la tercera vez? Como llego (modo de transportacion) la tercera vez? Documentacion - la tercera vez? Con quien cruzo - la tercera vez? Paso con coyote - la tercera vez? Cuanto pago al coyote - la tercera vez? Quien pago - la tercera vez? Por donde entro - la tercera vez? Describe la experiencia (la tercera vez): Como consiguio documento - la tercera vez? Occupacion - la tercera vez? Salario por hora - la tercera vez? Duracion del viaje - la tercera vez? Cruces intentados sin lograr pasar - la tercera vez? Le deportartaron? Describe la experiencia: Destino principal - la cuarta vez? Como llego (modo de transportacion) la cuarta vez? Documentacion - la cuarta vez? Con quien cruzo - la cuarta vez? Paso con coyote - la cuarta vez? Cuanto pago al coyote - la cuarta vez? Quien pago - la cuarta vez? Por donde entro - la cuarta vez? Occupacion - la cuarta vez? Salario por hora - la cuarta vez? Duracion del viaje - la cuarta vez? Cruces intentados sin lograr pasar - la cuarta vez? Le deportartaron? Destino principal - la quinta vez?
107 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. Como llego (modo de transportacion) la quinta vez? Documentacion - la quinta vez? Con quien cruzo - la quinta vez? Paso con coyote - la quinta vez? Cuanto pago al coyote - la quinta vez? Por donde entro - la quinta vez? Occupacion - la quinta vez? Salario por hora - la quinta vez? Duracion del viaje - la quinta vez? Cruces intentados sin lograr pasar - la quinta vez? Le deportartaron? Destino principal - la ultima vez? Como llego (modo de transportacion) la ultima vez? Documentacion - la ultima vez? Con quien cruzo - la ultima vez? Paso con coyote - la ultima vez? Cuanto pago al coyote - la ultima vez? Quien pago - la ultima vez? Quien pago - la ultima vez? Por donde entro - la ultima vez? Describe la experiencia (la ultima vez): Como consiguio documento - la ultima vez? En base a? Occupacion - la ultima vez? Salario por hora - la ultima vez? Duracion del viaje - la ultima vez? Cruces intentados sin lograr pasar - la ultima vez? Le deportartaron? Describe la experiencia: Cual es su occupacion principal? Tiene otro trabojo? Cual es su trabajo secundario? Como obtuvo su empleo? Cuanto le pagan por hora (trabajo principal)? Cuantas horas la semana trabaja (total)? Cuanto le gana mensual (total)? Cuantas meses al ano? Le pagan por cheque o con efectivo? Le descuentan seguridad social? 117. Le descuentan impuestos federales? 118. Cual es la raza o etnicidad del dueño del trabajo? 119. Cual es la raza o etnicidad de su supervisor? 120. Cuanto gasta al mes en renta? 121. Cuanto gasta al mes en alimentos? 122. Cuanto ahorra al mes? 123. En que piensa va a gastar ese dinero? 124. Tiene carro? 125. Cuanto le costo? 126. Cuanto le gasta seminal por petroleo y para mantenerlo? 127. Cuanto les manda al mes a los padres, parientes o familiares en Mexico? 128. Tiene Ud. cuenta bancaria en los EEUU? 129. Desde cuando? 130. Tiene Ud. tarjeta de credito de los EEUU? 131. Desde cuando? 132. Donde viven sus padres? 133. Donde viven sus abuelos? 134. Cuantos Hermanos tiene? 135. Donde vive hermano(a) #1? 136. Donde vive hermano(a) #2? 137. Donde vive hermano(a) #3? 138. Donde vive hermano(a) #4? 139. Donde vive hermano(a) #5? 140. Donde vive hermano(a) #6? 141. Donde vive hermano(a) #7? 142. Donde vive hermano(a) #8? 143. Donde vive hermano(a) #9? 144. Donde vive hermano(a) #10? 145. Donde vive la mayoria de los tios(as)? 146. Donde viven la mayoria de los primos(as)? 147. Viven algunas parientes en otras ciudades de los EEUU? 148. Quienes son y en cuales ciudades? 149. Con quien vive ahora? 150. Cuantas personas viven en su hogar? 151. De ellos quienes son relaciones suyos y de que relaccion? 107
108 152. Cuantos anos tiene el residente mas mayor en su hogar? 153. Cuantos anos tiene el residente mas menor en su hogar? 154. Tiene hijos? 155. Cuantos hijos tiene? 156. Cual es el edad de hijo #1? 157. Cual es el edad de hijo #2? 158. Cual es el edad de hijo #3? 159. Cual es el edad de hijo #4? 160. Cual es el edad de hijo #5? 161. Cual es el edad de hijo #6? 162. Cual es el edad de hijo #7? 163. Cual es el sexo de hijo #1? 164. Cual es el sexo de hijo #2? 165. Cual es el sexo de hijo #3? 166. Cual es el sexo de hijo #4? 167. Cual es el sexo de hijo #5? 168. Cual es el sexo de hijo #6? 169. Cual es el sexo de hijo #7? 170. Donde viven los hijos? 171. Con quien viven los hijos en Mexico? 172. Los hijos asisten la escuela en los EEUU? 173. Estan otros parientes (padres, tios, primos,etc.) quien vive en Phoenix? 174. Le acompañaron en su viaje? 175. Estan otros paisanos (del mismo pueblo/ciudad/etc) quien viven aqui en Phoenix? 176. Le acompanaron en el viaje? 177. De donde viene su #1 mejor amigo? 178. Donde vive el/ella ahora? 179. Con que frequencia reune con el #1 mejor amigo(a)? 180. De donde viene su #2 mejor amigo? 181. Donde vive el/ella ahora (#2)? 182. Con que frequencia reune con el #2 mejor amigo(a)? 183. De donde viene su #3 mejor amigo? 184. Donde vive el/ella ahora (#3)? 185. Con que frequencia reune con el #3 mejor amigo(a)? 186. Cuantas veces la semana habla por telefono con el/ella (#1)? 187. Cuantas veces la semana habla por telefono con el/ella (#2)? 188. Cuantas veces la semana habla por telefono con el/ella (#3)? 189. Si viven en Mexico o otro ciudad, cauantas veces al mes les escribe? 190. Tiene otros amigos (no incluye los 3 mejores amigos) que viven en otras ciudades de los EEUU? 191. Cuales ciudades? 192. Pertenece a algunas asociaciones sociales? 193. Cuantos grupos? 194. Cual es el nombre (#1)? 195. De donde son los miembros de este club o grupo (#1)? 196. Es un grupo formal o informal (#1)? 197. Que hace este grupo (#1)? 198. Juaga Ud. un deporte? 199. Cual deporte? 200. Juega por un equipo? 201. De donde son los miembros del equipo? 202. Contra quien juegan? 203. Que tipo de relacion tiene con Chicanos? 204. Describe los problemas que tiene: 205. Que tipo de relacion tiene con Mexicanos? 206. Que tipo de relacion tiene con otros Latinos? 207. Que tipo de relacion tiene con Anlgos (Gringos)? 208. Que tipo de relacion tiene con Negros? 209. Describe los problemas que tiene: 210. Que tipo de relacion tiene con Asiaticos? 211. Habla Ud. Ingles? 212. Cual idioma habla mas en casa? 213. Cual idioma habla mas al trabajo/escuela? 214. Cual Idioma habla con los vecinos? 215. Cual idioma habla con la mayoria de los amigos o familiars? 108
109 216. Cual idioma habla con esposa(o)/novia(o)? 217. Le gusta escuchar musica? 218. Cuales grupos/cantantes son sus preferidos? 219. Escucha la radio? 220. Cual canal? 221. Que tipo de programas le gusta escuchar? 222. Le gusta ver la television? 223. Cual es su canal preferida? 224. Cuales son sus programas preferidas? 225. Le gusta bailar? 226. Donde baila? 227. Que clase de baile? 228. Le gusta ver las peliculas? 229. Cuales son sus peliculas preferidas? 230. Cual es su actor/actriz favorito/a? 231. Cuales son su pasatiempos (no mencionadas antes)? 232. Le gusta cocinar? 233. Cual es su comida preferida? 234. Cuando salga para cenar a cuales restaurants vaya? 235. Por cuales occaciones reune con sus amigos y familiars 236. Con que frequencia llama al Mexico? 237. Cuando llama como paga? 238. A quien llama? 239. Con que frequencia escribe cartas o postales al Mexico? 240. A quien escribe? 241. Usa el Internet? 242. Usa para escribir cartas electronicas a amigos/familia en Mexico? 243. Como mas lo usa? 244. Que quiere decir el patriotismo para Ud? 245. Que es identidad nacional? 246. Como es para ser Mexicano mientras vivir en los EEUU? Describelo. 247. Describe su connecion emocional a su tierra nativa (pueblo, ciudad, estado, pais 248. Piensa Ud. que esta viviendo con las patas en dos mundos? 249. Describelo: 250. Piensa volver algun dia a su tierra nativa? 251. Cuando? Como? 252. Ya estamamos terminados con la entrevista, a algo que quire añadir o cambiar?
109
APPENDIX D - US AND MEXICO NETWORK TIES
Table 16 - US and M exican Family/Social Ties Core Sample
12 23 18
14
5
26
9
1
10
16
17
Key
19 4 13 22 8 11 US Marriage US Family Tie US Social Tie Mex Marriage 24 2 28 20 Mex Family Tie Mex Social Tie
111
Table 15 - US and Mexican Family/Social Ties - Church Sample
3
6
21
7
15
Key
US Marriage US Family Tie US Social Tie Mex Marriage Mex Family Tie Mex Social Tie
111
This document was created with Win2PDF available at. The unregistered version of Win2PDF is for evaluation or non-commercial use only. | https://www.scribd.com/document/2279630/Thesis-Updated-10-15-2002 | CC-MAIN-2018-13 | refinedweb | 30,959 | 51.68 |
Plum those issues are unique to the application at hand, but one particular type of issues stands out.
What we found out was that almost every Java application out there is using either Log4j or Logback. As a matter of fact, from the data we had available, it appears to be that more than 90% of the applications are using either of those frameworks for logging. But this is not the interesting part. Interesting is the fact that about third of those applications are facing rather significant lock wait times during logging calls. As it stands, more than 10% of the Java applications seem to halt for more than 5,000 milliseconds every once in a while during the innocent-looking log.debug() call.
Why so? Default choice of an appender for any server environment is some sort of File appender, such as RollingFileAppender for example. What is important is the fact that these appenders are synchronized. This is an easy way to guarantee that the sequence of log entries from different threads is preserved.
To demonstrate the side effects for this approach, we setup a simple JMH test (MyBenchmark) which is doing nothing besides calling log.debug(). This benchmark was ran on a quad-core MacBook Pro with 1,2 and 50 threads. 50 threads was chosen to simulate a typical setup for a servlet application with 50 HTTP worker threads.
@State(Scope.Benchmark) public class LogBenchmark { static final Logger log = LoggerFactory.getLogger(LogBenchmark.class); AtomicLong counter; @Benchmark public void testMethod() { log.debug(String.valueOf(counter.incrementAndGet())); } @Setup public void setup() { counter = new AtomicLong(0); } @TearDown public void printState() { System.out.println("Expected number of logging lines in debug.log: " + counter.get()); } }
From the test results we see a dramatic decrease in throughput 278,898 ops/s -> 84,630 ops/s -> 73,789 ops/s we can see that going from 1 to 2 threads throughput of the system decreases 3.3x.
So how can you avoid this kind of locking issues? The solution is simple – for more than a decade there has been an appender called AsyncAppender present in logging frameworks. The idea behind this appender is to store the log message in the queue and return the flow back to the application. In such a way the framework can deal with storing the log message asynchronously in a separate thread.
Let’s see how AsyncAppender can cope with multithreaded application. We set up similar simple benchmark but configure the logger for that class to use AsyncAppender. Now, when we run the benchmark with the same 1, 2 and 50 threads we get stunning results: 4,941,874 ops/s -> 6,608,732 ops/s -> 5,517,848 ops/s. The improvement in throughput is so good, that it raises suspicion that there’s something fishy going on.
Let’s look at the documentation of the AsyncAppender. It says AsyncAppender is by default a lossy logger, meaning that when the logger queue will get full, appender will start dropping trace, debug and info level messages, so that warnings and errors would surely get written. This behavior is configured using 2 parameters – discardingThreshold and queueSize. First specifies how full should be the queue when messages will start to be dropped, second obviously specifies how big is the queue.
The default queue size set to 256 can for example configured to 0 disabling discarding altogether so that the appender becomes blocking when the queue will get full. To better understand the results, let’s count the expected number of messages in the log file (as the number of benchmark invocations by the JMH is non-deterministic) and then compare how many were actually written to see how many messages are actually discarded to get such brilliant throughput.
We run the benchmark with 50 threads, varied the queue size and turned discarding on and off. The results are as follows:
What can we conclude from them? There’s no free lunches and no magic. Either we discard 98% of the log messages to get such massive throughput gain, or when the queue fills, we start blocking and fall back to performance comparable to synchronous appender. Interestingly the queue size doesn’t affect much. In case you can sacrifice the debug logs, using AsyncAppender does make sense. | http://www.javacodegeeks.com/2014/07/locking-and-logging.html | CC-MAIN-2014-42 | refinedweb | 715 | 61.56 |
SolarPHP 1.0 Released
timothy posted more than 4 years ago | from the something-new-under-the-sun dept.
(1)
royallthefourth (1564389) | more than 4 years ago | (#31445460)
It's called Symfony, FYI
Re:Symfony (-1, Troll)
The Turd Burglar (1765270) | more than 4 years ago | (#31446224)
Can I burgle some turds from your toilet?
blog (4, Insightful)
killmenow (184444) | more than 4 years ago | (#31445528)
Re:blog (-1, Redundant)
Archangel Michael (180766) | more than 4 years ago | (#31445560)
I just used the last of my mod points
... crap ..
Re:blog (2, Informative)
nacturation (646836) | more than 4 years ago | (#31445564)
It is being Slashdotted right now, so it's not known whether the limitation is the framework speed, the server it's on, available bandwidth, database performance, or something else.
Foghorn Leghorn Alert (4, Funny)
killmenow (184444) | more than 4 years ago | (#31445614)
(just a little something I picked up in Sarcasm 101)
Re:Foghorn Leghorn Alert (1)
WrongSizeGlass (838941) | more than 4 years ago | (#31445714)
Re:Foghorn Leghorn Alert (2, Funny)
nacturation (646836) | more than 4 years ago | (#31445958)
I'm built too low. The fast ones go over my head. I got a hole in my glove. You keep pitchin' 'em and I keep missin' 'em. I gotta keep my eye on the ball. Eye. Ball. I almost had a gag.
Re:Foghorn Leghorn Alert (1)
bwintx (813768) | more than 4 years ago | (#31445976)
Re:blog (-1, Flamebait)
Anonymous Coward | more than 4 years ago | (#31446040)
Molasses? What are you? A fucking nigger?
Re:blog (0, Flamebait)
killmenow (184444) | more than 4 years ago | (#31446080)
Re:blog (-1, Offtopic)
Anonymous Coward | more than 4 years ago | (#31446326)
Enjoy the genital warts and scabies she gave you. My mom is a slut.
Re:blog (1)
jo42 (227475) | more than 4 years ago | (#31446234)
He's running Wordpress. At least he could have of installed something other than a version of the hideous default theme that it comes with.
Re:blog (0)
Anonymous Coward | more than 4 years ago | (#31446734)
...could have installed...
Literacy rocks. Try it.
Re:blog (1)
XorNand (517466) | more than 4 years ago | (#31447404)
Re:blog (1)
michaelhood (667393) | more than 4 years ago | (#31449356)! [ ]"
Perfect timing... (0, Interesting)
Anonymous Coward | more than 4 years ago | (#31445628)!
Re:Perfect timing... (-1, Troll)
Anonymous Coward | more than 4 years ago | (#31446070)
You'll find that PHP really isn't fast enough for complex applications. You should use Oracle instead.
google "cache:..." (2, Informative)
MessyBlob (1191033) | more than 4 years ago | (#31445642)
Improving PHP (0, Interesting)
Anonymous Coward | more than 4 years ago | (#31445650)
If the community wants to improve PHP they could start with making the function, class and method names case sensitive. For some unknown reason the powers behind PHP have chosen not fix this.
At the end of the day... (0)
Anonymous Coward | more than 4 years ago | (#31445778)
... it's still PHP.
Lipstick on a pig and all that.
Re:At the end of the day... (1, Funny)
Anonymous Coward | more than 4 years ago | (#31445994)
What does Sarah Palin have to do with this?
Re:At the end of the day... (0, Flamebait)
evanism (600676) | more than 4 years ago | (#31446174)
any PHP framework cant be as slow as Palin
Re:At the end of the day... (1)
Narcocide (102829) | more than 4 years ago | (#31447310)
I dunno man Joomla is pretty fucking slow...
Re:At the end of the day... (0, Redundant)
The Turd Burglar (1765270) | more than 4 years ago | (#31447784)
Trig still has PHP beat for slowness.
Re:At the end of the day... (0)
Anonymous Coward | more than 4 years ago | (#31447804)
Re:At the end of the day... (0)
Anonymous Coward | more than 4 years ago | (#31447862)
He was overqualified.
Performance? (1)
palmerj3 (900866) | more than 4 years ago | (#31445814)
Re:Performance? (2, Informative)
Sollord (888521) | more than 4 years ago | (#31446516)
Re:Performance? (1)
Fnkmaster (89084) | more than 4 years ago | (#31446868)
Except that it uses Wordpress rather than PHPSolar or whatever it's called. Thus having no bearing whatsoever on the discussion.
Epic fail.
Re:Performance? (1)
sootman (158191) | more than 4 years ago | (#31448050)
Is that "epic fail" on the part of the parent for not researching before he commented and being wrong, or "epic fail" on the part of the site owner for using WP instead of eating his own dogfood?
Yet another... (3, Insightful)
menkhaura (103150) | more than 4 years ago | (#31446056)
Yet another PHP framework. Won't this ever stop? Won't the development efforts ever be directed to only a handful of frameworks, to get the best we can instead of a gazillion half-(or un-) documented, over-(or under-) engineered frameworks?
Re:Yet another... (3, Funny)
BitHive (578094) | more than 4 years ago | (#31446308):Yet another... (2, Insightful)
Anonymous Coward | more than 4 years ago | (#31446400) with it on a limited basis if ever before, and only wants to learn it because he's heard on some blog that it will increase his productivity. Since the average framework has a lifecycle of approximately 1 project all he's really done is slowed development of that project immensely to pick up a braindead API he will never see again.
Re:Yet another... (3, Insightful)
evanism (600676) | more than 4 years ago | (#31447124):Yet another... (1)
ducomputergeek (595742) | more than 4 years ago | (#31448864) schedule for once. Every time they need some API or function, there seemed to be a Perl Module for it already in CPAN, tested, and pretty much exactly what was needed.
PHP guys are easier to come by these days, but the last few PHP projects I've been involved in, it seems like they spend a lot of time trying out the Popular Framework of the year, only to decide to roll their own. I may be biased, but a lot of the projects seems like they could have been almost done if they just gone with Perl.
But I'm just a systems guy. I'm biased towards Perl because I like getting shit done.
Re:Yet another... (0)
Anonymous Coward | more than 4 years ago | (#31449466)
Last time I checked the pear stuff was outnumbering the cpan stuff. NB: I don't really code in either language anymore.
Re:Yet another... (2, Insightful)
Kjella (173770) | more than 4 years ago | (#31446478) (3, Insightful)
SmallFurryCreature (593017) | more than 4 years ago | (#31449760)
:Yet another... (2, Informative)
iamgnat (1015755) | more than 4 years ago | (#31446504) with PHP and often rolled my own libraries and objects even when the basic functionality exists simply because I disagree with fundamental decisions that were made (like how they (don't) handle errors being the most common. PHP supports Exceptions for christ sake. Use them!).
Re:Yet another... (0, Flamebait)
biryokumaru (822262) | more than 4 years ago | (#31448396)
I'm not saying that there are good PHP people out there
Good. Neither are we.
Re:Yet another... (1)
larry bagina (561269) | more than 4 years ago | (#31447826)
Re:Yet another... (1)
ArundelCastle (1581543) | more than 4 years ago | (#31446346)
Oh, you mean a PHP cartel.
Sure, that usually turns out fine.
Also, if you happen to be involved in any open source projects, could you please stop diluting the workforce and just go work for somebody established? You're hurting the big guys.
Re:Yet another... (1)
onion2k (203094) | more than 4 years ago | (#31446374) native code, or maybe cache content into static HTML, so the speed of the framework itself is meaningless - a good one does at little as possible for each page view.
Re:Yet another... (1)
nurb432 (527695) | more than 4 years ago | (#31446438)
Its not just PHP, the entire OSS world is like this..
Everyone wants their own wheel as no one likes painting a wheel that belongs to someone else.
No. (1)
weston (16146) | more than 4 years ago | (#31446468) probably farther down but still striking the fancy of developers here or there.
But it pretty much comes down to developer itches, and the fact that thoroughly understanding a system is usually a task roughly equivalent to writing it.
Re:Yet another... (2, Insightful)
OzRoy (602691) | more than 4 years ago | (#31446968):Yet another... (0)
Anonymous Coward | more than 4 years ago | (#31447290)
No.
This is the nature of open source. Opinions are like arseholes, everyone has one and everyone else's stinks. What is the 'best we can' ? Does the we in that sentence include me because it doesn't look like we'd agree?
And this is where open source keeps tripping over it's own toes. You can't please everyone all the time. And the natural response from the majority?
... fork-off. So we end up with 670 different Linux distributions, 150 AJAX libraries, 50 mature PHP frameworks, multiple mature mysql distros. And everything has it's own foibles, problems, syntax, configuration settings ... gah!
PHP has a beautiful API! If this isn't enough of a framework for you, enhance it. Anything not targeted at the base API isn't worth considering.
Re:Yet another... (1)
Ukab the Great (87152) | more than 4 years ago | (#31448996):Yet another... (0)
Anonymous Coward | more than 4 years ago | (#31449186)
You missed the point, here, then. Ruby itself is the fad of the week, and there is no competition within that ecosystem because nobody else except the Rails fad-seeking web develotards even give a shit about it. I reiterate that practically nobody gave a shit about, or even knew of, Ruby until the "Ruby on Rails" blog spampaign by that egocentric shitstain of a lead developer began. It's essentially an immature language previously relevant (and I may be assuming too much here, even) only in deep, dark corners of academia. Look at Twitter: it's always a great idea to run on a platform where much of your developer time is spent optimizing the language's virtual machine because it has never been scaled to a production implementation before, right?
Can't beat PHPulse (-1, Redundant)
Foofoobar (318279) | more than 4 years ago | (#31446170)
Phpulse is still faster (0, Redundant)
Foofoobar (318279) | more than 4 years ago | (#31446266) [phpulse.com]
Rails 3.1 Comparison (-1, Troll)
BitHive (578094) | more than 4 years ago | (#31446368)
The reason nobody cares about your web framework is that they'd rather type:
def index
@posts = Post.where(:status => 'public').order('created DESC')
end
instead of:
<?php
public function actionIndex()
{
$fetch = array(
'where' => array('blogs.status = ?' => 'public'),
'order' => 'blogs.created DESC',
'page' => 'all',
);
$this->list = $this->_model->blogs->fetchAll($fetch);
}
?>
Re:Rails 3.1 Comparison (1)
rho (6063) | more than 4 years ago | (#31446554)
Yeah, because Rails is being used everywhere.
Re:Rails 3.1 Comparison (2, Interesting)
BitHive (578094) | more than 4 years ago | (#31446582)
If we used what was everywhere everyone would be developing websites in
.NET to deploy on their Windows intranet. But it's a lot easier to be sarcastic than have a point other than "lol nobody uses Rails" (as if that were even close to true).
Re:Rails 3.1 Comparison (0)
Anonymous Coward | more than 4 years ago | (#31446866)
Re:Rails 3.1 Comparison (1)
BitHive (578094) | more than 4 years ago | (#31446912)
Masterfully observed
Re:Rails 3.1 Comparison (2, Insightful)
thasmudyan (460603) | more than 4 years ago | (#31447352)'
));
}
Without knowing the actual library used for the PHP example, there might be saner and less ugly variants.
Re:Rails 3.1 Comparison (1)
DavidTC (10147) | more than 4 years ago | (#31448856) presumably use 'blogs' by default. You can just use 'status' and 'created' as the Ruby example does. So:
public function actionIndex() {
$this->list = $this->_model->blogs->fetchAll(array('where' => array('status = ?' => 'public'),'order' => 'created DESC'));
}
Also, I don't know in what universe you commonly pass a single array to functions instead of, you know, actual function parameters. While I'm sure in some universe there's some framework that lets you do that, in reality you'd have a fetchAll($where,$order=NULL) function that you could use here, with array passing used for really options stuff, and an array passed in for $where. And, also, inexplicably, your function name has doubled in PHP.
So it would more likely be something like:
public function index() {
$this->list = $this->_model->blogs->fetchAll(array('status = ?' => 'public'), 'created DESC');
}
Vs:
def index
@posts = Post.where(:status => 'public').order('created DESC')
end
Yeah, that's massively shorter. Why, in PHP, you have to...um...explicitly use $this to access your own class and use array() to make an array. The horrors, the horrors!
Why on earth you're writing a public function for this is beyond me, though. I think you just did that because PHP takes longer to define a public function.
A sane programmer would just, instead of defining a class to have actionIndex() on, and then making such an object, and then calling $random_obect->actionIndex(); and then $records = $random_obect->list(); would just do this:
$records = $this->_model->blogs->fetchAll(array('status = ?' => 'public'), 'created DESC');
Re:Rails 3.1 Comparison (1)
DavidTC (10147) | more than 4 years ago | (#31448862)
Re:Rails 3.1 Comparison (1)
BitHive (578094) | more than 4 years ago | (#31449036)
You seem to think I made up that example, when in fact I got it from the SolarPHP documentation: [solarphp.com]
Re:Rails 3.1 Comparison (1)
BitHive (578094) | more than 4 years ago | (#31449048)
You also assume a lot about what the Ruby code is doing; this is where my Rails example is from: [onkey.org]
Re:Rails 3.1 Comparison (1)
BitHive (578094) | more than 4 years ago | (#31449016)
Actually I pulled the sample straight from the documentation for the project in the OP.
Re:Rails 3.1 Comparison (1)
thasmudyan (460603) | more than 4 years ago | (#31449904) PHP-heavy programmer myself, I have to concede that PHP's syntax is anything but elegant. It's one step away from the surreal ASCII art that is Perl
;-)
Re:Rails 3.1 Comparison (0)
Anonymous Coward | more than 4 years ago | (#31447658)
You could also abbreviate every. posts == p, Post to P, and status to s. and public to p, and created to c. Then it would be.
@p = P.where(:s => 'p').order('created DESC')
Even less typing. cause typing is so tedious and IDE's have autocomplete and copy paste.
But then in PHP I could use something like
Or
And they may not be as AWESOME, but they're alright.
In the end it depends what you want to do, how long you have to do it, what your stuck working with, and how fast it needs to run.
Re:Rails 3.1 Comparison (1)
BitHive (578094) | more than 4 years ago | (#31449080) though, your counterpoint is a bit forced. It's not about reducing keystrokes at all costs, it's about providing the programmer with useful abstractions and reducing the need for him to repeat him or herself. Let's be real here and just admit that PHP doesn't make this easy for frameworks.
Bad Mod Alert. (1)
weston (16146) | more than 4 years ago | (#31448744)
(Score:0, Offtopic)
While the smugness of the parent post could be interpreted at a stretch as flamebait or trolling, it's in no way offtopic. Comparing code density/expressiveness between frameworks is topical.
Re:Rails 3.1 Comparison (1)
Bill, Shooter of Bul (629286) | more than 4 years ago | (#31449222)
Re:Rails 3.1 Comparison (1)
amn108 (1231606) | more than 4 years ago | (#31449752)
To paraphrase MadTV's Snoop Dogg video parody, "it's all about the blogz, baby, it's all about the blogz." I am ironic of course, but let's face it - the media paints this picture of Internet that is full of blogs.
No more frameworks please! (4, Interesting)
Hurricane78 (562437) | more than 4 years ago | (#31446576):No more frameworks please! (1)
Aladrin (926209) | more than 4 years ago | (#31446914)
I've never understood this. Why are you telling other developers what to do with their time? If you don't want their framework, IGNORE IT. If you want libraries, build them.
Re:No more frameworks please! (3, Funny)
Michael Kristopeit (1751814) | more than 4 years ago | (#31447106):No more frameworks please! (1)
royallthefourth (1564389) | more than 4 years ago | (#31447958)
Many developers end up picking up the pieces of halfway finished projects leftover by others; nobody works in a vacuum.
A good developer should care about what others are doing for a variety of reasons.
Re:No more frameworks please! (0)
Anonymous Coward | more than 4 years ago | (#31448018)
I don't care what they spend their time coding, its when they start to spew marketing-grade bullshit about the capabilities of their personal libraries, package them as a framework, and proceed to infect developers and fragment public domain code with yet another unnecessary, unoriginal, poorly conceived and poorly documented set of code generation tools that I get irate.
Fuck this guy and fuck his new framework. The world needs another PHP framework like I need a hole in my head.
Re:No more frameworks please! (1)
amn108 (1231606) | more than 4 years ago | (#31449778) their 'puter. Frameworks sometimes negatively affect developers who have never heard of them, or never WANTED to, for all the good reasons. If it's not your boss telling you what to do, it also happens some client pulls you in for a job, and then you discover you are in for redesigning their Joomla/EZ/Wordpress/Asswork website. Something the client did not assume to mention, because they think all developers can develop anything using anything. Sort of like if architects were expected to design a functional house, sketching with crayons on ricepaper.
Re:No more frameworks please! (0)
Anonymous Coward | more than 4 years ago | (#31447092)
I briefly visited the website and couldn't find the gitweb or equivalent so that I could laugh at the source code. I did however find the class documentation to be amusing. eg:
Pfft!
I've already got all the useful functionality as libs that I authored myself and my code is probably of a higher standard. My vote would be to replace the term "web framework" with the term "web programming clusterfuck"; it's a much more realistic description. I doubt that even that change would stop poor programmers mistaking the authors self-promotion for programming ability -- which is the only way to explain the popularity of "web programming clusterfucks".
Re:No more frameworks please! (1)
corychristison (951993) | more than 4 years ago | (#31447126) with '?>'. Why is that?
Re:No more frameworks please! (1, Informative)
Anonymous Coward | more than 4 years ago | (#31447244)
And they don't appear to close half of their
.php files with '?>'. Why is that?
Because you avoid errors with trying to send headers after output since someone left whitespace at the end of a ?>
Re:No more frameworks please! (1)
Dexx (34621) | more than 4 years ago | (#31449070)
Re:No more frameworks please! (1)
Chris Graham (942108) | more than 4 years ago | (#31449492)
Re:No more frameworks please! (1, Informative)
profplump (309017) | more than 4 years ago | (#31447274)! (4, Informative)
jjohnson (62583) | more than 4 years ago | (#31447378):No more frameworks please! (0, Flamebait)
shelterit (142065) | more than 4 years ago | (#31447414)
Re:No more frameworks please! (0)
Anonymous Coward | more than 4 years ago | (#31448546)
I am happy you didn't get basted for the ?> comment. Good job everyone on showing restraint and taking the higher road.
Truth is, when you think you've learned everything there is to know about the intricacies of languages and best practices... You've missed something and need to go back to the books. I'm slowly learning that lesson. Judgment requires experience and you need to know when you've got the experience.
Zend Framework For You, then (3, Informative)
weston (16146) | more than 4 years ago | (#31447174):Zend Framework For You, then (1)
giuntag (833437) | more than 4 years ago | (#31449428)
Re:No more frameworks please! (0)
Anonymous Coward | more than 4 years ago | (#31447248)
FYI Zend Framework _is_ a library. You can selectively use different elements as needed in plain old PHP scripts or with other frameworks. I've used it as a library for both CakePHP and CodeIgniter apps.
Re:No more frameworks please! (0)
Anonymous Coward | more than 4 years ago | (#31448538)
Solar *is* just a nice set of libraries. It has a separate application skeleton for those who want to get up and running quickly, as well as CLI tools to generate pieces of the basic structure.
Re:No more frameworks please! (1)
amn108 (1231606) | more than 4 years ago | (#31449800) always look for better tools. Sometimes though they find tools originally either made for something else (Flash) or the tools are so specialized, that even though they appear to fit perfectly for a particular kind of task, once the constraints or goals of this task change, it's a dead end for the tool user.
I have a contact that tries to make a generic website, using Wordpress for some reason. I have asked why Wordpress, a blogging CMS, but the person cannot give a good answer. They had used it before for blogs, came to like its ease of use, and came to think it should also fit fine for anything else than blogs, despite the fact that Wordpress goes pretty far to mark itself as a blogging CMS, nothing else. The human element fails?
Needless to mention, the person is pulling his hair now, because they need completely different functionality than Wordpress includes or easily allows for. But it is a bit too late, because a month was spent to set up the Wordpress site...
Debate? (1)
thePowerOfGrayskull (905905) | more than 4 years ago | (#31447624)? (1)
SlappyBastard (961143) | more than 4 years ago | (#31448160)
Re:What is the point of PHP frameworks? (1)
tthomas48 (180798) | more than 4 years ago | (#31448300) should be writing straight php files with markup embedded (and how to write the later so you can eventually move to the former if necessary)?
Re:What is the point of PHP frameworks? (1)
PhantomHarlock (189617) | more than 4 years ago | (#31448434):What is the point of PHP frameworks? (1)
tthomas48 (180798) | more than 4 years ago | (#31448710)elligible scribbles.
Yes, it is (1)
SmallFurryCreature (593017) | more than 4 years ago | (#31449794) people are not really used to such languages. They have always been considered to be to primitive.
And so the "proper" developers have always had a thing against PHP that allowed just anybody to start producing code and working web sites. You can see in a lot of frameworks the attempt to force PHP to become another language.
Do you need a framework? No, unless you come from a background where just raw coding is not how you do things. There is a difference between scripting and "programming". Please don't hang me up on those terms, but you probably get my meaning if I say the average Java developer would choke on Perl and the average Perl developer considers Java to be hopelessly over engineered.
One of my favorite discussions was with a Java developer about PHP's lack of proper garbage collection... he spend several hours trying to explain how important garbage collection is, in a script that runs for a few miliseconds and then is cleared completly from memory. It is like claiming that you absolutely need a parachute, on a kamikaze plane.
forget all this what about HIPHOP compiled PHP (0)
Anonymous Coward | more than 4 years ago | (#31448164)
Another framework. Big whoop. I'm more interested in things like HIPHOP that allow you to compile PHP to code for fast performance.
How does it compare to CodeIgniter? (1)
PhantomHarlock (189617) | more than 4 years ago | (#31448422) the wheel. CI looks relatively smaller in comparison.
The thing I like about CI is you just load the libraries or classes that you need for that particular app, so it remains very lightweight.
Re:How does it compare to CodeIgniter? (0)
Anonymous Coward | more than 4 years ago | (#31448498)
There are only a handful of classes required during a request on a bare-bones controller. Everything else is loaded as needed.
Some of the structuring in Solar is very different to other frameworks. Models are loaded through the model catalog, and depending on the query can return either a single model record, or a model collection of records (these are basically structs so they can be treated as objects or arrays).
If you don't see the sense of it, you will when you use it. Solars methodologies make it extremely flexible, so anything can be changed or extended if required.
Clarification (1, Informative)
Anonymous Coward | more than 4 years ago | (#31448462) libraries, or something in the middle. Even Zend has borrowed ideas from Solar ().
I like to think of it as a framework for people who already know PHP. Having worked with CakePHP, CodeIgniter and a few others, there are far too many people in those communities who think that by using a framework they don't need to learn how to program. I'm pretty confident these people won't understand Solar. Hooray!
Things to love about Solar:
Serious spagetti (1)
Aethedor (973725) | more than 4 years ago | (#31449606) | http://beta.slashdot.org/story/132608 | CC-MAIN-2014-15 | refinedweb | 4,242 | 71.95 |
Problem Statement
In the “Permutations of a Given String Using STL” problem, we have given a string “s”. Print all the permutations of the input string using STL functions.
Input Format
The first and only one line containing a string “s”.
Output Format
Print all the permutation of the given string where every line containing only one string.
Constraints
- 1<=|s|<=10
- s[i] must be a lower case English alphabet
Example
ABC
ABC ACB BCA BAC CAB CBA
Explanation: Here there are total 3*2*1 permutations. After performing operations, we get ABC, ACB, BCA, BAC, CAB, CBA as our answer.
Algorithm for Permutations of a Given String Using STL
Permutation also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Here we use the next_permute() function, which rearranges the given string and returns the lexicographically next permutation.
The “rotate()” function rotates elements of a vector/string such that the passed middle element becomes first. For example, if we call rotate for “abc” with the middle as the second element, the string becomes “bca”. And if we again call rotate with the middle as the second element, the string becomes “cab”.
- Take input string s from the user and another empty string ans.
- When the size of str becomes 0, ans has a permutation (length of “ans” is n).
- One by one move all characters at the beginning of the string “ans”.
- Remove the first character from str and add it to “ans”.
- Rotate string by one char left.
Implementation
C++ Program for Permutations of a Given String Using STL
#include <bits/stdc++.h> using namespace std; void permute(string s, string ans) { if(s.size()==0) { cout<<ans<<endl; return; } for(int i=0;i<s.size();i++) { permute(s.substr(1),ans+s[0]); rotate(s.begin(),s.begin()+1,s.end()); } } int main() { string s; cin>>s; permute(s,""); return 0; }
Java Program for Permutations of a Given String Using STL
import java.util.Scanner; import java.util.Vector; class sum { public static String leftrotate(String str) { String ans = str.substring(1) + str.substring(0, 1); return ans; } public static void permute(String s, String ans) { if(s.length()==0) { System.out.println(ans); return; } for(int i=0;i<s.length();i++) { permute(s.substring(1),ans+s.charAt(0)); s = leftrotate(s); } } public static void main(String[] args) { Scanner sr = new Scanner(System.in); String s = sr.next(); permute(s,""); } }
cup
cup cpu upc ucp pcu puc
Complexity Analysis for Permutations of a Given String Using STL
Time Complexity
O(n!) where n is the size of the given string. Here we print all the permutation of the given string “s”.
Space Complexity
O(n) where n is the size of the given string. We use this space to store a string that represents a particular permutation before printing it. | https://www.tutorialcup.com/interview/string/permutations-of-a-given-string-using-stl.htm | CC-MAIN-2021-49 | refinedweb | 501 | 57.98 |
I’m gearing up for a new release of DFConnect, which has been renamed to Daggerfall Connect. I feel this is more in line with the naming convention of my other tools and avoids any potential misunderstanding with a trademarked property also called DFConnect.
The next build is a major update across the entire namespace. I have temporarily taken down all Daggerfall Connect pages while I update the documents, tutorials, FAQ, etc. These should be back in a couple of weeks.
To summarise, the following changes have been made to Daggerfall Connect:
- DaggerfallConnect root namespace now contains classes and structures emitted back to applications, such as DFBlock and DFMesh. These were previously in the Arena2 namespace. The reasoning is to keep “low-level” classes in Arena2 and “high-level” classes in the root namespace. The Arena2 namespace now only contains classes for opening files in the Arena2 folder.
- The Utility namespace has been added. This is for mostly internal classes used by Daggerfall Connect, but may contain public classes at a later date.
- The first reader class has been added. ImageFileReader is a vastly simplified way of opening any Daggerfall image file.
- All image classes are now based on abstract base class DFImageFile. This allows ImageFileReader to handle all image files in a standard way and return a standard object back to applications regardless of the image file type originally opened.
- Casing changed from lower camel casing (e.g. getFrameCount) to upper camel casing (e.g. GetFrameCount). This is to be more in line with .NET Framework conventions.
I will post more on this after Daggerfall Imaging 2 is released. | https://www.dfworkshop.net/dfconnect-rename-update/ | CC-MAIN-2021-04 | refinedweb | 270 | 57.98 |
August 2014
Volume 29 Number 8
Microsoft Azure : Use Distributed Cache in Microsoft Azure
Iqbal Khan | August 2014
Microsoft Azure is rapidly becoming the cloud choice for .NET applications. Besides its rich set of cloud features, Azure provides full integration with the Microsoft .NET Framework. It’s also a good choice for Java, PHP, Ruby and Python apps. Many of the applications moving to Azure are high-traffic, so you can expect full support for high scalability. In-memory distributed cache can be an important component of a scalable environment.
This article will cover distributed caching in general and what it can provide.
The features described here relate to general-purpose in-memory distributed cache, and not specifically Azure Cache or NCache for Azure. For .NET applications deployed in Azure, in-memory distributed cache has three primary benefits:
- Application performance and scalability
- Caching ASP.NET session state, view state and page output
- Sharing runtime data with events
Application Performance and Scalability
Azure makes it easy to scale an application infrastructure. For example, you can easily add more Web roles, worker roles or virtual machines (VMs) when you anticipate higher transaction load. Despite that flexibility, data storage can be a bottleneck that could keep you from being able to scale your app.
This is where an in-memory distributed cache can be helpful. It lets you cache as much data as you want. It can reduce expensive database reads by as much as 90 percent. This also reduces transactional pressure on the database. It will be able to perform faster and take on a greater transaction load.
Unlike a relational database, an in-memory distributed cache scales in a linear fashion. It generally won’t become a scalability bottleneck, even though 90 percent of the read traffic might go to the cache instead of the database. All data in the cache is distributed to multiple cache servers. You can easily add more cache servers as your transaction load increases. Figure 1 shows how to direct apps to the cache.
Figure 1 Using In-Memory Distributed Cache in .NET Apps
// Check the cache before going to the database Customer Load(string customerId) { // The key for will be like Customer:PK:1000 string key = "Customers:CustomerID:" + customerId; Customer cust = (Customer)Cache[key]; if (cust == null) { // Item not found in the cache; therefore, load from database LoadCustomerFromDb(cust); // Now, add this object to the cache for future reference Cache.Insert(key, cust, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null ); } return cust; }
An in-memory distributed cache can be faster and more scalable than a relational database. Figure 2 shows some performance data to give you an idea. As you can see, the scalability is linear. Compare this with your relational database or your ASP.NET Session State storage and you’ll see the benefit.
Figure 2 Performance Numbers for a Typical Distributed Cache
Caching ASP.NET Session State, View State and Page Output
Using in-memory distributed cache in Azure also helps with ASP.NET Session State, ASP.NET View State and ASP.NET Output Cache. You’ll need to store ASP.NET Session State somewhere. This can become a major scalability bottleneck. In Azure, you can store ASP.NET Session State in a SQL database, Azure Table Storage or an in-memory distributed cache.
A SQL database isn’t ideal for storing session state. Relational databases were never really designed for Blob storage, and an ASP.NET Session State object is stored as a Blob. This can cause performance issues and become a scalability bottleneck.
Similarly, Azure Table Storage isn’t ideal for Blob storage. It’s intended for storing structured entities. Although it’s more scalable than a SQL database, it’s still not ideal for storing ASP.NET Session State.
An in-memory distributed cache is better suited for storing ASP.NET Session State in Azure. It’s faster and more scalable than the other two options. It also replicates sessions so there’s no data loss if a cache server goes down. If you store sessions in a separate dedicated caching tier, then Web roles and Web server VMs become stateless, which is good because you can bring them down without losing any session data.
While running ASP.NET Session State in cache is ideal from a performance standpoint, if the cache goes down, your entire app will go down. And, of course, whatever is in your session would also be gone. The new Redis Cache for Azure session state provider will have a way you can know when these types of issues happen and at least display them to the user in a clean way.
Figure 3 shows how to configure an in-memory distributed cache to store ASP.NET Session State.
Figure 3 Configure ASP.NET Session State Storage in a Distributed Cache
// Check the Cache before going to the database Customer Load(string customerId) { // The key for will be like Customer:PK:1000 string key = "Customers:CustomerID:" + customerId; Customer cust = (Customer)Cache[key]; if (cust == null) { // Item not found in the cach; therefore, load from database LoadCustomerFromDb(cust); // Now, add this object to the cache for future reference Cache.Insert(key, cust, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null ); } return cust; }
Although the ASP.NET MVC framework has removed the need for using ASP.NET View State, the majority of ASP.NET applications haven’t yet moved to the ASP.NET MVC framework. Therefore, they still require ASP.NET View State.
ASP.NET View State can be a major bandwidth burden, and cause a noticeable drop in your ASP.NET application response times. That’s because ASP.NET View State can be hundreds of kilobytes for each user. It’s unnecessarily sent to and from the browser in case of post back. If this ASP.NET View State is cached on the Web server end and a unique identifier is sent to the browser, it can improve response times and also reduce the bandwidth consumption.
In Azure, where your ASP.NET application is running in multiple Web roles or VMs, the least disruptive place to cache this ASP.NET View State is in an in-memory distributed cache. That way, you can get at it from any Web server. Here’s how you can configure the ASP.NET View State for storage in an in-memory distributed cache:
<!-- /App_Browsers/Default.browser --> <browsers> <browser refID="Default" > <controlAdapters> <adapter controlType="System.Web.UI.Page" adapterType="DistCache.Adapters.PageAdapter"/> </controlAdapters> </browser> </browsers>
ASP.NET also provides an output cache framework that lets you cache page output that’s not likely to change. That way you don’t have to execute the page next time. This saves CPU resources and speeds up ASP.NET response time. In a multi-server deployment, the best place to cache page output is within a distributed cache so it will be accessible from all Web servers. Fortunately, ASP.NET Output Cache has a provider-based architecture so you can easily plug in an in-memory distributed cache (see Figure 4).
Figure 4 Configure ASP.NET Output Cache for In-Memory Distributed Cache
<!-- web.config --> <system.web> <caching> <outputCache defaultProvider="DistributedCache"> <providers> <add name="DistributedCache" type="Vendor.Web.DistributedCache.DistCacheOutputCacheProvider, Vendor.Web.DistributedCache" cacheName="default" dataCacheClientName="default"/> </providers> </outputCache> </caching> </system.web>
Runtime Data Sharing Through Events
Another reason to consider using in-memory distributed cache in Azure is runtime data sharing. Applications typically do runtime data sharing in the following ways:
- Polling relational databases to detect data changes
- Using database events (such as SqlDependency or OracleDepedency)
- Using message queues such as MSMQ
These approaches all provide basic functionality, but each has certain performance and scalability issues. Polling is usually a bad idea. This involves many unnecessary database reads. Databases are already a scalability bottleneck, even without additional database events. With the added overhead of database events, databases will choke even more quickly under heavy transaction load.
Message queues specialize in sequenced data sharing and persisting events to permanent storage. They’re good for situations where the recipients might not receive events for a long time or where applications are distributed across the WAN. However, when it comes to a high-transaction environment, message queues might not perform or scale like an in-memory distributed cache.
So if you have a high-transaction environment where multiple applications need to share data at run time without any sequencing and you don’t need to persist events for a long time, you might want to consider using an in-memory distributed cache for runtime data sharing. An in-memory distributed cache lets you share data at run time in a variety of ways, all of which are asynchronous:
- Item level events on update, and remove
- Cache- and group/region-level events
- Continuous Query-based events
- Topic-based events (for publish/subscribe model)
The first three capabilities are essentially different ways to monitor data changes within the cache. Your application registers callbacks for each of these. The distributed cache is responsible for “firing the event” whenever the corresponding data in the cache changes. This results in your application callback being called.
When a specific cached item is updated or removed, there will be an item-level event fired. Cache- and group/region-level events are fired when data in that “container” is added, updated or removed. Continuous Query consists of search criteria to define a dataset in the distributed cache. The distributed cache fires events whenever you add, update or remove data from this dataset. You can use this to monitor cache changes:
string queryString = "SELECT Customers WHERE this.City = ?"; Hashtable values = new Hashtable(); values.Add("City", "New York"); Cache cache = CacheManager.GetCache(cacheName); ContinuousQuery cQuery = new ContinuousQuery(queryString, values); cQuery.RegisterAddNotification( new CQItemAddedCallback(cqItemAdded)); cQuery.RegisterUpdateNotification( new CQItemUpdatedCallback(cqItemUpdated)); cQuery.RegisterRemoveNotification( new CQItemRemovedCallback(cqItemRemoved)); cache.RegisterCQ(query);
Topic-based events are general purpose, and aren’t tied to any data changes in the cache. In this case, a cache client is responsible for “firing the event.” The distributed cache becomes something like a message bus and transports that event to all other clients connected to the cache.
With topic-based events, your applications can share data in a publish/subscribe model, where one application publishes data and fires a topic-based event. Other applications wait for that event and start consuming that data once it’s received.
Distributed Cache Architecture
High-traffic apps can’t afford downtime. For these apps running in Azure, there are three important aspects of in-memory distributed cache:
- High availability
- Linear scalability
- Data replication and reliability
Cache elasticity is an essential aspect of maintaining your in-memory distributed cache. Many in-memory distributed caches achieve elasticity and high availability with the following:
Self-healing peer-to-peer cache cluster: All cache servers form a cache cluster. A self-healing peer-to-peer cluster adjusts itself whenever nodes are added or removed. The more powerful caches form a self-healing peer-to-peer cache cluster, while others form master/slave clusters. Peer-to-peer is dynamic and lets you add or remove cache servers without stopping the cache. Master/slave clusters are limited because one or more of the designated nodes going down hampers cache operations. Some caches such as Memcached don’t form any cache cluster and, therefore, aren’t considered elastic.
Connection failover: The cache clients are apps running on app servers and Web servers that then access the cache servers. Connection failover capability is within the cache clients. This means if any cache server in the cluster goes down, the cache client will continue working by finding other servers in the cluster.
Dynamic configuration:Both cache servers and cache clients have this capability. Instead of requiring the cache clients to hardcode configuration details, cache servers propagate this information to the cache clients at run time, including any changes.
Caching Topologies
In many cases, you’re caching data that doesn’t exist in the database, such as ASP.NET Session State. Therefore, losing data can be quite painful. Even where data exists in the database, losing a lot of it when a cache node goes down can severely affect app performance.
Therefore, it’s better if your in-memory distributed cache replicates your data. However, replication does have performance and storage costs. A good in-memory cache provides a set of caching topologies to handle different types of data storage and replication needs:
Mirrored Cache: This topology has one active and one passive cache server. All reads and writes are made against the active node and updates are asynchronously applied to the mirror. This topology is normally used when you can only spare one dedicated cache server and share an app/Web server as the mirror.
Replicated Cache: This topology has two or more active cache servers. The entire cache is replicated to all of them. All updates are synchronous—they’re applied to all cache servers as one operation. Read transactions scale linearly as you add more servers. The disadvantage is that adding more nodes doesn’t increase storage or update transaction capacity.
Partitioned Cache: This topology has the entire cache partitioned, with each cache server containing one partition. Cache clients usually connect to all cache servers so they can directly access data in the desired partition. Your storage and transaction capacity grows as you add more servers so there’s linear scalability. There’s no replication, though, so you might lose data if a cache server goes down.
Partitioned-Replicated Cache: This is like a Partitioned Cache, except each partition is replicated to at least one other cache server. You don’t lose any data if a cache server goes down. The partition is usually active and the replica is passive. Your application never directly interacts with the replica. This topology provides the benefits of a Partitioned Cache like linear scalability, plus data reliability. There is a slight performance and storage cost associated with the replication.
Client Cache (Near Cache): Cache clients usually run on app/Web servers, so accessing the cache typically involves network traffic. Client Cache (also called Near Cache) is a local cache that keeps frequently used data close to your app and saves network trips. This local cache is also connected and synchronized with the distributed cache. Client Cache can be InProc (meaning inside your application process) or OutProc.
Deploying Distributed Cache in Azure
In Azure, you have multiple distributed cache options, including Microsoft Azure Cache, NCache for Azure and Memcached. Each cache provides a different set of options. These are the most common deployment options for a single region:
- In-Role Cache (co-located or dedicated)
- Cache Service
- Cache VMs (dedicated)
- Cache VMs across WAN (multi-regions)
In-Role Cache You can deploy an in-role cache on a co-located or dedicated role in Azure. Co-located means your application is also running on that VM and dedicated means it’s running only the cache. Although a good distributed cache provides elasticity and high availability, there’s overhead associated with adding or removing cache servers from the cache cluster. Your preference should be to have a stable cache cluster. You should add or remove cache servers only when you want to scale or reduce your cache capacity or when you have a cache server down.
The in-role cache is more volatile than other deployment options because Azure can easily start and stop roles. In a co-located role, the cache is also sharing CPU and memory resources with your applications. For one or two instances, it’s OK to use this deployment option. It’s not suitable for larger deployments, though, because of the negative performance impact.
You can also consider using a dedicated in-role cache. Bear in mind this cache is deployed as part of your cloud service and is only visible within that service. You can’t share this cache across multiple apps. Also, the cache runs only as long as your service is running. So, if you need to have the cache running even when you stop your application, don’t use this option.
Microsoft Azure Cache and NCache for Azure both offer the in-role deployment option. You can make Memcached run this configuration with some tweaking, but you lose data if a role is recycled because Memcached doesn’t replicate data.
Cache Service In a Cache Service, the distributed cache is deployed independent of your service, and offers you a cache-level view. You allocate a certain amount of memory and CPU capacity and create your cache. The benefit of a Cache Service is its simplicity. You don’t install and configure any of the distributed cache software yourself. As a result, your cache management effort is reduced because Azure is managing the distributed cache cluster for you. Another benefit is that you can share this cache across multiple applications.
The drawback of a Cache Service is your limited access. You can’t control or manipulate the cache VMs within the cluster like you would in an on-premises distributed cache. Also, you can’t deploy any server-side code such as Read-through, Write-through, cache loader and so on. You can’t control the number of cache VMs in the cluster because it’s handled by Azure. You can only choose among Basic, Standard and Premium deployment options. Microsoft Azure Cache provides a Cache Service deployment option, whereas NCache for Azure does not.
Cache VMs Another option is to deploy your distributed cache in Azure. This gives you total control over your distributed cache. When you deploy your application on Web roles, worker roles or dedicated VMs, you can also deploy the client portion of the distributed cache (the libraries). You can also install the cache client through Windows Installer when you create your role. This gives you more installation options like OutProc Client Cache (Near Cache).
Then you can allocate separate dedicated VMs as your cache servers, install your distributed cache software and build your cache cluster based on your needs. These dedicated cache VMs are stable and keep running even when your application stops. Your cache client talks to the cache cluster through a TCP protocol. For a Cache VM, there are two deployment scenarios you can use:
- Deploy within your virtual network: Your application roles/VMs and the cache VMs are all within the same virtual network. There are no endpoints between your application and the distributed cache. As a result, cache access is fast. The cache is also totally hidden from the outside world and, therefore, more secure.
- Deploy in separate virtual networks: Your application roles/VMs and the cache VMs are in different virtual networks. The distributed cache is in its own virtual network and exposed through endpoints. As a result, you can share the cache across multiple applications and multiple regions. However, you have a lot more control over your Cache VMs than a Cache Service.
In both Cache VM deployment options, you have full access to all cache servers. This lets you deploy server-side code such as read-through, write-through and cache loader, just like you would in an on-premises deployment. You also have more monitoring information, because you have full access to the cache VM. Microsoft Azure Cache doesn’t provide the Cache VM option, whereas it’s available in NCache for Azure and Memcached.
Microsoft plans to have its managed cache in general availability by July, which will replace the existing shared cache service. It will most likely not have an Azure portal presence and will require a Windows PowerShell command line to create and manage.
You can install NCache for Azure on dedicated VMs and access it from your Web and Worker Roles. You can also install NCache for Azure on Web and Worker Roles, but that’s not a recommended strategy. NCache for Azure doesn’t come as a cache service. Microsoft Azure also provides Redis Cache Service, which is available through the management portal.
Cache VMs Across WAN If you have a cloud service that’s deployed in multiple regions, consider deploying your Cache VMs across the WAN. The Cache VM deployment in each region is the same as the previous option. However, you have a situation with two additional requirements:
- Multi-site ASP.NET sessions: You can transfer an ASP.NET session from one site to another if a user is rerouted. This is a frequent occurrence for applications deployed in multiple active sites. They may reroute traffic to handle overflows or because they’re bringing one site down.
- WAN replication of cache: You can replicate all cache updates from one site to another. This can be an active-passive or active-active multi-site deployment. In active-passive, updates are replicated in one direction. In active-active, they’re bidirectional. The cache is kept synchronized across multiple sites through WAN replication, but keep in mind it consumes bandwidth.
Important Caching Features
When you use an in-memory distributed cache, it will handle a lot of data. A basic in-memory distributed cache only provides a hashtable (key, value) interface. An enterprise-level distributed cache may provide the following features as well:
Search features:Instead of always finding data based on a key, it’s a lot easier to search the cache based on some other logical data. For example, many distributed caches let you use groups and tags to logically group cached items. Many also let you search the cache through LINQ, which is popular for object searching in the .NET Framework. Some also provide their own Object Query Language (OQL), a SQL-like querying language with which you can search the cache. The ability to search a distributed cache based on attributes other than keys makes the distributed cache look and feel like a relational database. Figure 5 shows how you might execute such a search.
Figure 5 Configure a LINQ Search of a Distributed Cache
public IList<Customer> GetCutomers(string city) { // Use LINQ to search distributed cache IQueryable<Customer> customers = new DistCacheQuery<Customer>(cache); try { var result = from customer in customers where customer.City = city select customer; IList<Customer> prods = new List<Customer>(); foreach (Customer cust in result) { customers.Add(cust); } } return customers; }
Read-through and write-through/write-behind: Read-through and write-through handlers simplify your application code because you’ve moved a large chunk of your persistent code into the cache cluster. Your application simply assumes the cache is its data store. This is another way of reusing code across multiple applications.
The cache calls read-through whenever your application tries to fetch something that isn’t in the cache (this is called a “miss”). When a miss happens, the cache calls the read-through handler and it fetches the data from your database (see Figure 6). The distributed cache puts it in the cache and returns it to your application.
Figure 6 Read-Through Handler for a Distributed Cache
public class SqlReadThruProvider : IReadhThruProvider { // Called upon startup to initialize connection public void Start(IDictionary parameters) { ... } // Called at the end to close connection public void Stop() { ... } // Responsible for loading object from external data source public object Load(string key, ref CacheDependency dep) { string sql = "SELECT * FROM Customers WHERE "; sql += "CustomerID = @ID"; SqlCommand cmd = new SqlCommand(sql, _connection); cmd.Parameters.Add("@ID", System.Data.SqlDbType.VarCh; } }
The cache also calls your write-through handler whenever you update the cache and want it to automatically update the database. Your write-through handler runs on one or more cache servers in the cluster and talks to your database. If the write-through is called asynchronously after a delay and not as part of the cache update transaction, however, this operation is called write-behind. Write-behind improves application performance because you don’t have to wait for the database update to be completed.
Synchronize cache with relational database: Most data within a distributed cache comes from your application database. That means there are now two copies of the data, the master copy in the database and one in the distributed cache. If you have applications directly updating data in the database, but don’t have access to your in-memory distributed cache, you end up with stale data in the cache.
Some distributed caches provide database synchronization to ensure the cache never has stale data. This synchronization is either event-driven (using database notifications such as SqlDependency) or polling-based. Event-driven is closer to real time, but has more overhead because it creates a separate SqlDependency in the database server for each cached item. Polling is more efficient because one database call can synchronize thousands of items. But there’s usually a delay in synchronization, in order to avoid flooding the database with unnecessary polling calls. So your choice is between closer to real-time database synchronization or more efficient polling-based synchronization with a slight delay.
Handling relational data in a distributed cache: An in-memory distributed cache is a key-value object store, but most data cached within comes from a relational database. This data has one-to-many, one-to-one and many-to-many relationships. Relational databases provide referential integrity constraints and cascaded updates and deletes to enforce these relationships. The cache needs something similar as well.
CacheDependency lets you have one cached item depend on another. If the other cached item is updated or deleted, the original cached item is automatically deleted. This operates like a cascading delete. It’s useful for handling one-to-one and one-to-many relationships between objects in the cache. Some in-memory distributed caches have implemented this feature as well. Figure 7 shows how you would configure CacheDependency.
Figure 7 Use CacheDependency to Manage Relationships in the Cache
public void CacheCustomerAndOrder(Customer cust, Order order) { Cache cache = HttpRuntime.Cache; // Customer has one-to-many with Order. Cache customer first // then cache Order and create CacheDependency on customer string custKey = "Customer:CustomerId:" + cust.CustomerId; cache.Add(custKey, cust, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null); // CacheDependency ensures order is removed if Cust updated or removed string[] keys = new string[1]; keys[0] = custKey; CacheDependency dep = new CacheDependency(null, keys); string orderKey = "Order:CustomerId:" + order.CustomerId + ":ProductId:" + order.ProductId; // This will cache Order object with CacheDependency on customer cache.Add(orderKey, order, dep, absolutionExpiration, slidingExpiration, priority, null); }
Wrapping Up
Microsoft Azure is a powerful cloud platform and a scalable environment. An in-memory distributed cache can be an important component of this environment. If you’ve written your application in the .NET Framework, then you should consider using a .NET distributed cache. If it’s in Java, you have various Java-based distributed caching solutions. If you have a combination of .NET and Java applications, use a distributed cache that supports both and provides data portability. Most caches are totally focused on .NET or Java, although some do support both.
For PHP, Ruby, Python and other applications, you can use Memcached. This supports all these environments. Memcached isn’t an elastic cache and, therefore, has high-availability and data-reliability limitations. Either way, keep in mind that a distributed cache is a sensitive part of your production environment. Therefore, you must evaluate all available caching solutions in your environment thoroughly and select one that best meets your needs.
Iqbal Khan is the technology evangelist for Alachisoft, which provides Ncache distributed cache for .NET and Microsoft Azure. You can reach him at iqbal@alachisoft.com.
Jeremiah Talkar is a Microsoft Azure tech evangelist within the Microsoft Developer Platform Evangelism Corporate Team with 26 years of experience in product engineering, consulting and sales. Reach him at jtalkar@microsoft.com.
Thanks to the following Microsoft technical experts for reviewing this article: Scott Hunter, and Trent Swanson | https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/august/microsoft-azure-use-distributed-cache-in-microsoft-azure | CC-MAIN-2020-05 | refinedweb | 4,630 | 57.06 |
- Don't have an automated test framework set up? Take a look at a basic one I have for IntelliJ and Eclipse.
For this example, I will be setting up Selenium Grid a Windows 10 box, what I use at home. Feel free to set it up on whatever Mac or Linux/ Unix operating system you have. We aren't going to be doing a deep dive on any of the moving parts. That will come later. This article is focusing on the setup.
Directions can be found on SeleniumHQ's Grid 2 GitHub site:
0. Pre-requisites:0.1. Knowing how to start your Operating System's Command Line Interface:
- PC: If using Windows 10, in the "Search Windows" textbox next to the Start menu, type in: cmd
- Mac: Start the "Terminal".
- PC & Mac: Type in: java -version
1. Setup a Directory for Selenium Server
1.1. Start your Operating System's Command Line Interface:
- PC: Shortcut to Command Prompt: If using Windows 10, in the "Search Windows" textbox next to the Start menu, type in: cmd
- Mac: Start the "Terminal".
1.2. Go to the root directory in the Command Line:
- PC: Type in: cd \
- Mac: Type in: cd /
1.3. Create a folder called "drivers" at the root directory. For this example, this will be the home of Selenium Server.
- PC & Mac: Type in: mkdir drivers
2. Download Selenium Standalone ServerSet up the Selenium Server to run as a Hub.
2.1. Get the latest copy of the Selenium Standalone Server, and place it in a folder that is easily accessible.
- Go to the SeleniumHQ Download Page at
- The link to the current version to download selenium-server-standalone is listed in the Selenium Standalone Server paragraph. At the time of this blog the download version is: 2.53.1
- Right click on the link and select "Save link as..."
- Save this executable Jar File somewhere easy to remember for now. I created for this example a directory called "drivers" on my C: drive and placed selenium-server-standalone-2.53.1.jar there.
2.2 Verify that the file has been created.
- PC: The command "dir" shows the directory listing. Type in: dir \drivers
- Mac: The command "ls" shows the list of files in directory. Type in: ls /drivers
Make sure that the file listed is: selenium-server-standalone-2.53.1.jar
3. Start the Selenium Server
3.1. Go to the directory where Selenium Server is located:
- PC: Type in: cd \drivers
- Mac: Type in: cd /drivers
3.2. Start the Selenium Server:
java -jar selenium-server-standalone-2.53.1.jar -role hub
- Success: Message: Selenium Grid hub is up and running
- Failure: Error messages, plus a huge stack trace and a help file.
Did you get a message such as Java.net.BindException: Address is already in use? That's what happened to me. I may have accidentally double-clicked multiple instances of Selenium Server when writing this documention.
By default, the Selenium Server runs on port 4444. You can shut down a Selenium Server that failed by running:
java -jar selenium-server-standalone-2.53.1.jar -role hub -port 4445
3.3. Verify that the Selenium Server has started:
- Open up your favorite browser and go to:
- Check that you see:
"Find help on the official selenium wiki : more help here
"default monitoring page : console"
- Select the link to the console.
4. Setup a Selenium Node
4.1 Start Selenium Node
- Open a new Command Line Interface, go to the drivers directory, and enter:
java -jar selenium-server-standalone-2.53.1.jar -role node -hub
You will see a message that the node is ready for use!
Let's verify that:
Note that the Hub is running on 192.168.1.5, port 5555 ()
These are all the browsers on the machine you are using at the moment. Since I'm using as an Operating System Windows 10, that is what is listed.
Disregard the "Remote Control (legacy)" browsers those are for an earlier version, Selenium RC.
We can spin up three types of browsers for our automated test framework. Hover your cursor over them to see the browser names. We will need them later.
Hook Up Selenium Grid with Your Automation FrameworkWhat? Don't have an automated test framework ready to go? Not sure of what one is? Follow one of these links to walk you through setting up a new Gradle Java product, the Java Gradle plugin, setting up dependencies, creating browser tests in Firefox and Chrome, and how to match values using Hamcrest:
@Test public void test_FirefoxNavigatesToLoginPage() throws Exception { driver = new FirefoxDriver(); driver.get(""); assertThat(driver.getTitle(), is(equalTo("The Internet"))); }
The test:
- Goes to Dave Haeffner's test site,
- Opens up a new Firefox browser on your local machine
- Asserts that the title is "The Internet".
If we make the driver we are using an instance of RemoteWebDriver instead of just WebDriver, we get a lot more flexibility. You can open up browsers on other environments than on your local machine. If you are on a Mac, you can set up and use browser nodes on a PC or a Linux machine in your automated tests. All you would need to do is pass along the location of your Selenium Hub (in this case, "").
You can also set up, once you have the browser nodes, the corresponding Desired Capabilities, setting up the:
- Browsers: Chrome, Firefox, MS Edge, Android, etc.
- Browser name, what you want to call the browser configuration you are setting up.
- Platform, whether generic Windows, Win8, Win10, generic Mac, Mountain Lion, El Capitan, etc.
Remember, unless you are using Sauce Labs preset nodes, you need to have a machine with the pre-existing capabilities.
See for a complete list.
Let's do the same test again, but this time, call a RemoteWebDriver in a setup method and handle the desired capabilities there.
public class LoginPageTest { private RemoteWebDriver driver; @Before public void setUp() throws Exception { DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setBrowserName("firefox"); capabilities.setPlatform(Platform.WIN10); driver = new RemoteWebDriver(new URL(""), capabilities); } @Test public void test_FirefoxGridNavigatesToLoginPage() throws Exception { driver.get(""); assertThat(driver.getTitle(), is(equalTo("The Internet"))); } @After public void closeBrowsers() throws Exception { driver.quit(); } }... And the test passed!
Coming up in the next few weeks, now that we have the basics, we'll build on that:
- We covered the basics of Docker, and the basics of Selenium Grid. Next up: We combine the two!
- We add Selenium Grid to the automated testing framework w/ Gradle we started building in IntelliJ and Eclipse, refactoring the DesiredCapabilities into its own library.
- We add multi-threading to the automated test framework, so we can run tests in parallel.
Happy Testing, and have a Happy Fourth of July!
-T.J. Maher
Sr. QA Engineer,
Fitbit-Boston
// QA Engineer since Aug. 1996
// Automation developer for [ 1.5 ] years and still counting! | http://www.tjmaher.com/2016/07/setup-of-selenium-grid-for-beginners.html | CC-MAIN-2020-29 | refinedweb | 1,153 | 57.27 |
Business Processes and Rules: Siebel eBusiness Application Integration Volume IV > Data Mapping Using Scripts >
EAI Data Transformation.
Setting Up a Data Transformation Map
- Start Siebel Tools.
- Choose a locked project.
- Create a new business service.
- Choose the CSSEAIDTEScriptService class for the business service.
- Double-click the Business Services Methods folder and add the method Execute.
- Select the Business Service Method Arg folder and add the arguments for the Execute method. For a list of arguments and their description, see DTE Business Service Method Arguments. The arguments to include are:
- MapName
- An input argument. Select one of SiebelMessage, XMLHierarchy, or MIMEHierarchy as the argument name, based on the type of input.
- An output argument. Required if the output object is a different type than the input argument. Select one of SiebelMessage, XMLHierarchy, or MIMEHierarchy as the argument name.
NOTE: If the input and output types are the same then the same argument entry is used for both.
- OutputType
- InputType(Optional). This is required only when passing the business service input property set to the map function without interpretation. This is done by specifying the InputType as ServiceArguments. DTE business service
- Choose the Business Service object and select the business service you want to contain the transformation map.
- Right-click to display the pop-up menu.
- Choose Edit Server Scripts and choose eScripts as the scripting language if you are prompted to select scripting language.
- In the (declarations) procedure of the (general) object, add the line:
#include "eaisiebel.js"
- In the Service_PreInvokeMethod function of the service, change the function to the following:.
- The MethodName must be Execute and is used by Siebel Workflow. The name of your function is the name you supply for the MapName argument to the Execute method.
- Inputs is the input message from workflow containing service arguments—for example, MapName and Output Integration Object Name—and the integration message to be transformed. Outputs is the argument used to return data—for example, Siebel Message. MapName specifies the map function to be executed and must be the name of one of the functions you defined in the business service. For examples of DTE Business Services, see Siebel eBusiness Connector for Oracle Guide. | http://docs.oracle.com/cd/E05554_01/books/EAI4/EAI4_DataMapUsScripts3.html#wp112146 | crawl-003 | refinedweb | 363 | 58.18 |
This document shows you how to import a real 3rd party project built with the
Ant tool into NetBeans IDE as a free-form
project. The project that has been selected to demonstrate free-form project
functionality is the PMD tool. This
tutorial will show not only how to import the project but also how to change
the build script to better utilize what NetBeans project infrastructure can
offer. This tutorial uses information available in Advanced
Free-Form Project Configuration and if you are familiar with this document
it will be easier for you to finish the tutorial.
Expected duration: 20 minutes
This tutorial assumes you have some basic knowledge of Ant and XML, and that
you know basics about how projects in NetBeans IDE work.
Before you begin, you need to install the following software on your computer:
The following topics are covered in this document:
PMD is a handy tool for programmers that detects potential problems in Java
source code. You can download PMD from pmd.sourceforge.net
as a
Zip source distribution or check it out from anonymous CVS. This tutorial
assumes that you are using zipped sources distribution of PMD 3.5. If you want
to use sources checked out from PMD source repository then follow instructions
on sourceforge.net to get the PMD sources.
It's really easy using CVS support in NetBeans 5.0. Described instructions
can be used for 3.5 sources and for trunk sources as well. This tutorial uses
the 3.5 version because there were compilation errors and execution errors in
trunk sources at the time the tutorial was written.
The goal of this exercise is to perform the initial import of the project's
build script to the IDE and set up all required settings for basic IDE operations.
Now that you have created the project, let's examine it.
The project node contains both source roots and also the build script. The
names of the nodes are a little strange - src and regress/test.
We should change them to something nicer. Open Project Properties from project's
contextual menu. You will see two tables with source roots location and labels.
You can change the label to whatever you want. Double click the label and
change src to Source Packages and regress/test to Test Packages.
To set the classpath correctly we will need to look what is in the build
script - by basic observation we find out that compilation is done with following
classpath definition:
<property name="dir.lib" value="lib\"/>
...
<path id="dependencies.path">
<pathelement location="${dir.build}"/>
<fileset dir="${dir.lib}">
<include name="jaxen-1.1-beta-7.jar" />
<include name="jakarta-oro-2.0.8.jar" />
<include name="xercesImpl-2.6.2.jar" />
<include name="xmlParserAPIs-2.6.2.jar" />
</fileset>
</path>
The same classpath is used for compilation of tests, because everything
is compiled together.
The classpath set up in this step is used for IDE features such as code
completion and by no means affects the classpath used for compilation of the
project.
When examining the project build script you will actually realize that some
targets that you mapped to IDE actions when creating the project are not correct.
The Build action target is not compile but in fact jar.
The Clean action should not be mapped to the clean target but delete.
And the Run Project target is in fact called pmd. This can be easily
fixed:
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask" classpathref="dependencies.path"/>
Another method is to add pmd-3.5.jar to the additional classpath
entries for Ant. Choose Tools > Options, then select Miscellaneous >
Ant, click the Manage Classpath button, and add pmd/lib/pmd-3.5.jar.
The JAR file is only available after the project is built, of course.
The better method is to use explicit classpath when defining the task, because
then the build script is more portable. And in this particular case it's also
better because if you add pmd-3.5.jar to Ant classpath on Windows
then it's not possible to run Clean Project since the JAR file is be locked
by the OS.
But there is still one minor problem with Run Project action. The build
script points to the absolute location of some not existing source file in
the bin folder. A simple fix is to replace the absolute path in pmd
task with bin. The fileset inside the pmd task then
should look like this:
<fileset dir="bin">
<include name="Foo.java"/>
</fileset>
And you also need to create missing class in pmd/bin folder:
public class Foo {
private static int FOO = 2; // Unused
private int i = 5; // Unused
private int j = 6;
public int addOne() {
return j++;
}
public void doSomething() {
int i = 5; // Unused
}
private void foo() {} // unused
private void bar(String howdy) {
// howdy is not used
}
}
Note: The Foo class is based on comments in rulesets/unusedcode.xml.
Usually, it's useful to make the run target depend on the build target.
It's not the case in PMD's build script, so if you want run target to be executable
even when project is not built, add depends="jar" to the pmd
target definition.
Now you can finally run the project and you will get the pmd-3.5/rpt.html
file in the project folder showing problematic parts of the Foo class:
Now your project is set up and you can execute all basic project related
actions: Build Project, Clean Project, Generate Javadoc for Project, Run Project,
Test Project and Clean and Build Project.
Having correctly set up project outputs is a very important part of free-form
project configuration. It's important for debugging tasks, for fast background
classpath scanning, and for using project products as libraries for other
projects.
Each source root should have its own build product(s), either a folder or
JAR file. From observation of the compile and jar targets
in the PMD build script you can find out that the Source Packages are built
into the build folder along with test classes and the final JAR file
is lib/pmd-3.5.jar. In order to view Javadoc in projects that depends
on the PMD free-form project you also need to set the Javadoc output. PMD
build script produces Javadoc documentation into folder docs/apidocs
- according to the javadoc target.
Now the project is set up and ready to be used in IDE. In following chapters
I will show how to get even more from the IDE.
Each good project should have tests and the PMD project has a number of tests
that can be executed with the Test Project command. But if you run this command
you will see that output doesn't look as nice as it looks when running standard
NetBeans projects.
This can be fixed too. First, you need to modify target names to comply with
simple convention - the name must start with test, which can be followed
by a dash or period and then anything you want (e.g. test-server or
test.server). Alternatively, you can name the target run-tests.
The other thing is that JUnit tasks use various formatters to print various
types of output and the NetBeans JUnit module requires a particular combination
of formatters to show nice output. The JUnit tasks in PMD build script use the
following formatter:
<formatter type="plain"/>
<formatter type="xml"/>
<formatter type="brief" usefile="false"/>
And you will get very nice display of JUnit test execution that updates itself
when tests are running, as in the following image:
3rd party projects have also special targets that are project-specific and
there can be no mapping to standard IDE commands. But that's not a problem for
a free-form project - you can map any target to a command which is then available
in project context menu.
The PMD project contains a couple of such targets that might be candidates
for adding them to the context menu, for example targets for uploading build
products to a web server or targets for running partial test suites.
The context menu for the PMD free-form project then might look like this:
Note: Upload actions are just an example, they require external
executable files and appropriate write access.
When developing a larger project you might want to be able to run compilation
only for a selected file or group of files, execute a single file, or debug
a project or even a single file. All this is possible, although it requires
some Ant knowledge. The PMD project is not a good example to show all of the
commands that I just mentioned but I can show how to set up at least some of
them.
There is support in the IDE for generating additional build scripts the for
Compile File action and for the Debug Project action. All details about setting
up NetBeans-specific actions are in the document Advanced
Free-Form Project Configuration.
The target in the generated build script is called when you invoke the Compile
File command on one or more files from a single source root folder. If you
have already correctly setup everything the script does not require any modifications.
Just to check - the compilation target should look like this:
<target name="compile-selected-files-in-src">
<fail unless="files">Must set property 'files'</fail>
<mkdir dir="build"/>
<javac destdir="build" includes="${files}" source="1.5" srcdir="src">
<classpath path="lib/jakarta-oro-2.0.8.jar;lib/jaxen-1.1-beta-7.jar;lib/xercesImpl-2.6.2.jar;lib/xmlParserAPIs-2.6.2.jar"/>
</javac>
</target>
The destination build directory must be created in case the target
is called after a clean. The source dir must point to the src folder,
the includes attribute of the javac task must contain the
property ${files}, and the classpath must be the same as the classpath
for compilation in main build script.
The other file that has been modified and is opened in the editor is project.xml.
It contains the actual mapping of the Compile File action to the appropriate
Ant target.
There is no support for generating an Ant target for the Run File command.
It must be created by hand.
<action name="run.single">
<script>nbproject/ide-file-targets.xml</script>
<target>run-selected-file</target>
<context>
<property>runclass</property>
<folder>src</folder>
<pattern>\.java$</pattern>
<format>java-name</format>
<arity>
<one-file-only/>
</arity>
</context>
</action>
<target name="run-selected-file" depends="jar">
<fail unless="runclass">Must set property 'runclass'</fail>
<java classname="${runclass}" classpathref="dependencies.path" fork="true"/>
</target>
<import file="../${ant.script}"/>
The Run File command is now enabled on any file under the Source Packages
folder. Of course, it makes sense to run this command only on classes with
a main method.
The Debug Project command is normally pre-generated when invoked for first
time, but it requires a correctly configured run target in the main script
using the java task. This is not the case in the PMD project. Hence,
we have to create a Debug File action that is enabled on single files and
not on the project itself.
<action name="debug.single">
<script>nbproject/ide-file-targets.xml</script>
<target>debug-selected-file</target>
<context>
<property>debugclass</property>
<folder>src</folder>
<pattern>\.java$</pattern>
<format>java-name</format>
<arity>
<one-file-only/>
</arity>
</context>
</action>
<target name="debug-selected-file" depends="jar" if="netbeans.home">
<fail unless="debugclass">Must set property 'debugclass'</fail>
<nbjpdastart name="debugclass" addressproperty="jpda.address" transport="dt_socket">
<classpath refid="dependencies.path"/>
</nbjpdastart>
<java classname="${debugclass}" fork="true">
<jvmarg value="-Xdebug"/>
<jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
<classpath refid="dependencies.path"/>
</java>
</target>
The Debug File command is also enabled on all files under the Source Packages
folder and it makes sense to invoke it only on executable classes.
The PMD project is now fully integrated in IDE and the user can utilize almost
all actions that are available for NetBeans native projects.
There are some general rules and good practices that, if followed, make it
easier to integrate 3rd party projects into the IDE as free-form projects:
To send comments and suggestions, get support, and keep informed on the latest
developments on the NetBeans IDE J2EE development features, join the
nbusers@netbeans.org
mailing list.
Bookmark this page | http://www.netbeans.org/kb/articles/freeform-import.html | crawl-002 | refinedweb | 2,067 | 54.32 |
The simplest C++ program is shown here:
#include <iostream> // The entry point of the program int main() { std::cout << "Hello, world!n"; }
The first point to make is that the line starting with // is a comment. All the text until the end of the line is ignored by the compiler. If you want to have multiline comments, every line must start with //. You can also use C comments. A C comment starts with /* and ends with */ and everything between these two symbols is a comment, including line breaks.
C comments are a quick way to comment out a portion of your code.
The braces, {}, indicates a code block; in this case, the C++ code is for the function main. We know that this is a function because of the basic format: first, ... | https://www.oreilly.com/library/view/beginning-c-programming/9781787124943/92cc5088-1331-48a4-8852-0366e091d840.xhtml | CC-MAIN-2019-04 | refinedweb | 132 | 82.24 |
So equations are quite simple;
You have a number, an operator, and another number.
Simple… Until you try and pass in the variable from another script and try to follow BEDMAS or PEMDAS or whatever else you want to call the order of operations.
So I did a thing for a group prototype to try and handle it, using floats and strings
You can start off with a simple method
float answer; void EquationSolver (float _numOne, float _numTwo, string _op) { }
The first issue: passing an operator.
I searched for ages trying to find something but couldn’t find anything.. So I found the solution was to use a string and do stuff from there.
So here’s how it would basically look :
float answer; void EquationSolver (float _numOne, float _numTwo, string _op) { // goes through all the operators one by one if (_op == "/") answer = _numOne / _numTwo; else if (_op == "*") answer = _numOne * _numTwo; else if (_op == "+") answer = _numOne + _numTwo; else if (_op == "-") answer = _numOne - _numTwo; }
This works really well if you have an equation for only 2 numbers and an operator. But the you may as well just have it in one line anyway!
float answer = _numOne * _numTwo;
So what if you had a list of numbers, and a list of operators like us then? Well I started with the same basic idea as before, but using a list of the gameObjects we added, instead of separate floats.
using System.Collections.Generic; float answer; void EquationSolver (List <GameObject> _list) { // goes through the list until it finds a new operator // when it finds one, it goes one gameObject before, and one after in the list for (int i = 0; i < i < _ops.Count - 1; i++) { if (_list [i].GetComponent <Operator> ().GetOperator == "/") answer += _list [i-1] / _list [i+1]; else if (_list [i].GetComponent <Operator> ().GetOperator == "*") answer += _list [i-1] * _list [i+1]; else if (_list [i].GetComponent <Operator> ().GetOperator == "+") answer += _list [i-1] + _list [i+1]; else if (_list [i].GetComponent <Operator> ().GetOperator == "-") answer += _list [i-1] - _list [i+1]; } }
Now this had two problems (apart from being difficult to read).
1) It would still ignore BEDMAS and do them in the order in which they were added.
2) It would ignore the fact that some of the numbers had been used already, and used their unchaged state, giving an incorrect answer
Looking pretty bleak atm.. But fear not, I came up with a solution!.. Not overly pretty, but effective. Enter my new found joy in Dictionary’s! The coding one, not the word one.
The concept of a Dictionary (if you’ve never used one before) is basically a more advanced list. Instead of having a zero index for holding values, you have a key which can be an int, a float, or a string (possibly others, but I’m not sure).
I also used a localized string array for the operators so it would always perform the equation in the proper order of operations.
So here’s what I did for the final outcome, making it a public int so it could be called from anything and give back a direct answer:
using System.Collections.Generic; float answer; Dicitonary <int, float> previousCalculation; string [] operators = new string [] {"/", "*", "+", "-"}; public int FinalAnswer (List <GameObject> _list) { // creates a new dictionary and sets the answer to 0 at the start of the equation // this makes sure that it doesn't have anything left from previous equations calculated = new Dictionary <int, int> (); answer = 0; // starts a for loop for each of the operators in the operator list foreach (string _op in operators) { // I could have use a foreach loop again, but this way allows us to select one before and one after for (int i = 0; i < _list.Count - 1; i++) { // checks the gameObjects for the operator we're currently looking for if (_list[i].GetComponent <Operator> ().GetOperator () == _op) { // we create some temporary floats that will be used in the next part of the calculation float a = 0; float b = 0; // checks if the number has already been used // if it has use the calculated number instead of the original one if (calculated.ContainsKey (i-1)) a = calculated [i-1]; else a = _list [i-1].GetComponent <Number> ().GetValue (); // does the same as above, but for the second number if (calculated.ContainsKey (i+1)) b = calculated [i+1]; else b = _list [i+1].GetComponent <Number> ().GetValue (); // performs the various operations based on which operator we are checking if (op == "/") answer = a/b; else if (op == "*") answer = a*b; else if (op == "+") answer = a+b; else if (op == "-") answer = a-b; // will replace the calculated value, or add a new one if there is not one if (!calculated.ConatinsKey (i+1)) calculated.Add (i+1, answer); else calculated[i+1] = answer; // will do the same as above but place it backwards not forwards in the list if (!calculated.ConatinsKey (i-1)) calculated.Add (i-1, answer); else calculated[i-1] = answer; } } } return answer; }
And there you have it! A working equation solver that follows BEDMAS and is dynamic in which operators or numbers you pass through.
Not altogether pretty, but it works!
Feel free to use it or adapt it if you want. But I can’t imagine to many circumstances where this would even be used haha.
EDIT: you can now download a prototype build of ADD for free
1 Pingback | https://dannyhaddow.com/2015/11/19/equation-programming/ | CC-MAIN-2018-47 | refinedweb | 893 | 59.23 |
This is the master repository of the npm
npmvc module.
The main goal of this module is to add more flexibility and modulairity within the use of the combination of Node.js and the PureMVC framework. The module enables the aggregation of PureMVC classes in a local file structure or/and in seperated modules.
It adds an
include method on top of the official multicore PureMVC JavaScript library (currently version 1.0.1). This method is based on the node.js
require method and is added to the puremvc namespace. (See API specs below).
You can use the
include function to include dependecies that are located local or in other npm modules. Class files are wrapped the node.js module.export style (see Creating external class files).
npm install npmvc
When installed you can use it like this
var puremvc = ;puremvc;puremvc;puremvc;// make instance of ApplicationFacade and trigger start commandvar app = testApplicationFacade;appstart;
module {// use include te aquire dependency class files;// ---> now you can use puremvc.define to define class/*** @class test.ApplicationFacade* @extends puremvc.Facade*/puremvc};
This module adds some exra methods on top of the
puremvc root object:
path [string] Sets the source dir for all include's, It uses this for includes on all directory levels. So when you include a dependencie in say
model/MyProxy you have to reference
model/vo/MyVo by using the path up from the sourceDir, not relative to the folder the file is in:
puremvc.include("model/vo/MyVo");
If you have to hack this, you can use tempPath, the second param of puremvc.include. See below.
Also note that if you do not set the sourceDir it will default to
process.cwd() (the directory where you started the main node file).
Returns any value, but mainly use for return the reference to the classlets constructor from
puremvc.define.
path [string]
Path to puremvc class, relative from path set by
puremvc.setSourceDir
tempPath [String]
This overides the sourceDir. An include of
MyVo in class
model/vo/MyVo would look like this:
puremvc.include("vo/MyVo",__dirname);
callback [function] You can use a callback, but you have to trigger it in the aquired class file.
You can include a class in an other npm module if the file is not equal in the context of your current sourceDir path. So when you want to load the class
SomeClass in the module
my-npm-module then do not use tempPath but use:
puremvc.include("my-npm-module/path/to/SomeClass");
returns the current source directory, root of puremvc classes.
This is one way to create puremvc modules that harmonize with npm (node package manager).
in package.json add a puremvc object, and provide a namespace, sourcedir (relative from module root dir), and an array with initial includes. The main property has to point to 'index.js'.
{"name": "somemodule","version": "1.0.0","description": "Just a module","main": "index","puremvc":{"namespace":"com.domain.somemodule","sourcedir":"./src/","include":["mediator/SomeMediator","model/SomeProxy"]},"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC"}
for index.js use this code:
module {puremvc;}
Now in any point in your npmvc application you can import a module by using the include method:
module {;puremvc;}
boolean (default:false)
This option only works on macosx darwin. In a case insensitive environment typo's can be hard to find because node.js on a mac does not throw an error when loading case typo's in filenames. When validateIncludePaths is set to true it will warn when a file that is included has a case typo in it's path.
Note that in a other environment than 'darwin', npmvc will ignore this option and outputs a warning about that when set to 'true'.
Set this option before calling the include method. Example usage:
var puremvc = require("npmvc");puremvc.validateIncludePaths = true;
boolean (default:true)
This option only works on macosx darwin. It suppresses throwing case insensitive errors. It is mainly for testing, so you can ignore it basicly. | https://www.npmjs.com/package/npmvc | CC-MAIN-2017-47 | refinedweb | 668 | 65.83 |
I had the chance to go to the Alt.net Seattle open spaces this past weekend and it was a great experience. First of all I wanted to publicly thank my company for sending seven of us to the conference. Part of the reason for taking a position with Headspring systems is that I felt that their values for software development aligned with mine. Giving us the opportunity to go to this event and get outside of the Austin echo chamber was really good for us to get some perspective on what, how, and why we are doing what we are doing.
Open Source in .Net
What I took from this session, is that many companies are still scared to use open source projects. There is still a lot around licensing that scares software managers, CTOs, and corporate lawyers. In the past I really tried to stay away from using any of the Microsoft Open Source licenses, but as I started to think about why I do this, I really think my logic was flawed. I wanted to distance my projects from being associated with Microsoft. That is a really stupid thing for me to do considering, all of the open source projects that I run or participate in are written in .Net technologies and target .Net developers as the users of my projects. So, if there is a developer who wants to use my projects and they are in a very conservative company that is afraid of open source, it seems that the company would most likely be comfortable with a Microsoft Open Source license. As a result, if the license for any of my projects are preventing a company from adopting my project, I am willing to change the license. I plan on putting this on the homepage of each project so that no-one has the license as an excuse for adoption.
One of the action items that came out of this session was that Scott Hanselman was going to track down someone who could put together a License Matrix so that developers, like me who do not understand all the legalese, would be able to see which licenses are equivalent as well as where they fall on the scale from scary viral to friendly do what ever you want. This will really help open source project owners to make an educated decision about which license to pick.
Talking with others.
I had a chance to sit down and share some of the things I am doing and see what others are doing. Aaron Jensen is doing some really cool work with the Spark view engine. After seeing some more complex work on top of Spark, I am convinced that there will realistically be two view engines that are used with the ASP.Net MVC framework. The Aspx engine and the Spark engine. While the other view engines are interesting and some people are using them, I just do not see the others really taking hold and getting wide spread adoption. I also think that as Spark gets more visibility that we could see some features of Spark show up in the aspx view engine. I really like the ability to add a foreach attribute inside of an html element to loop through a collection. It really cleans up a view compared to the aspx equivalent.
I spent some time with Alan Stevens and we talked a lot about Test Driven Development and some of the tools and ways to make using that practice frictionless in Visual Studio. I walked through my Resharper Plugin and showed him some options. I also got a chance to explain how frustrated I am with Resharper and the way that their API changes with every minor release. It is extremely painful to maintain a resharper plugin. That being said, I will release a new version of the TDD Productivity Plugin that will work with Resharper 4.5. By the way … I know I am bad at naming my projects so if someone has a better name for the plugin… comment on this post or email me or twitter me. I will be more than willing to change the name.
I spent some time talking with John Lam about Iron Ruby. After this conversation, I am looking into how I can host IronRuby in a Visual Studio add in so that I can add more productivity enhancements. The main sell for me is that in order to develop visual studio add-ins I cannot work using test driven development. This is because so much of the Visual Studio API objects have property dictionaries, and the only way to figure out what needs to be done is to debug into visual studio and poke around in the object model until I can find the property I am looking for. This in itself is painful because recompiling an add in and debugging it requires starting up a second instance of visual studio, which is a 30-35 second process. I am hoping that with a Ruby host add in, I can just run inside visual studio and interactively inspect the object model and produce a nice dsl (Domain Specific Language) for adding productivity scripts. I guess you can say that the macro engine does this now but writing in VB script is something I would like to put behind me.
NGems / ROCKS
There was talk about some existing work being done to provide a Gems like experience for delivering extensions to the .Net framework. Gems is a feature in ruby where any developer can create a class or package, register that package on a central server so that all other Ruby developers can than use the Gem command to download the package to their machine. It pulls down all the files and correct versions of any dependencies that are needed as well. The thinking is that if we had this in the .Net space a developer could pull down a project, say MvcContrib and they could get the latest version or a specific version. They would not have to go to our project site to get it and they would not need to pull down some of the dependencies individually. I really like the idea of getting this working. There has been a lot of talk about doing this in the past Alt.Net events, but at the end of the day everyone is busy and cannot spare the time to get this implemented. The group decided to try to reuse as much of the existing Ruby infrastructure as possible, this means we could produce the package files in the ruby format and even use Iron Ruby to pull down these packages.
We talked more about how we can do this and get something that is usable as quickly as possible and the solution we that came up was to write a small .Net wrapper (code name Rocks) and that would load up iron ruby and call the gems command to pull down assemblies from the internet. Everyone in the room was pretty hard core command line guys so the focus was to to this for the command line. I would be more than willing to make a VS add into work with this once we get the command line running. I am exited for this.! I could also tie in a “Remote Reference” feature to my Solution Factory add in, which would be really cool.
Code Camp Server Code Review
We had a session that walked through the code camp server source code. We were looking for feedback on what was good , but more importantly what was bad or hard to understand. Here are my raw notes:
- In the Conference domain object it seemed like having the Attendees collection have specific Add and Remove methods and not exposing the actual collection to the rest of the domain seemed to be unnecessary. There was a suggestion to just make the Attendees collection a public field and get rid of the Add and Remove methods.
- The lock implementation in the dependency registrar module has a bug and was not implemented correctly. see file DependencyRegistrarModule.cs line 30
- General application style: The conventions are hard to understand as a total collection. When each convention is explained it is pretty easy to understand individually, but at first glance all of the conventions together are hard / overwhelming to digest. The suggestion was to pull back some to be more inline with the conventions of the base framework.
- There were some questions about using lambdas in our UrlHelpers to create strongly typed links to the controller actions. Code that looks like c => c.Index(null,null) is really strange. The null arguments in method parameters really bothered some of the reviewers. The counter argument was that this is a limitation of the current c# language and that since this syntax is used in some of the Mocking frameworks that it is just something developers are getting used to seeing. (I am looking at some ways to use T4 Templates to possibly generate extension methods that would be able to clean up the syntax and avoid the pain of having to maintain special code just to get the strong typing with a nice syntax)
- In the view pages where forms are rendered. The suggestion was across the board to make the inputFor to be intention revealing. Everyone would rather see something like TextBoxFor or CheckBox for. For me the part that is tough is that the InputFor made it really easy to generate these view using the scaffolding that comes in RC1. I think we can still support this suggestion, we will just have to move some logic from the InputBuilders classes into the T4 new item templates.
- Expect that the html forms elements in the view.. cant see the textbox, version radio buttons.
-would like to see a more obvious list of the input elements.
- There was a comment that the short one/two line methods in controllers seems like a waist.. it was suggested taht pulling the dependency up into those methods would be better. We actually than showed a controller that had 10 + actions and than the value in having small action methods started to become a good thing. Than we actually pulled up the code from one of the Mapper services into the controller that we were looking at and it became a total mess in the class file because that required brining up 5 additional private methods which made the controller class break the Single Responsibility Principle. It was a great discussion and once we stopped talking about the possibilities and just tried implementing these suggestions on the projector we really could really make some good decisions.
I wanted to thank everyone who participated in this review, it was great to get your points of view and as a result we will make changes to address these concerns and have a better reference for line of business MVC Applications.
Abstract Test Assertions
I hosted this session as a way to address a problem that came up in the MvcContrib.TestHelpers library. In that library we have some extension methods that make testing the URL Routing features in the MVC framework much clearer to read than without the extensions. This could be called a DSL around route testing. The problem that we have is that our implementation uses NUnit assert statements and some developers want to use this DSL with other testing frameworks. I went into this session thinking that would could produce some sort of abstract class or interface that each developer that wanted to use the DSL would have to implement and wire up to our library.
This session took a little bit to get started but a few people came in a little late and we even had some people participating with the Live internet feed.
The result of this session was that we determined the easy way to become Test Framework independent was to create a MvcContrib.TestHelper.AssertException and that instead of calling into a test framework our DSL would just through an expectation with an informative message just like the test frameworks do. Charlie Poole ,the nunit developer, said that this is how the unit test frameworks integrate with the mocking frameworks. The recognize that when an exception is thrown and they know the namespace of the exception comes from the mocking framework , nunit does a little magic to remove the call stack frames that are in the mocking framework.. That then creates a good experience for the developers using the two tools. He said that if the unit test framework maintainers wanted to provide a better experience than they would treat the MvcContrib.TestHelpers namespace the same way.
As a result of this session, I am going to implement this feature this way and that means that we will remove the reference to nunit from the TestHelpers assembly. I think the next step after this would be to contribute patches to the open source test frameworks and I think that we will just have to live with MSTest being an experience that will not be as good as the other test runners. I like the solution and I am going to look at the nBehave project and see if I can do something similar their.
Demo of Macro and Micro Code Generation.
I had a chance to demo my to Visual Studio add ins Solution Factory and Flywheel to a number of people. I got some really good feedback about the tools and was encouraged to blog about them more. So here we go.
Solution Factory – This is a visual studio add in that will export an entire solution as well as its parent and sibling directories into a Visual Studio Project Template. The reason it pulls along the parent and sibling directories to the solution folder is that most of the developers that I have talked to put all of their project dependencies in a folder that is a sibling of the solution folder and than all the projects reference those assemblies using a relative path. This means that the template produced by solution factory follows the Flat Tire Principle, which is: When you have to perform maintenance our your code, All of your dependencies and tools are located in your solution Trunk.
This is a tool that Headspring systems will use to turn the project format that we use in our Agile Boot Camp, into a template that our attendees can easily create a new solution using all of the pieces need to get up and running fast. My hope with this project is that other companies and projects could use this add in to easily share their solutions. I could see nServiceBus , S#arp Architecture and Fubu using this tool to easily create the File –> New Project experience. I am hoping that the development community will be able to start sharing more knowledge and make this process frictionless for newbie. You can get Solution Factory by going to the project site:
FlyWheel – This is an add-in that was inspired by the new MVC New Item T4 templates. The idea behind this add-in is that instead of Generating Code from a database schema,Flywheel will generate new files based off an existing Code Class in your project. I also wanted to solve the problem of really making it easy to create multiple files at once. So when you generate scaffolding against a code class, the add-in lets you select a Template collection and run each of the templates in one click/keyboard stroke. I have two examples to demonstrate how powerful this can be.
1. Given a Domain object/ Aggregate Root object: , I would have a template set that generates the following files / classes:
- Repository Interface
- Repository Class
- Repository Integration Test Class
- ORM Mapping File (this template would correctly set the Build Action to Embedded Resource automatically)
- ORM Mapping File Integration Test Class
- Presentation Model Object
- Mapping File to Map from the Domain Object to the Presentation Model
- Unit Test class to validate the Mapping from the Domain Object to the Presentation Model works correctly.
2. Given a Presentation Model object in an MVC project.
- Controller Class that handles the CRUD operations
- Controller unit test Class to validate the CRUD operations are functioning.
- Index (listing ) view file
- Show (detail) view file
- Edit (new and edit) view file
I think that using a scaffolding command like this gets you through the 80% of work that is literally some sort of a copy and paste. By reducing the friction of creating files generated off of a model, this lets the developer focus on the actual domain logic inside each of these files that provide value to your application.
This project is hosted at
Post Footer automatically generated by Add Post Footer Plugin for wordpress. | http://lostechies.com/erichexter/2009/03/03/alt-net-seattle-review/ | CC-MAIN-2015-11 | refinedweb | 2,818 | 65.56 |
An issue that frequently causes confusion for MSMQ users is that of message encryption. A message is marked for encryption and sent off, but when it shows up in the destination queue the contents are plainly viewable in clear text. What’s going on here?
Let’s look first at what MSMQ encryption actually does. MSMQ messages can be encrypted by setting the Message.UseEncryption property if using System.Messaging, or PROPID_M_PRIV_LEVEL message property if using the native API. When this property is set, the message body is encrypted using a key from the directory service when it is removed from the outgoing queue to be transmitted on the network. At the destination machine, the message is decrypted and placed in the destination queue. This type of encryption is a part of transport security — if the message were to be intercepted in transport, the contents would be safe.
“But this isn’t what I wanted! I can’t have sensitive customer data sitting in the queue until my application retrieves the message.” This is a common problem, which in the past was often solved by developers adding their own level of encryption to the data before placing it in the message body, and decrypting it after retrieving the message at the destination. This is certainly doable, as the CryptoAPI and its .NET namespace System.Security.Cryptography offer plenty of encryption tools. But it’s a hassle, and can take as much time and code as sending the message itself.
Enter WCF and the NetMsmqBinding. Queued messages sent using this WCF binding can be set to use the Message security mode, which uses the WS-* security protocols to secure the message layer itself. Messages secured in this way will remain encrypted until the WCF client removes the message from the destination queue. The WCF binding can also be set to Transport mode, which allows MSMQ to handle the encryption and authentication on the transport layer, or to Both, which makes everybody happy.
For more information, check out WCF Distributed Application Security.
—Sean McDaniel
MSMQ Test | http://blogs.msdn.com/b/motleyqueue/archive/2007/10/06/complementing-msmq-security-with-wcf.aspx | CC-MAIN-2014-52 | refinedweb | 344 | 56.66 |
The
yield keyword in Python is used to create generators. A generator is a type of collection that produces items on-the-fly and can only be iterated once. By using generators you can improve your application's performance and consume less memory as compared to normal collections, so it provides a nice boost in performance.
In this article we'll explain how to use the
yield keyword in Python and what it does exactly. But first, let's study the difference between a simple list collection and generator, and then we will see how
yield can be used to create more complex generators.
Differences Between a List and Generator
In the following script we will create both a list and a generator and will try to see where they differ. First we'll create a simple list and check its type:
# Creating a list using list comprehension squared_list = [x**2 for x in range(5)] # Check the type type(squared_list)
When running this code you should see that the type displayed will be "list".
Now let's iterate over all the items in the
squared_list.
# Iterate over items and print them for number in squared_list: print(number)
The above script will produce following results:
$ python squared_list.py 0 1 4 9 16
Now let's create a generator and perform the same exact task:
# Creating a generator squared_gen = (x**2 for x in range(5)) # Check the type type(squared_gen)
To create a generator, you start exactly as you would with list comprehension, but instead you have to use parentheses instead of square brackets. The above script will display "generator" as the type for
squared_gen variable. Now let's iterate over the generator using a for-loop.
for number in squared_gen: print(number)
The output will be:
$ python squared_gen.py 0 1 4 9 16
The output is the same as that of the list. So what is the difference? One of the main differences lies in the way the list and generators store elements in the memory. Lists store all of the elements in memory at once, whereas generators "create" each item on-the-fly, displays it, and then moves to the next element, discarding the previous element from the memory.
One way to verify this is to check the length of both the list and generator that we just created. The
len(squared_list) will return 5 while
len(squared_gen) will throw an error that a generator has no length. Also, you can iterate over a list as many times as you want but you can iterate over a generator only once. To iterate again, you must create the generator again.
Using the Yield Keyword
Now we know the difference between simple collections and generators, let us see how
yield can help us define a generator.
In the previous examples, we created a generator implicitly using the list comprehension style. However in more complex scenarios we can instead create functions that return a generator. The
yield keyword, unlike the
return statement, is used to turn a regular Python function in to a generator. This is used as an alternative to returning an entire list at once. This will be again explained with the help of some simple examples.
Again, let's first see what our function returns if we do not use the
yield keyword. Execute the following script:
def cube_numbers(nums): cube_list =[] for i in nums: cube_list.append(i**3) return cube_list cubes = cube_numbers([1, 2, 3, 4, 5]) print(cubes)
In this script a function
cube_numbers is created that accepts a list of numbers, take their cubes and returns the entire list to the caller. When this function is called, a list of cubes is returned and stored in the
cubes variable. You can see from the output that the returned data is in-fact a full list:
$ python cubes_list.py [1, 8, 27, 64, 125]
Now, instead of returning a list, let's modify the above script so that it returns a generator.
def cube_numbers(nums): for i in nums: yield(i**3) cubes = cube_numbers([1, 2, 3, 4, 5]) print(cubes)
In the above script, the
cube_numbers function returns a generator instead of list of cubed number. It's very simple to create a generator using the
yield keyword. Here we do not need the temporary
cube_list variable to store cubed number, so even our
cube_numbers method is simpler. Also, no
return statement is needed, but instead the
yield keyword is used to return the cubed number inside of the for-loop.
Now, when
cube_number function is called, a generator is returned, which we can verify by running the code:
$ python cubes_gen.py <generator object cube_numbers at 0x1087f1230>
Even though we called the
cube_numbers function, it doesn't actually execute at this point in time, and there are not yet any items stored in memory.
To get the function to execute, and therefore the next item from generator, we use the built-in
next method. When you call the
next iterator on the generator for the first time, the function is executed until the
yield keyword is encountered. Once
yield is found the value passed to it is returned to the calling function and the generator function is paused in its current state.
Here is how you get a value from your generator:
next(cubes)
The above function will return "1". Now when you call
next again on the generator, the
cube_numbers function will resume executing from where it stopped previously at
yield. The function will continue to execute until it finds
yield again. The
next function will keep returning cubed value one by one until all the values in the list are iterated.
Once all the values are iterated the
next function throws a StopIteration exception. It is important to mention that the
cubes generator doesn't store any of these items in memory, rather the cubed values are computed at runtime, returned, and forgotten. The only extra memory used is the state data for the generator itself, which is usually much less than a large list. This makes generators ideal for memory-intensive tasks.
Instead of always having to use the
next iterator, you can instead use a "for" loop to iterate over a generators values. When using a "for" loop, behind the scenes the
next iterator is called until all the items in the generator are iterated over.
Optimized Performance
As mentioned earlier, generators are very handy when it comes to memory-intensive tasks since they do not need to store all of the collection items in memory, rather they generate items on the fly and discards it as soon as the iterator moves to the next item.
In the previous examples the performance difference of a simple list and generator was not visible since the list sizes were so small. In this section we'll check out some examples where we can distinguish between the performance of lists and generators.
In the code below we will write a function that returns a list that contains 1 million dummy
car objects. We will calculate the memory occupied by the process before and after calling the function (which creates the list).
Take a look at the following code:
import time import random import os import psutil car_names = ['Audi', 'Toyota', 'Renault', 'Nissan', 'Honda', 'Suzuki'] colors = ['Black', 'Blue', 'Red', 'White', 'Yellow'] def car_list(cars): all_cars = [] for i in range (cars): car = { 'id': i, 'name': random.choice(car_names), 'color': random.choice(colors) } all_cars.append(car) return all_cars # Get used memory process = psutil.Process(os.getpid()) print('Memory before list is created: ' + str(process.memory_info().rss/1000000)) # Call the car_list function and time how long it takes t1 = time.clock() cars = car_list(1000000) t2 = time.clock() # Get used memory process = psutil.Process(os.getpid()) print('Memory after list is created: ' + str(process.memory_info().rss/1000000)) print('Took {} seconds'.format(t2-t1))
Note: You may have to
pip install psutil to get this code to work on your machine.
In the machine on which the code was run, following results were obtained (yours may look slightly different):
$ python perf_list.py Memory before list is created: 8 Memory after list is created: 334 Took 1.584018 seconds
Before the list was created the process memory was 8 MB, and after the creation of list with 1 million items, the occupied memory jumped to 334 MB. Also, the time it took to create the list was 1.58 seconds.
Now, let's repeat the above process but replace the list with generator. Execute the following script:
import time import random import os import psutil car_names = ['Audi', 'Toyota', 'Renault', 'Nissan', 'Honda', 'Suzuki'] colors = ['Black', 'Blue', 'Red', 'White', 'Yellow'] def car_list_gen(cars): for i in range (cars): car = { 'id':i, 'name':random.choice(car_names), 'color':random.choice(colors) } yield car # Get used memory process = psutil.Process(os.getpid()) print('Memory before list is created: ' + str(process.memory_info().rss/1000000)) # Call the car_list_gen function and time how long it takes t1 = time.clock() cars = car_list_gen(1000000) t2 = time.clock() # Get used memory process = psutil.Process(os.getpid()) print('Memory after list is created: ' + str(process.memory_info().rss/1000000)) print('Took {} seconds'.format(t2-t1))
Following results were obtained by executing the above script:
$ python perf_gen.py Memory before list is created: 8 Memory after list is created: 8 Took 3e-06 seconds
From the output, you can see that by using generators the memory difference is negligible (it remains at 8 MB) since the generators do not store the items in memory. Furthermore, the time taken to call the generator function was only 0.000003 seconds, which is also far less compared to time taken for list creation.
Conclusion
Hopefully from this article you have a better understanding of the
yield keyword, including how it's used, what it's used for, and why you'd want to use it. Python generators are a great way to improve the performance of your programs and they're very simple to use, but understanding when to use them is the challenge for many novice programmers. | http://stackabuse.com/understanding-pythons-yield-keyword/ | CC-MAIN-2018-26 | refinedweb | 1,681 | 53.1 |
While developing and deploying wireless applications and sensor networks is mandatory to assert the wireless link, to try and estimate the maximum range between two devices and to prevent link loss due to rain, obstacles, fading, etc.
Normally you would need to include in your toolbox, besides a sniffer and spectrum analyser (such as this one), at least one transmitter and receiver, and pack a laptop to read and store the results, unless purchasing a kit properly prepared to do this, like the CC2538dk or the CC1120dk around 250€-300€ approx.
As I grew tired of packing my laptop and having to rush open field testing to cope with my discharging battery, I opted to prepare my own field test setup just packing the essentials, for a lightweight test spree.The components
As I primarily work with RE-Mote platforms both in the 2.4GHz and 863-950MHz bands, I threw in the mix a commercial USB battery charger I normally use when travelling, and the Sparkfun's LCD with RGB backlight.
The LCD works over I2C, the library was already ported in Contiki by me (see rgb-bl-lcd.c) and is powered over 5V (but luckily the I2C has a 3.3V logic).
As the RE-Mote works using a 3.3V logic but can be powered over USB at 5V, I powered the LCD from the RE-Mote over the
D+5.1 pin (see above). The LCD I2C pins (SDA and SCL) are connected to the RE-Mote over the
I2C.SDA and
I2C.SCL pins as expected.
The battery charger is an USB battery with 6000mAh capacity, plenty of juice to last days of testing. The only drawback is having to either continuously press the power on button, or disable the RE-Mote's low power operation, else the battery "thinks" there's no connected device as the power consumption is too low.The result
Below is a video detailing the operation of the range test application.
When the application starts it will print information about the radio configuration. The current channel is displayed at the bottom row on the left, followed by the available channels and the transmission power (in dBm).
When the application starts it will start blinking the blue LED and instructions will be printed on the LCD.
Basically when long-pressing the user button (without releasing) it will toggle between the sender and receiver mode. The LCD will bright red when configured as receiver, or green when selected the transmitter mode.
When the user button is released the operation mode will be set (warning: if you need to change the operation mode, press the reset button and repeat). A single press on the user button will start the test.
I develop a simple application to wrap everything together, available as always in my Contiki's Github fork, look for the field-test-lcd branch.
git clone cd contiki && git checkout field-test-lcd
The application lives at
examples/zolertia/zoul/range-test
If you look at the Makefile there are two compilations switches to consider:
ifdef WITH_LCD CFLAGS += -DLCD_ENABLED=$(WITH_LCD) endif ifdef WITH_SUBGHZ CFLAGS += -DRF_SUBGHZ=$(WITH_LCD) endif
When compiling and programming the RE-Mote you can select to use either the 2.4GHz radio interface (CC2538) or the 868/915MHz radio (CC1200) (if adding
WITH_SUBGHZ=1). If you include the
WITH_LCD=1 argument to the compilation it will include the LCD display support, else if you don't have a LCD display you can still see the results over USB if connecting to the RE-Mote, by just using a micro-USB cable and putty or alike.
# Configure for 868MHz band make range-test.upload WITH_SUBGHZ=1 WITH_LCD=1 or # Configure for 2.4GHz band make range-test.upload WITH_LCD=1
And that's it! have fun testing and enjoying the weather! | https://www.hackster.io/alinan/range-tests-made-easy-with-the-re-mote-and-lcd-6e78b3 | CC-MAIN-2022-33 | refinedweb | 641 | 61.26 |
In today’s Programming Praxis problem, we have to implement the RC4 cipher, which is often used in protocols such as SSL and WEP. Let’s have a go, shall we?
First, some imports:
import Data.Bits import Data.Char import Data.IntMap ((!), fromList, insert, size, IntMap)
In this algorithm we’re going to have to swap two elements of a list twice, so let’s make a function for it. In order to speed this operation up, we’re going to use IntMaps instead of plain lists.
swap :: Int -> Int -> IntMap a -> IntMap a swap i j a = insert j (a ! i) $ insert i (a ! j) a
The algorithm consists of two steps. The first step is to create a list of 256 integers based on the key.
rc4init :: IntMap Char -> IntMap Int rc4init key = snd $ foldl (\(j, a) i -> let j' = mod (j + a ! i + ord (key ! mod i (size key))) 256 in (j', swap i j' a)) (0, s) [0..255] where s = fromList $ zip [0..] [0..255]
In the second step, we create a stream of characters based on the result of step 1, which is xor’ed with the input string.
rc4 :: String -> String -> String rc4 key = map chr . zipWith xor (stream key) . map ord where stream = s 0 0 . rc4init . fromList . zip [0..] s i' j' k' = k ! (mod (k ! i + k ! j) 256) : s i j k where i = mod (i' + 1) 256 j = mod (j' + k' ! i) 256 k = swap i j k'
Let’s see if that works correctly:
main :: IO () main = do print $ rc4 "Kata" "Bonsai Code" print . rc4 "Kata" $ rc4 "Kata" "Bonsai Code"
Yup. 11 lines, not too shabby.
Tags: bonsai, cipher, code, Haskell, kata, praxis, programming, rc4, ron's, ssl, wep | http://bonsaicode.wordpress.com/2009/09/04/programming-praxis-ron%E2%80%99s-cipher-4/ | CC-MAIN-2014-41 | refinedweb | 293 | 93.95 |
Last time [1], I gave a survey of the first batch of suggested library extensions that were considered at the October 2001 C++ standards meeting in Redmond, Washington, USA. This time, as promised, we'll take a closer look at one of the proposed facilities smart pointers, which were discussed again at the following April 2002 standards meeting in Curaçao, in the Netherlands Antilles.
And Then There Was One
In today's Standard C++, there's only one smart pointer:
std::auto_ptr.
Considering that it's such a tiny feature,
auto_ptr sure has received copious attention. The main reason for the attention is that attention is deserved, both positively and negatively. On the one hand,
auto_ptr is very useful for specific situations and those uses deserve to be described; see the discussion in Items 19 and 37 of Exceptional C++ [2], Item 10 of More Effective C++ [3], and my article "Using
auto_ptr Effectively," available online [4]. On the other hand,
auto_ptr can also be moderately suspicious to highly dangerous in other situations, such as the minefield of trying to put
auto_ptrs into standard containers like
vector and
map; see for example Item 21 of More Exceptional C++ [5] and Item 28 of More Effective C++ [3]. (On the gripping hand, as Niven and Pournelle might say,
auto_ptr relies on some fairly obscure language trickery to make it deliberately not work in some dangerous cases. Fortunately this trickery gets less press the details are not for the faint of heart. Suffice it to say that
auto_ptr is designed with some sleight of hand that's intended to make it deliberately break when used with, say, standard containers.)
So today's Standard C++ has exactly one smart pointer:
auto_ptr. That's it. So it must be all you need, right? Not a bit of it. There's more to this story.
It's actually a real shame that
auto_ptr is the only standard smart pointer, for at least two reasons. First,
auto_ptr doesn't do all the useful things that smart pointers might be good for; there are many good uses of smart pointers that poor
auto_ptr was never designed to support, and shouldn't, and doesn't. Second,
auto_ptr can be a dangerous snake that turns and bites you on the hand if you do try to use it in some of those other ways.
The first piece of good news is that many good and useful smart pointers are available and were available even before
auto_ptr. The only problem is that they weren't, and aren't, standard. That's somewhere between disappointing and annoying, depending on how portable your code needs to be standard features are of course generally the most portable.
The second piece of good news is that those alternative smart pointers are now strong candidates for inclusion into the Standard. (Some could have been in the original Standard; see [1]. But better late than never.)
If One Is Good, Six Are Better... (?)
The Boost library ships with five additional smart pointers [6]. All of these smart pointer templates take a single type parameter specifying the type of the object to be held. Briefly, here they are:
scoped_ptr: a non-copyable smart pointer intended to be used as an auto (stack) object. When a
scoped_ptrgoes out of scope and is destroyed, it will automatically delete the single object it points to. Arguably,
scoped_ptris what
auto_ptrought to have been in the first place, way back when
auto_ptrwas first meant to be really an "auto" pointer. But
scoped_ptrdoesn't support the modern
auto_ptr's important additional usefulness for sources and sinks (described in [4]).
scoped_array: like
scoped_ptr, but owns an array instead of a single object.
shared_ptr: a reference-counted smart pointer intended to be used to share "handles" to the pointed-at object. When a
shared_ptrgoes out of scope and is destroyed, if it is the last
shared_ptrpointing at the owned object, it will automatically delete the owned object a classic case of "last one out, turn off the lights." Note that
shared_ptrdoes support
auto_ptr's important use for sources and sinks. More importantly, it can be safely used in a container, which for
auto_ptrs is not allowed and highly dangerous.
shared_array: like
shared_ptr, but owns an array instead of a single object.
weak_ptr: to be used in conjunction with a
shared_ptr. If you have an object that's already managed by one or more
shared_ptrs, you can create
weak_ptrs to it too. Now, the
shared_ptrs still follow the "last one out, turn off the lights" policy; the last
shared_ptrwill delete the owned object even if there are still
weak_ptrs to it. How is
weak_ptrthen any better than just a bald pointer to the object? Because the
shared_ptrthat turns off the lights will also check to see if any
weak_ptrs still point to that object and set them to null if they do. That's a level of safety you don't get with plain old raw pointers.
Let me repeat some advice from last time, because it's worth repeating: if you know nothing else about Boost, know about
shared_ptr. It's especially valuable if you ever want to have a container of pointers, because what you almost always really want is a container of
shared_ptrs. For one thing, they'll be managed for you and will get cleaned up correctly, and they'll avoid the usual pitfalls of using mutating STL algorithms on containers of bald pointers. For another, they are not
auto_ptrs, which is a Good Thing because
auto_ptrs should never be put into STL containers.
The Boost approach is to have lots of special-purpose smart pointer types, one for each kind of smart pointer behavior. In this model, a smart pointer template is quite simple:
template<typename T> class scoped_ptr; template<typename T> class scoped_array; template<typename T> class shared_ptr; template<typename T> class shared_array; template<typename T> class weak_ptr;
Only one template parameter is needed, to specify the type of the owned object. It is both an advantage and a disadvantage that these little class templates can all have very different interfaces if they want to. On the one hand, it allows customization, say when a member function might make sense for one but not another smart pointer. But, on the other hand, it also means that it's easy to get inconsistent interfaces, especially when people start extending the facility by providing more smart pointers of their own, both within and outside the Boost library.
If Six Are Good, Infinity Is Better... (?!)
Although Boost chooses to follow the model of designing special-purpose smart pointer templates, we can ask: "Why stop there?" In fact, some very bright language designers, notably Andrei Alexandrescu in Modern C++ Design [7], have proposed that a "one size fits all" über-pointer may be an achievable dream, using policy-based design.
Policy-based design takes the view that certain details, such as checking policies and ownership policies, can be abstracted out into their own classes, which are then supplied as template parameters to configure or customize the basic smart pointer. Thus Loki's
SmartPtr template looks something like this:
template < typename T, template <class> class OwnershipPolicy = RefCounted, class ConversionPolicy = DisallowConversion, template <class> class CheckingPolicy = AssertCheck, template <class> class StoragePolicy = DefaultSPStorage > class SmartPtr;
Note that we still have the obligatory template parameter
T that describes the type of the pointed-at object. But we also get policies that govern much of the behavior of the smart pointer. The policies may look cumbersome to type out, but they are defaulted for those who don't want or need to specify them; the default
Loki::SmartPtr is a lot like a
boost::shared_ptr. In fact,
SmartPtr covers all that the four basic Boost smart pointers can do, and more. (An equivalent of Boost's
weak_ptr could also be provided to work with a partial specialization of
SmartPtr corresponding to
shared_ptr.)
Indeed, Loki's
SmartPtr is so much a superset of Boost's smart pointers that we would love to just create synonyms. In Standard C++, the following code won't work because it relies on a feature that was frankly just overlooked, namely
typedef templates (for some existing discussion, see [8]; I'll be writing more about this up-and-coming feature in the future). Barring major surprises, such as the Earth suddenly deciding to break out of its usual orbit and head for Mars on a holiday,
typedef templates will be in the next C++ Standard, C++0x (see [9]). If we had this feature, we could write the following synonym:
namespace boost { template<typename T> // typedef templates aren't standard typedef Loki::SmartPtr // yet, but let's overlook that for now... < T, // note, T still varies RefCounted, // but everything else is fixed DisallowConversion, NoCheck, DefaultSPStorage > shared_ptr; }
So that the usage would simply be, as usual:
shared_ptr<int> a; // simple -- no fuss, no muss!
Similar synonyms could be created for
shared_array,
scoped_ptr,
scoped_array, and even
std::auto_ptr. Such simple names for common configurations would make all the tedious template parameters go away for those common cases. We can't do that today, alas, but once
typedef templates become commonly available we will be able to do this and more.
SmartPtr really then describes an unlimited family of smart pointers having a consistent interface. Note that because Loki's
SmartPtr inherits publicly from its template parameter types, the interface does not have to be identical across the whole family; the policies could add some visible functionality too. Loki already comes with several predefined policies allowing hundreds of combinations. But you can add your own policies, such as for managing COM and CORBA distributed objects and other advances uses, so the size of the
SmartPtr family really is effectively unlimited.
Summary
The standards committee is still considering these options and welcomes other smart pointer submissions. In particular, there is ongoing discussion, with different points of view, about whether the "one size fits all" customizable policy-based design is the way to go, or whether just a few special-purpose smart pointer templates are needed. Want to weigh in? Start discussion on the Boost reflector [10] or on the
comp.std.c++ newsgroup.
Next time: more news from the April 2002 standards meeting in Curaçao. Stay tuned.
References
[1] H. Sutter. "The New C++: The Group of Seven Extensions under Consideration for the C++ Standard Library," C/C++ Users Journal C++ Experts Forum, April 2002, <>.
[2] H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
[3] S. Meyers. More Effective C++ (Addison-Wesley, 1996).
[4] H. Sutter. "Using
auto_ptr Effectively," C/C++ Users Journal, October 1999, available online at <>.
[5] H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
[6] <>
[7] A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
[8] H. Sutter. "Guru of the Week #79: Template Typedef," available online at <>.
[9] H. Sutter. "The New C++," C/C++ Users Journal C++ Experts Forum, February 2002, <>.
[10] C++ Boost, <>.
About the Author. | https://www.drdobbs.com/cpp/the-new-csmarter-pointers/184403837 | CC-MAIN-2020-10 | refinedweb | 1,830 | 59.84 |
< Modularity | Development
Revision as of 12:34, 22 September 2016
Most of our code is written in Python, so this document will concentrate on it.
Contents
- 1 Upstream guidelines
- 2 Keep It Simple
- 3 Python 2 and 3
- 4 Idiomatic code
- 5 External links
Upstream guidelines
Fortunately, with PEP 8 there's an extensive official Style Guide for Python Code. All new Python code you submit should conform to it, unless you have good reasons to deviate from it, for instance readability.
Keep PEP 20, the Zen of Python, under your pillow.
Keep It Simple
The code you write now probably needs to be touched by someone else down the road, and that someone else might be less experienced than you, or have a terrible headache and be under pressure of time. So while a particular construct may be a clever way of doing something, a simple way of doing the same thing can be and often is preferrable. If (when) complexity can't be avoided, try to isolate it: put a difficult operation into its own function, method or class, add comments liberally. If complexity can be hidden from upper layers of the code, do so.
Python 2 and 3
Python comes in two major versions nowadays:
- The legacy version 2, of which the first release 2.0 came out in October 2000. The Python project will maintain its final minor release 2.7 until 2020.
- The current version 3, its first release 3.0 was published in December 2008. At the time of writing, the current minor release is version 3.5, to be superseded by 3.6 around the end of 2016.
Version 3 is not backwards compatible to version 2. While we mainly target "the future", there are some components we have to work with that haven't yet been ported over the Python 3, most notably
koji. Additionally, we may also want to support the "user tools" we create on legacy systems, so we can't write code that uses all the latest features. Fortunately, many of the original Python 3 features have been back-ported to Python 2.7, so we can and should write code that is very close to writing idiomatic Python 3 but can still be run on version 2.7. Targeting older minor releases (Python 2.6 and earlier) is much more of a balancing act, so we won't aim for it.
The following sections cover areas that require some attention. The Python project itself has a great Porting Python 2 Code to Python 3 document which goes into much detail about the differences and is worth a read, even though it mainly addresses existing Python 2 code bases.
Absolute and relative imports
In Python 2, importing modules can be ambiguous when a module of that name exists in the same package and elsewhere in the module search path
sys.path. To work around this ambiguity, programmers often resorted to adding paths private to the project to the beginning of
sys.path to force loading modules from a project-internal location (which adds unwanted noise and can make e.g. testing code that isn't installed difficult). Python 3 introduces new syntax for import statements which makes both cases distinct, this is available since version 2.5 from the
__future__ module:
from __future__ import absolute_import # Import the sys module from the module search path import sys # Import the foo module from the same directory from . import foo # Import snafu from the bar module one directory above from ..bar import snafu
Print function
Python 3 did away with
from __future__ import print_function
Numbers
Python 2 has two integer types,
int which is whatever integer-type is native to the system (which has certain maximal and minimal values and can overflow) and
long which can store arbitrary integer numbers. Python 3 only the latter type, but it's called
int.
Dividing integer numbers using
/ truncates the result to an integer in Python 2 by default, but yields a floating point number in Python 3. In order for code to do the same thing on either version, include the following line at the top of your source files where you divide numbers, and use
/ for normal divisions and
// for divisions that should truncate the result:
from __future__ import division
Strings
Some consider this the main difference between Python 2 and 3: Both versions have a type for strings of bytes and strings of Unicode character points. They are called
str and
unicode in version 2 and
bytes and
str in version 3, respectively.
String Literals
Python 2 and 3 use different ways of marking literals of the different types by default. Byte strings can have no prefix or
b in Python 2.7, but must be prefixed in Python 3, and text strings must have the
u prefix in Python 2 which can be and usually is omitted in Python 3:
# a byte string in Python 2 and 3 string1 = b"abc" # a byte string in Python 2, but a text string in Python 3 string2 = "def" # a text string in Python 2 and 3 string3 = u"ghi"
In order to ease writing code that is compatible between the versions, you can switch Python 2 to treat unprefixed string literals as
unicode, the text string type, by adding this snippet to the top of the relevant source code files:
from __future__ import unicode_literals
Explicit Encoding and Decoding
In Python 2, the byte and text string types are exchangeable in many places, taking the user's or system default locale into account (and sometimes failing, when the locale didn't match up with encoded data). Apart from the change in type names and how literals look like, Python 3 requires you to explicitly encode
str and decode
bytes objects if you need them cast into the respective other string type. It is good practice to exclusively use text strings for strings that represent text in a program and decode byte strings as early and encode text strings as late as possible at interfaces that produce or consume encoded data.
from __future__ import print_function text_string = u"Hello, world!" print(text_string.replace("world", "gang"))
from __future__ import print_function, unicode_literals text_string = "Hello, world!" print(text_string.replace(b"world".decode('utf-8'), b"gang".decode('ascii')))
String formatting
With version 3.6 around the corner, there are four ways to format strings in Python now:
- using the
%operator
- using
string.Templateof PEP 292
- with the
str.format()method
- using PEP 498 literal string interpolation
The last method isn't available yet in a stable Python release and will never be in Python 2, so it's not suitable for our purposes. The other three variants work in all Python versions we're interested in, formatting with
string.Template is very rarely done however. The remaining two ways, commonly called old-style (
% operator) and new-style (
str.format()), are both in wide-spread use, here's a site showcasing the differences between them. New-style formatting is more powerful and often easier to read, but on the other hand can be a little more to type. From a technical point of view, this is a case of "use what works for you", but for consistency sake the new-style
str.format() way is preferrable if you're comfortable with using it. If not, others can convert old-style to new-style formatting for you during review or when happening across it. At any rate, consistently use one way or the other in what you submit.
Old- and New-style Classes
Python 2 and earlier knows two types of classes, old-style which have no base class, and new-style which have
object as the base class. Because their behavior is slightly different in some places, and some things can't be done with old-style classes, we want to stick to new-style classes wherever possible.
The syntactical difference is that new-style classes have to explicitly be derived from
object or another new-style class.
# old-style classes class OldFoo: pass class OldBar(OldFoo): pass # new-style classes class NewFoo(object): pass class NewBar(NewFoo): pass
Python 3 only knows new-style classes and the requirement to explicitly derive from
object was dropped. In projects that will only ever run on Python 3, it's acceptable not to explicitly derive classes without parents from
object, but if in doubt, do it just the same.
Idiomatic code
In Python, it's easy to inadvertently emulate idiomatic styles of other languages like C/C++ or Java. In cases where there are constructs "native" to the language, it's preferrable to use them.
Literals and Comprehensions
Python has special syntax for literals for a couple of built-in compound data types (lists, tuples, dictionaries, strings—however, there is no literal for sets). It's customary to use that syntax instead of the class constructor to create objects for these data types unless you have good reason not to. Apart from how it looks, the literal syntax is performing a little bit better (because it doesn't have to look up the class name in the current scope).
Often the initial contents of a compound object are only known when it's created at runtime. For simple cases like mere type conversions, calling the class constructors are the way to go:
- Converting a tuple to a list or vice versa:
a_list = list(a_tuple) another_tuple = tuple(another_list)
- Convert a list to a set, e.g. to filter out duplicates:
a_set = set([1, 2, 3, 2])
For more involved cases, say some values need to be filtered or a specific attribute of the objects is wanted, Python has so-called comprehensions to create compound objects in a syntactically "nice" way. These largely supersede the old (ugly) way of using
map() and
filter() in conjunction with class constructors.
Looping
Languages like C normally use incremented indices to loop over arrays:
float pixels[NUMBER_OF_PIXELS] = [...]; for (int i = 0; i < NUMBER_OF_PIXELS; i++) { do_something_with_a_pixel(pixels[i]); }
Implementing the loop like this would give away that you've programmed in C or a similar language before:
pixels = [...] for i in range(len(pixels)): do_something_with_a_pixel(pixels[i])
Here's the "native" way to implement the above loop:
pixels = [...] for p in pixels: do_something_with_a_pixel(p)
It yields pairs of count (starting at 0 by default) and the current value like this:
pixels = [...] for p_no, p in enumerate(pixels, 1): print("Working on pixel no. {}".format(p_no)) do_something_with_a_pixel(p)
Properties rather than explicit accessor methods
In order to allow future changes in how object attributes (member variables) are set, some languages encourage always using getter and/or setter methods. This is unnecessary in Python, as you can intercept access to an attribute by wrapping it into a property if and when this becomes necessary. Properties allow having accessor methods without making the user of the class have to use them explicitly. This way you can validate values when an attribute is set, or translate back and forth between the interface used on the attribute and an internal representation.
Validating a value when setting an attribute
To ensure that an
Employee object only has positive values for its
salary attribute, you'd put a property in its place which checks values before storing them in an attribute called e.g.
_salary:
class Employee(object): @property def salary(self): return self._salary @salary.setter def salary(self, salary): if salary <= 0: raise ValueError("Salary must be positive.") self._salary = salary
Translating between attribute interface and internal representation
Take these classes of geometric primitives,
Point and
Circle:
class Point(object): def __init__(self, x, y): self.x = x self.y = y class Circle(object): def __init__(self, point, radius): self.point = point self.radius = radius
If you wanted to add a
diameter attribute to
Circle, you can do so as a property which translates back and forth between it and the existing
radius attribute:
... class Circle(object): def __init__(self, point, radius=None, diameter=None): self.point = point if (radius is None) == (diameter is None): raise ValueError("Exactly one of radius or diameter must be set") if radius is not None: self.radius = radius else: self.diameter = diameter @property def diameter(self): return self.radius * 2 @diameter.setter def diameter(self, diameter): self.radius = diameter / 2.0 ...
Even setting
self.diameter in the constructor goes by way of the property and therefore the setter method. | https://fedoraproject.org/w/index.php?title=Modularity/Development/Coding_Style&diff=prev&oldid=474739 | CC-MAIN-2018-43 | refinedweb | 2,071 | 59.94 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
Extra Include Files
A hopefully handy plugin for Pelican to allow extra CSS and JS files per-article.
The Problem
I write a bunch of tutorials on how to do things with CSS and JS. For the examples in these, I need individual article-specific CSS and JS files. Adding a single file of each type is no big deal; just add a filename in metadata, and you're all good. However, trying to add multiple files as a list proved to be beyond my poor capabilities in Jinja2. So, I wrote a dirt simple plugin to help me out.
The Solution
The
extra_include_files plugin looks for
extra_css and
extra_js metadata in your articles, and converts it into a list that's available as
extra_css_files and
extra_js_files in your templates.
Example
In
my_tutorial.md article, I need two unique CSS files and a unique JavaScript file to provide examples in the article. So in my markdown file:
Title: I am a pretty pony extra_css: pony_tutorial.css, dark_background.css extra_js: pony_tutorial.js Summary: This needs to look different for some reason. # This article looks different If lots of your articles need unique CSS, this is easier than making a billion templates.
Then in the
article.html template:
<html> <head> <link rel="stylesheet" href="base.css"> {% if article.extra_css_files %} {% for file in article.extra_css_files %} <link rel="stylesheet" href="/css/{{ file|trim }}" media="screen"> {% endfor %} {% endif %} </head> <body> {{ article.content }} {% if article.extra_js_files %} {% for file in article.extra_js_files %} <script src="/js/{{ file|trim }}"></script> {% endfor %} {% endif %} </body> </html>
And now that article will have two extra CSS files and a JavaScript included in it. | https://bitbucket.org/simblestudios/pelican-extra-include-files-plugin | CC-MAIN-2018-05 | refinedweb | 294 | 59.5 |
I'm new to unity and I'm trying to get the hang of it, I'm following this tutorial to try and create movable ball similar to monkey ball. I've created a camera that is following the sphere using this code:
public class FollowCamera : MonoBehaviour {
public GameObject target;
public float damping = 1;
Vector3 offset;
void Start() {
offset = target.transform.position - transform.position;
}
void LateUpdate() {
float currentAngle = transform.eulerAngles.y;
float desiredAngle = target.transform.eulerAngles.y;
float angle = Mathf.LerpAngle(currentAngle, desiredAngle, Time.deltaTime * damping);
Quaternion rotation = Quaternion.Euler(0, angle, 0);
transform.position = target.transform.position - (rotation * offset);
transform.LookAt(target.transform);
}
}
While this works correctly and follows the sphere, the controls are very awkward and do not work as expected however if the sphere is changed to a cube or anyother model its works perfectly fine.
Also if anyone has any sites to get me started that would be nice of you.
Thanks
Answer by Wolferino
·
Sep 02, 2014 at 02:52 PM
bumperino
The Irony here is that you posted your bump as an Answer which means your question will be removed from the Unanswered section making it even more unlikely to get any answers on it.
Ins$$anonymous$$d of bumping your questions you should think about why your question may have gone unanswered. With this question you have not provided enough details.
You say it does not work as expected. You should then provide us with details about how it should work, why you think what you have done would work and what exactly it does wrong. Saying the controls are awkward give us nothing I am afraid.
If you want some tutorials then Unity has a ton of them:
But you have probably already been to that.
Flip over an object (smooth transition)
3
Answers
Coding noob struggles to implement first-Person camera rotation.
1
Answer
maximum angle for camera
0
Answers
Limit camera RotateAround for an UAV game
0
Answers
Rotating following camera for a sphere
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/781792/third-person-follow-camera-on-a-sphere.html?sort=oldest | CC-MAIN-2021-17 | refinedweb | 339 | 55.64 |
Introduction: Python Word Art
A few years ago, I came across some beautiful art made by formatting the layout of text from well-known books. An image associated with the book was created by adjusting the space of the characters to form an elementary gray-scale image. By adding extra spaces in the text, you can reproduce pictures or designs representing the original book. The pictures above are from Alice in Wonderland, A Christmas Carol, and the poem Jabberwocky from Through the Looking Glass.
I decided to write a simple code to reproduce this idea. The underlying principle of the project is to convert an image into a mask and then format the text from a book to reflect this mask. There are five critical elements in this project:
- We must import Python libraries into the code.
- We need to download or access a long string of text that we will format into the art. Next, we will need to clean the text to remove any embedded control characters.
- We need to convert an image into a mask. First, we must rescale the image so the number of pixels maps into the available space for the text. Next, each row in this rescaled image must be scanned and associated with text strings. Finally, we place characters where the pixel values are above a set threshold, and blank spaces are embedded when they fall below this threshold.
- We need to convert the raw text into a file format to set the font type and size for printing.
- We need to pick an image and a source for the text and run the code.
You can download the sample code along with some of the graphics from Github.
You can browse the repository and clone it from here:
Step 1: Importing the Needed Libraries.
To begin the code, we need to import some libraries. I've included the pip commands to install these libraries. You should only uncomment and execute the "pip install" lines the first time you run this on a new machine.
We start by grabbing elements of the python image library.
#pip install PIL import PIL.ImageGrab import PIL.ImageOps import PIL.Image
We then grab the python presentation library.
#pip install python-pptx from pptx import Presentation from pptx.util import Inches from pptx.util import Pt<br>
We use the requests library to grab data from the web:
#pip install requests import requests
Finally, we use the regular expression library. This library should be part of the standard python distribution.
import re<br>
Step 2: Downloading Text From the Project Gutenberg
Before the internet was created, efforts were underway to move public domain documents into digital collections. One of the best examples of these collections is Project Gutenberg. This free digital collection has over 60,000 manuscripts. The books are usually available in various formats, from UTF-8 text to formats designed for multiple ebook readers.
As a geek (and data scientist), this data set is a goldmine for projects. You can search through their entire collection. They also maintain a list of the 100 most popular downloads.
For this project, I am using the UTF-8 version of the books. Once you pick a book you are interested in (like Alice in Wonderland), you can see the list of available formats available to download.
Reading a file into a python program is easy using the python request library.
import requests data = requests.get("") text = data.text
Once the file is downloaded and converted into text, we clean up the UTF-8 control characters. The easiest way to do this using the regular expression (re) library and python string replacements. In my code, I did the following steps:
First, get rid of the new lines and character returns.
text = re.sub("\r"," ",text) text = re.sub("\n"," ",text)<br>
Eliminate the asterisks, underline characters, and quotes because they mess up my formatting. I used the regular expression library for this change. I probably could have just used a text replacement.
<pre style="font-size: 13.5px;"> text = re.sub("\*", "", text) text = re.sub("\_", "", text) text = re.sub('"', '', text)<br>
Remove all the quirky control characters associated with UTF-8. This code fixes the problems I found when I visually inspected the data in Jupyter notebook.
<pre style="font-size: 13.5px;"> text = text.replace("â\x80\x9d", "") text = text.replace("â\x80\x9c", "") text = text.replace("â\x80\x9c", "''") text = text.replace("â\x80\x99","''") text = text.replace("â\x80\x94","") text = text.replace("â\x80\x98", "")
Finally, I changed all the multiple spaces into a single space. Regular expressions are the easiest way to do this change. The "\s+" means all the occurrences of at least one white space.
<pre style="font-size: 13.5px;"> text = re.sub("\s+"," ", text)
Step 3: Using an Image to Format the Text Layout
Once we have some text, we need to format the letters to match the shape of an image.
First, we open the image and read it into the code.
# load the image img = PIL.Image.open(image_name)<br>
Next, I set up the parameters associated with the final text size.
# set up the margins for the text text_width = slide_width - 2*slide_left_margin text_height= slide_height - 2*slide_top_margin<br>
Now we can calculate the number of characters that will fit in the text box. The first step is to determine how big the font is in inches. The 60 and 120 in the code were found experimentally based. These numbers SHOULD probably be 72 and 144 based on my understanding of point sizes in formatting, but I needed to adjust them slightly.
vscale = 60 / font_size hscale = 120 / font_size<br>
Next, we resize the image so the number of pixels in the new image corresponds to the number of characters available in the text field. To determine this number, we have to multiply the text width times scaling factor from above.
nw = int(text_width * hscale) nh = int(text_height * vscale) img3 = img.resize((nw, nh))<br>
Now we need to convert this image into simple one-byte grayscale and invert it if desired:
gray = img3.convert("L") if invertBW: gray = PIL.ImageOps.invert(gray)<br>
The next thing I do is convert the pixels in this image into a one-dimensional list. I could have sampled the pixel values one at a time, but this seemed a bit more natural to me.
a = list(gray.getdata())<br>
This list is the key to the whole project. The size of the list is the product of the length and width (in pixels) of the newly resized image. Each value in the list is between 0 and 255, so we can determine if it should be a blank or a character based on this pixel value.
We will now loop through image pixels. However, before that, we need to set up a few counters.
- text_counter is the current location within our downloaded text
- pixel_counter is the current location within the long list of pixel values
- plist is a list of paragraphs we will be creating with the formatted text. Each paragraph is a line of formatted text.
- threshold is the value above which we consider pixel to be dark. Usually, we pass this value into the function as a parameter, but I include it here for completeness.
text_counter = 0 character_counter = 0 plist = [] threshold = 128<br>
We will now loop over the image by row and column. The rows are associated with the number of pixels in the image height. The number of columns is related to the image width. The ft variable is the formatted text for this paragraph. The outer loop structure looks like this:
for i in range(nh): fT = "" for j in range(nw): <br>
We can now determine if the current pixel is above the threshold. If it is, we add the next character and update the text_counter. If it is below the threshold, we add a blank space and don't update the text_counter. After we append the character to our formatted text string (ft), we update the pixel_counter. I could simplify the code a bit, but I wanted to ensure it was straightforward for less experienced programmers.
c = a[pixel_counter] add_character = ( c>= threshold) if add_character: fT = fT + text[text_counter] text_counter = text_counter + 1 else: fT = fT + " " pixel_counter = pixel_counter + 1
We append the text string into the paragraph list at the end of each row.
plist.append(fT)<br>
Text from the original book is formatted around the white space associated with locations in the image.
Step 4: Reformatting the Image Into a Printable Form
The final step in this process is putting the text into a format that is easy to print. I decided to use Powerpoint for the final document. I probably could have used Word or PDF, but Powerpoint is relatively universal. You can bring a Powerpoint slide into your local copy/printing center and ask them to print it as a large poster.
For this step, I used the python-pptxlibrary in the code. However, setting up this library was a little confusing, so let me explain the sequence you need to follow for using this library.
First, we need to create the presentation. Next, we need to set the slide height and width in inches. In the code, the Inches routine is part of the pptx library. Finally, we need to select the slide format as a blank slide. Based on experimentation, 6 is the number associated with this layout.
prs=Presentation() prs.slide_width = Inches(slide_width) prs.slide_height = Inches(slide_height) lyt=prs.slide_layouts[6] <br>
Within the slide, we are going to create a textbox. I am setting the textbox bounds based on the slide size and the margins on the sides and top/bottom. So first, I define the textbox with the left, top, width, and height variables. I used these values in the next step.
text_width = slide_width - 2*slide_left_margin text_height= slide_height - 2*slide_top_margin left = Inches(slide_left_margin) top = Inches(slide_top_margin) width = Inches(text_width) height = Inches(text_height)<br>
I will now create a new slide in the presentation and add a textbox. Finally, I construct a text frame to accept the paragraphs of the formatted text.
slide=prs.slides.add_slide(lyt) text_box=slide.shapes.add_textbox(left, top, width, height) tb=text_box.text_frame<br>
Now I can create our paragraphs and add the text associated with the paragraph list (plist).
for pp in plist: pgr = tb.add_paragraph() pgr.text=pp <br>
Finally, I set the font and font size for each paragraph. We will loop through the paragraphs and set these variables. I could have done this in the previous step, but I wanted to make it easier to read. It is important to note that not all fonts will work well with this type of art. For example, Courier is a monospaced font; thus, all characters have the same width.
for i in range(len(tb.paragraphs)): tb.paragraphs[i].font.size = Pt(font_size) tb.paragraphs[i].font.name = 'Courier' # use a monospace font <br>
Finally, we save the output file as a Powerpoint file. The name generally should have the "pptx" extension.
prs.save(output_name) <br>
Step 5: Creating Word Art
Since I organized the python notebook into a few simple functions, using this code is pretty straightforward.
To help people get started, I set up some example book metadata from Project Gutenberg. Each record contains the book's title, the author, the URL where you can access it, and the text associated with the first line.
book_data = [ { "title":"A CHRISTMAS CAROL IN PROSE BEING A Ghost Story of Christmas", "author":"Charles Dickens", "url":"", "firstLine":"MARLEY was dead: to begin with" }, { "title":"Alice’s Adventures in Wonderland", "author":"Lewis Carroll", "url":"", "firstLine":"Alice was beginning to get very tired" }, { "title":"War of the Worlds", "author":"H. G. Wells", "url":"", "firstLine":"No one would have believed" }, .... ]<br>
The book data is then loaded using:
data = requests.get( book["url"]) istart = data.text.find(book["firstLine"]) text = data.text[istart:]<br>
Although you can theoretically use any image for this project, simple is the best. A paint program is the best way to create these images. You could also use pictures and then run them through a photo editor to simplify the outlines. For example, the picture above was made from a relatively complex drawing by Sir John Tenniel for the original Alice in Wonderland book. Although Alice is visible in the formatted text, the original picture needs editing to sharpen the resulting image.
I hope you experiment with this project. For example, adding bold or color text could make the image more interesting. (Hint: text "runs" within the pptx library can help with this.) Changing the direction to follow the outline of objects would also be fun.
Although it was fun to format classic texts into graphically attractive layouts, you could use this program with papers, reports, and even thesis projects.
Have fun experimenting with the code! Also, please post some of the art you create with it!
First Prize in the
Hour of Code Speed Challenge
Be the First to Share
Recommendations
2 Comments
6 months ago on Step 5
Hello, this is wonderful, well done!
Thanks for sharing this, you should be first place :-D
Reply 6 months ago
Thanks! Also - thanks for posting the picture. :) | https://www.instructables.com/Python-Word-Art/ | CC-MAIN-2022-33 | refinedweb | 2,225 | 66.44 |
Local Data
Running a LINQ query directly against a DbSet will always send a query to the database, but you can access the data that is currently in-memory using the DbSet.Local property. You can also access the extra information EF is tracking about your entities using the DbContext.Entry and DbContext.ChangeTracker.Entries methods. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.
Using Local to look at local data
The Local property of DbSet provides simple access to the entities of the set that are currently being tracked by the context and have not been marked as Deleted. Accessing the Local property never causes a query to be sent to the database. This means that it is usually used after a query has already been performed. The Load extension method can be used to execute a query so that the context tracks the results. For example:
using (var context = new BloggingContext()) { // Load all blogs from the database into the context context.Blogs.Load(); // Add a new blog to the context context.Blogs.Add(new Blog { Name = "My New Blog" }); // Mark one of the existing blogs as Deleted context.Blogs.Remove(context.Blogs.Find(1)); // Loop over the blogs in the context. Console.WriteLine("In Local: "); foreach (var blog in context.Blogs.Local) { Console.WriteLine( "Found {0}: {1} with state {2}", blog.BlogId, blog.Name, context.Entry(blog).State); } // Perform a query against the database. Console.WriteLine("\nIn DbSet query: "); foreach (var blog in context.Blogs) { Console.WriteLine( "Found {0}: {1} with state {2}", blog.BlogId, blog.Name, context.Entry(blog).State); } }
If we had two blogs in the database - 'ADO.NET Blog' with a BlogId of 1 and 'The Visual Studio Blog' with a BlogId of 2 - we could expect the following output:
In Local: Found 0: My New Blog with state Added Found 2: The Visual Studio Blog with state Unchanged In DbSet query: Found 1: ADO.NET Blog with state Deleted Found 2: The Visual Studio Blog with state Unchanged
This illustrates three points:
- The new blog 'My New Blog' is included in the Local collection even though it has not yet been saved to the database. This blog has a primary key of zero because the database has not yet generated a real key for the entity.
- The 'ADO.NET Blog' is not included in the local collection even though it is still being tracked by the context. This is because we removed it from the DbSet thereby marking it as deleted.
- When DbSet is used to perform a query the blog marked for deletion (ADO.NET Blog) is included in the results and the new blog (My New Blog) that has not yet been saved to the database is not included in the results. This is because DbSet is performing a query against the database and the results returned always reflect what is in the database.
Using Local to add and remove entities from the context
The Local property on DbSet returns an ObservableCollection with events hooked up such that it stays in sync with the contents of the context. This means that entities can be added or removed from either the Local collection or the DbSet. It also means that queries that bring new entities into the context will result in the Local collection being updated with those entities. For example:
using (var context = new BloggingContext()) { // Load some posts from the database into the context context.Posts.Where(p => p.Tags.Contains("entity-framework").Load(); // Get the local collection and make some changes to it var localPosts = context.Posts.Local; localPosts.Add(new Post { Name = "What's New in EF" }); localPosts.Remove(context.Posts.Find(1)); // Loop over the posts in the context. Console.WriteLine("In Local after entity-framework query: "); foreach (var post in context.Posts.Local) { Console.WriteLine( "Found {0}: {1} with state {2}", post.Id, post.Title, context.Entry(post).State); } var post1 = context.Posts.Find(1); Console.WriteLine( "State of post 1: {0} is {1}", post1.Name, context.Entry(post1).State); // Query some more posts from the database context.Posts.Where(p => p.Tags.Contains("asp.net").Load(); // Loop over the posts in the context again. Console.WriteLine("\nIn Local after asp.net query: "); foreach (var post in context.Posts.Local) { Console.WriteLine( "Found {0}: {1} with state {2}", post.Id, post.Title, context.Entry(post).State); } }
Assuming we had a few posts tagged with 'entity-framework' and 'asp.net' the output may look something like this:
In Local after entity-framework query: Found 3: EF Designer Basics with state Unchanged Found 5: EF Code First Basics with state Unchanged Found 0: What's New in EF with state Added State of post 1: EF Beginners Guide is Deleted In Local after asp.net query: Found 3: EF Designer Basics with state Unchanged Found 5: EF Code First Basics with state Unchanged Found 0: What's New in EF with state Added Found 4: ASP.NET Beginners Guide with state Unchanged
This illustrates three points:
- The new post 'What's New in EF' that was added to the Local collection becomes tracked by the context in the Added state. It will therefore be inserted into the database when SaveChanges is called.
- The post that was removed from the Local collection (EF Beginners Guide) is now marked as deleted in the context. It will therefore be deleted from the database when SaveChanges is called.
- The additional post (ASP.NET Beginners Guide) loaded into the context with the second query is automatically added to the Local collection.
One final thing to note about Local is that because it is an ObservableCollection performance is not great for large numbers of entities. Therefore if you are dealing with thousands of entities in your context it may not be advisable to use Local.
Using Local for WPF data binding
The Local property on DbSet can be used directly for data binding in a WPF application because it is an instance of ObservableCollection. As described in the previous sections this means that it will automatically stay in sync with the contents of the context and the contents of the context will automatically stay in sync with it. Note that you do need to pre-populate the Local collection with data for there to be anything to bind to since Local never causes a database query.
This is not an appropriate place for a full WPF data binding sample but the key elements are:
- Setup a binding source
- Bind it to the Local property of your set
- Populate Local using a query to the database.
WPF binding to navigation properties
If you are doing master/detail data binding you may want to bind the detail view to a navigation property of one of your entities. An easy way to make this work is to use an ObservableCollection for the navigation property. For example:
public class Blog { private readonly ObservableCollection<Post> _posts = new ObservableCollection<Post>(); public int BlogId { get; set; } public string Name { get; set; } public virtual ObservableCollection<Post> Posts { get { return _posts; } } }
Using Local to clean up entities in SaveChanges
In most cases entities removed from a navigation property will not be automatically marked as deleted in the context. For example, if you remove a Post object from the Blog.Posts collection then that post will not be automatically deleted when SaveChanges is called. If you need it to be deleted then you may need to find these dangling entities and mark them as deleted before calling SaveChanges or as part of an overridden SaveChanges. For example:
public override int SaveChanges() { foreach (var post in this.Posts.Local.ToList()) { if (post.Blog == null) { this.Posts.Remove(post); } } return base.SaveChanges(); }
The code above uses the Local collection to find all posts and marks any that do not have a blog reference as deleted. The ToList call is required because otherwise the collection will be modified by the Remove call while it is being enumerated. In most other situations you can query directly against the Local property without using ToList first.
Using Local and ToBindingList for Windows Forms data binding
Windows Forms does not support full fidelity data binding using ObservableCollection directly. However, you can still use the DbSet Local property for data binding to get all the benefits described in the previous sections. This is achieved through the ToBindingList extension method which creates an IBindingList implementation backed by the Local ObservableCollection.
This is not an appropriate place for a full Windows Forms data binding sample but the key elements are:
- Setup an object binding source
- Bind it to the Local property of your set using Local.ToBindingList()
- Populate Local using a query to the database
Getting detailed information about tracked entities
Many of the examples in this series use the Entry method to return a DbEntityEntry instance for an entity. This entry object then acts as the starting point for gathering information about the entity such as its current state, as well as for performing operations on the entity such as explicitly loading a related entity.
The Entries methods return DbEntityEntry objects for many or all entities being tracked by the context. This allows you to gather information or perform operations on many entities rather than just a single entry. For example:
using (var context = new BloggingContext()) { // Load some entities into the context context.Blogs.Load(); context.Authors.Load(); context.Readers.Load(); // Make some changes context.Blogs.Find(1).Title = "The New ADO.NET Blog"; context.Blogs.Remove(context.Blogs.Find(2)); context.Authors.Add(new Author { Name = "Jane Doe" }); context.Readers.Find(1).Username = "johndoe1987"; // Look at the state of all entities in the context Console.WriteLine("All tracked entities: "); foreach (var entry in context.ChangeTracker.Entries()) { Console.WriteLine( "Found entity of type {0} with state {1}", ObjectContext.GetObjectType(entry.Entity.GetType()).Name, entry.State); } // Find modified entities of any type Console.WriteLine("\nAll modified entities: "); foreach (var entry in context.ChangeTracker.Entries() .Where(e => e.State == EntityState.Modified)) { Console.WriteLine( "Found entity of type {0} with state {1}", ObjectContext.GetObjectType(entry.Entity.GetType()).Name, entry.State); } // Get some information about just the tracked blogs Console.WriteLine("\nTracked blogs: "); foreach (var entry in context.ChangeTracker.Entries<Blog>()) { Console.WriteLine( "Found Blog {0}: {1} with original Name {2}", entry.Entity.BlogId, entry.Entity.Name, entry.Property(p => p.Name).OriginalValue); } // Find all people (author or reader) Console.WriteLine("\nPeople: "); foreach (var entry in context.ChangeTracker.Entries<IPerson>()) { Console.WriteLine("Found Person {0}", entry.Entity.Name); } }
You'll notice we are introducing a Author and Reader class into the example - both of these classes implement the IPerson interface.
public class Author : IPerson { public int AuthorId { get; set; } public string Name { get; set; } public string Biography { get; set; } } public class Reader : IPerson { public int ReaderId { get; set; } public string Name { get; set; } public string Username { get; set; } } public interface IPerson { string Name { get; } }
Let's assume we have the following data in the database:
Blog with BlogId = 1 and Name = 'ADO.NET Blog'
Blog with BlogId = 2 and Name = 'The Visual Studio Blog'
Blog with BlogId = 3 and Name = '.NET Framework Blog'
Author with AuthorId = 1 and Name = 'Joe Bloggs'
Reader with ReaderId = 1 and Name = 'John Doe'
The output from running the code would be:
All tracked entities: Found entity of type Blog with state Modified Found entity of type Blog with state Deleted Found entity of type Blog with state Unchanged Found entity of type Author with state Unchanged Found entity of type Author with state Added Found entity of type Reader with state Modified All modified entities: Found entity of type Blog with state Modified Found entity of type Reader with state Modified Tracked blogs: Found Blog 1: The New ADO.NET Blog with original Name ADO.NET Blog Found Blog 2: The Visual Studio Blog with original Name The Visual Studio Blog Found Blog 3: .NET Framework Blog with original Name .NET Framework Blog People: Found Person John Doe Found Person Joe Bloggs Found Person Jane Doe
These examples illustrate several points:
- The Entries methods return entries for entities in all states, including Deleted. Compare this to Local which excludes Deleted entities.
- Entries for all entity types are returned when the non-generic Entries method is used. When the generic entries method is used entries are only returned for entities that are instances of the generic type. This was used above to get entries for all blogs. It was also used to get entries for all entities that implement IPerson. This demonstrates that the generic type does not have to be an actual entity type.
- LINQ to Objects can be used to filter the results returned. This was used above to find entities of any type as long as they are modified.
Note that DbEntityEntry instances always contain a non-null Entity. Relationship entries and stub entries are not represented as DbEntityEntry instances so there is no need to filter for these.
Feedback | https://docs.microsoft.com/en-us/ef/ef6/querying/local-data | CC-MAIN-2019-30 | refinedweb | 2,169 | 53.81 |
In this tutorial we will learn about swapping of two number in java without using third variable. This is simple program to swap two value using arithmetic operation Swapping of two numbers is most popular question asked in so many interviews for fresher level. Swapping is nothing but exchanging the value of two variables. This is done by arithmetic operation on variables to exchange the value. From the example below you get the explanation in the following steps:
a=10 b=20 Step 1: a = a+b //Now a has value 30 Step 2: b = a-b //Now b has value 10 Step 3: a = a-b //Now a has value 20 a=20 // Now a has value 20 b=10 // Now b has value 10
Example : Using this example we will explain you how to swap two variables without using the third variables. First we declare one class in which we take two integer variables a and b. After initialization of two variables performing addition and subtraction on the variables to swap the value of both. So from the example below you can get the code.
import java.io.BufferedReader; import java.io.InputStream; public class Swapping { public static void main(String args[]) { int a=10; int b=20; System.out.println("Value of a before swapping = "+a); System.out.println("Value of b before swapping = "+b); a=a+b;// a has now value 30 b=a-b;// b has now value 10 a=a-b;// a has now value 20 System.out.println(""); System.out.println("Value of a after swapping = "+a); System.out.println("Value of b after swapping = "+b); } }
Output from the program
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Swapping of two numbers without using third variable
Post your Comment | http://www.roseindia.net/java/java-conversion/swapping-program.shtml | CC-MAIN-2014-41 | refinedweb | 311 | 62.38 |
t0mm0 Wrote:i've already discussed in eldorados thread that this will be fixed. i'm afraid i'm really busy at the moment and might not get to do much for a couple of weeks (see the post above yours)
thanks,
t0mm0
k_zeon Wrote:Hi t0mm0
just been playing around with eldorados new metautils and he said that at present i cannot add infolabels to directories but only on addvideoitem
just wondered if this is something that will be implemented and if poss a timescale.
many thanks for all your hard work
def unescape(self, text):
'''
Decodes HTML entities in a string.
You can add more entities to the ``rep`` dictionary.
Args:
text (str): String to be cleaned.
Returns:
Cleaned string.
'''
try:
text = self.decode(text)
rep = {'<': '<',
'>': '>',
'"': '"',
'’': '\'',
'´': '\'',
}
for s, r in rep.items():
text = text.replace(s, r)
# this has to be last:
text = text.replace("&", "&")
[b] except TypeError:
pass[/b]
return text
k_zeon Wrote:Hey Eldorado
Just added the fix to t0mm0's common module and then run ProjectfreeTV and it appears to run and scrape info.
Then when i scoll through the movies , the pics change and also the background but then all of a sudden the picture does not change and then scrolling back the pics that did show do not change. It stays the same.
No errors appear so do not know reason why....
Running my addon seems fine..
Edit:
Just took out the Fanart part ( fanart=meta['backdrop_url'] ) for the menu adding function and then it works fine.
Would be good to have an option to turn fanart downloading off.
t0mm0 Wrote:sorry for my lack of work recently, my excuse is a combination of busy-ness (work and non-work) not feeling well and my phone deciding not to alert me of new emails to my dev account
anyway, i'll get back to work again now honest and try and get a urlresolver release done ASAP
t0mm0
Eldorado Wrote:I have feature requests for your common library
t0mm0 Wrote:cool - request away!
i know already requested is to make adding directories and items take the same arguments....
t0mm0
Eldorado Wrote:Context menu item support is my next one, I saw the chat between you and Dragonwin on it but wasn't sure if any code was done to handle it.. ?
t0mm0 Wrote:Dragonwin's code is here
i haven't looked at it much yet (just getting through the pull requests at the moment) - let me know if that code does what you need. (maybe you could specify what you want it to do so i don't break it if i change that code?)
also is the add_directory() stuff okay for you now?
thanks,
t0mm0 | http://forum.kodi.tv/printthread.php?tid=105707&page=16 | CC-MAIN-2014-52 | refinedweb | 454 | 69.62 |
C++ Portability Guide
From MDC <insert favorite C++ feature>." But this is the reality of portable code. If you play by the rules, your code will seamlessly work on all of the Mozilla platforms and will be easy to port to newer machines.
We will endeavor to keep the information up to date (for example, sometimes a new compiler revision will lift a restriction). If you have updates on any of these tips, more information, more ideas, please forward them to Christopher Blizzard, Scott Collins, or David Baron.
If you find code in Mozilla that violates any of these rules, please report it as a bug. You can use bonsai to find the author.
None of these rules is absolute. If patch authors can demonstrate that what they want to do works on all the compilers we support, they're welcome to break, and revise, these rules. However, this is a lot of work, and is not recommended unless you have a very good reason for wanting to do it.
[edit] C++ portability rules
[edit] Be very careful when writing C++ templates
Don't use C++ templates unless you do only things already known to be portable because they are already used in Mozilla (such as patterns used by
nsCOMPtr or
CallQueryInterface) or are willing to test your code carefully on all of the compilers we support and be willing to back it out if it breaks.
[edit] Don't use static constructors
Non-portable example:
FooBarClass static_object(87, 92); void bar() { if (static_object.count > 15) { ... } }
Static constructors don't work reliably either. A static initialized object is an object which is instantiated at startup time (just before
main() is called). Usually there are two components to these objects. First there is the data segment which is static data loaded into the global data segment of the program. The second part is a initializer function that is called by the loader before
main() is called. We've found that many compilers do not reliably implement the initializer function. So you get the object data, but it is never initialized. One workaround for this limitation is to write a wrapper function that creates a single instance of an object, and replace all references to the static initialized object with a call to the wrapper function:
Portable example:
static FooBarClass* static_object; FooBarClass* getStaticObject() { if (!static_object) static_object = new FooBarClass(87, 92); return static_object; } void bar() { if (getStaticObject()->count > 15) { ... } }
[edit] Don't use exceptions
Exceptions are another C++ feature which is not very widely implemented, and as such, their use is not portable C++ code. Don't use them. Unfortunately, there is no good workaround that produces similar functionality.
One exception to this rule (don't say it) is that it's probably ok, and may be necessary to use exceptions in some machine specific code. If you do use exceptions in machine specific code you must catch all exceptions there because you can't throw the exception across XP (cross platform) code.
[edit] Don't use Run-time Type Information
Run-time type information (RTTI) is a relatively new C++ feature, and not supported in many compilers. Don't use it..
[edit] Don't use C++ standard library features, including iostream
Using C++ standard library features involves significant portability problems because newer compilers require the use of namespaces and of headers without
.h, whereas older compilers require the opposite. This includes iostream features, such as
cin and
cout.
Furthermore, using the C++ standard library imposes difficulties on those attempting to use Mozilla on small devices.
There is one exception to this rule: it is acceptable to use placement new. To use it, include the standard header
<new> by writing
#include NEW_H.
[edit] Don't use namespace facility
Support of namespaces (through the
namespace and
using keywords) is a relatively new C++ feature, and not supported in many compilers. Don't use it.
[edit]
main() must be in a C++ file
The first C++ compiler, Cfront, was in fact a very fancy preprocessor for a C compiler. Cfront reads the C++ code, and generates C code that would do the same thing. C++ and C startup sequences are different (for example static constructor functions must be called for C++), and Cfront implements this special startup by noticing the function called "
main()", converting it to something else (like "
__cpp__main()"), adding another
main() that does the special C++ startup things and then calls the original function. Of course for all this to work, Cfront needs to see the
main() function, hence
main() must be in a C++ file. Most compilers lifted this restriction years ago, and deal with the C++ special initialization duties as a linker issue. But there are a few commercial compilers shipping that are still based on Cfront: HP, and SCO, are examples.
So the workaround is quite simple. Make sure that
main() is in a C++ file. On the Unix version of Mozilla, we did this by adding a new C++ file which has only a few lines of code, and calls the main
main() which is actually in a C file.
[edit] Use the common denominator between members of a C/C++ compiler family
For many of the compiler families we use, the implementation of the C and C++ compilers are completely different, sometimes this means that there are things you can do in the C language, that you cannot do in the C++ language on the same machine. One example is the 'long long' type. On some systems (IBM's compiler used to be one, but I think it's better now), the C compiler supports long long, while the C++ compiler does not. This can make porting a pain, as often times these types are in header files shared between C and C++ files. The only thing you can do is to go with the common denominator that both compilers support. In the special case of long long, we developed a set of macros for supporting 64 bit integers when the long long type is not available. We have to use these macros if either the C or the C++ compiler does not support the special 64 bit type.
[edit] Don't put C++ comments in C code
The quickest way to raise the blood pressure of a Netscape Unix engineer is to put C++ comments (
// comments) into C files. Yes, this might work on your Microsoft Visual C compiler, but it's wrong, and is not supported by the vast majority of C compilers in the world. Just do not go there.
Many header files will be included by C files and included by C++ files. We think it's a good idea to apply this same rule to those headers. Don't put C++ comments in header files included in C files. You might argue that you could use C++ style comments inside
#ifdef __cplusplus blocks, but we are not convinced that is always going to work (some compilers have weird interactions between comment stripping and pre-processing), and it hardly seems worth the effort. Just stick to C style
/**/ comments for any header file that is ever likely to be included by a C file.
[edit] Don't put carriage returns in XP code
While this is not specific to C++, we have seen this as more of an issue with C++ compilers, see Use the common denominator between members of a C/C++ compiler family. In particular, it causes bustage on at least the IRIX native compiler.
On unix systems, the standard end of line character is line feed (
'\n'). The standard on many PC editors is carriage return and line feed (
"\r\n"), while the standard on Mac is carriage return (
"\r"). The PC compilers seem to be happy either way, but some Unix compilers just choke when they see a carriage return (they do not recognize the character as white space). So, we have a rule that you cannot check in carriage returns into any cross platform code. This rule is not enforced on the Windows front end code, as that code is only ever compiled on a PC. The Mac compilers seem to be happy either way, but the same rule applies as for the PC - no carriage returns in cross platform code.
MacCVS, WinCVS, and cygwin CVS when configured to use DOS line endings automatically convert to and from platform line endings, so you don't need to worry. However, if you use cygwin CVS configured for Unix line endings, or command line cvs on Mac OS X, you need to be somewhat careful.
[edit] Put a new line at end-of-file
Not having a new-line char at the end of file breaks .h files with the Sun WorkShop compiler and it breaks .cpp files on HP.
[edit] Don't put extra top-level semi-colons in code
Non-portable example:
int A::foo() { };
This is another problem that seems to show up more on C++ than C code. This problem is really a bit of a drag. That extra little semi-colon at the end of the function is ignored by most compilers, but it is not permitted by the standard and it makes some compilers report errors (in particular, gcc 3.4, and also perhaps old versions of the AIX native compiler). Don't do it.
Portable example:
int A::foo() { }
[edit] C++ filename extension is
.cpp
This one is another plain annoying problem. What's the name of a C++ file?
file.cpp,
file.cc,
file.C,
file.cxx,
file.c++,
file.C++? Most compilers could care less, but some are very particular. We have not been able to find one file extension which we can use on all the platforms we have ported Mozilla code to. For no great reason, we've settled on
file.cpp, probably because the first C++ code in Mozilla code was checked in with that extension. Well, it's done. The extension we use is
.cpp. This extension seems to make most compilers happy, but there are some which do not like it. On those systems we have to create a wrapper for the compiler (see
STRICT_CPLUSPLUS_SUFFIX in
ns/config/rules.mk and
ns/build/*), which actually copies the
file.cpp file to another file with the correct extension, compiles the new file, then deletes it. If in porting to a new system, you have to do something like this, make sure you use the
#line directive so that the compiler generates debug information relative to the original
.cpp file.
[edit] Don't mix varargs and inlines
Non-portable example:
class FooBar { void va_inline(char* p, ...) { // <span class="remark">something</span> } };
The subject says it all, varargs and inline functions do not seem to mix very well. If you must use varargs (which can cause portability problems on their own), then ensure that the vararg member function is a non-inline function.
Portable example:
// <span class="remark">foobar.h</span> class FooBar { void va_non_inline(char* p, ...); }; // <span class="remark">foobar.cpp</span> void FooBar::va_non_inline(char* p, ...) { // <span class="remark">something</span> }
[edit] Don't use initializer lists with objects
Non-portable example:
FooClass myFoo = {10, 20};
Some compilers won't allow this syntax for objects (HP-UX won't), actually only some will allow it. So don't do it. Again, use a wrapper function, see Don't use static constructors.
[edit] Always have a default constructor
Always have a default constructor, even if it doesn't make sense in terms of the object structure/hierarchy. HP-UX will barf on statically initialized objects that don't have default constructors.
[edit] Be careful with inner (nested) classes
When using nested classes, be careful with access control. While most compilers implement (whether intentionally or not) the rules in the 2003 version of the C++ standard that give nested classes special access to the members of their enclosing class, some compilers implement what is described in the 1998 version of the standard, which is that nested classes have no special access to members of their enclosing class.
Non-portable example:
class Enclosing { private: int x; public: struct Nested { void do_something(Enclosing *E) { ++E->x; } }; };
portable example:
class Enclosing { private: int x; public: struct Nested; // forward declare |Nested| so the |friend| // declaration knows what scope it's in. friend struct Nested; // make |Nested| a friend of its enclosing // class struct Nested { void do_something(Enclosing *E) { ++E->x; } }; };
A second non-portable example:
class Enclosing { private: struct B; struct A { B *mB; }; struct B { A *mA; }; };
and the equivalent portable example:
class Enclosing { private: struct A; friend struct A; struct B; friend struct B; struct A { B *mB; }; struct B { A *mA; }; };
[edit] Be careful of variable declarations that require construction or initialization
Non-portable example:
void A::foo(int c) { switch(c) { case FOOBAR_1: XyzClass buf(100); // <span class="remark">stuff</span> break; } }
Be careful with variable placement around if blocks and switch statements. Some compilers (HP-UX) require that any variable requiring a constructor/initializer to be run, needs to be at the start of the method -- it won't compile code when a variable is declared inside a switch statement and needs a default constructor to run.
Portable example:
void A::foo(int c) { XyzClass buf(100); switch(c) { case FOOBAR_1: // <span class="remark">stuff</span> break; } }
[edit] Make header files compatible with C and C++
Non-portable example:
/*<span class="remark">oldCheader.h</span>*/ int existingCfunction(char*); int anotherExistingCfunction(char*); /*<span class="remark"> oldCfile.c </span>*/ #include "oldCheader.h" ... // <span class="remark">new file.cpp</span> extern "C" { #include "oldCheader.h" }; ...
If you make new header files with exposed C interfaces, make the header files work correctly when they are included by both C and C++ files. If you start including an existing C header in new C++ files, fix the C header file to support C++ (as well as C), don't just
extern "C" {} the old header file. Do this:
Portable example:
/*<span class="remark">oldCheader.h</span>*/ PR_BEGIN_EXTERN_C int existingCfunction(char*); int anotherExistingCfunction(char*); PR_END_EXTERN_C /*<span class="remark"> oldCfile.c </span>*/ #include "oldCheader.h" ... // <span class="remark">new file.cpp</span> ...
Some systems include C++ in system header files that are designed to be included by C or C++. Not just
extern "C" {} guarding, but actual C++ code, usually in the form of inline functions that serve as "optimizations". While we question the wisdom of vendors doing this, there is nothing we can do about it. Changing system header files, is not a path we wish to take. Anyway, so why is this a problem? Take for example the following code fragment:
Non-portable example:
/*<span class="remark">system.h</span>*/ #ifdef __cplusplus /*<span class="remark"> optimization </span>*/ inline int sqr(int x) {return(x*x);} #endif /*<span class="remark">header.h</span>*/ #include <system.h> int existingCfunction(char*); // <span class="remark">file.cpp</span> extern "C" { #include "header.h" }
What's going to happen? When the C++ compiler finds the
extern "C" declaration in
file.cpp, it will switch dialects to C, because it's assumed all the code inside is C code, and C's type free name rules need to be applied. But the __cplusplus pre-processor macro is still defined (that's seen by the pre-processor, not the compiler). In the system header file the C++ code inside the
#ifdef __cplusplus block will be seen by the compiler (now running in C mode). Syntax Errors galore! If instead the
extern "C" was done in the header file, the C functions can be correctly guarded, leaving the systems header file out of the equation. This works:
Portable example:
/*<span class="remark">system.h</span>*/ #ifdef __cplusplus /*<span class="remark"> optimization </span>*/ inline int sqr(int x) {return(x*x);} #endif /*<span class="remark">header.h</span>*/ #include <system.h> extern "C" { int existingCfunction(char*); } // <span class="remark">file.cpp</span> #include "header.h"
One more thing before we leave the
extern "C" segment of the program. Sometimes you're going to have to
extern "C" system files. This is because you need to include C system header files that do not have
extern "C" guarding themselves. Most vendors have updated all their headers to support C++, but there are still a few out there that won't grok C++. You might have to do this only for some platforms, not for others (using
#ifdef SYSTEM_X). The safest place to do
extern "C" a system header file (in fact the safest place to include a system header file) is at the lowest place possible in the header file inclusion hierarchy. That is, push all this stuff down to the header files closer to the system code, don't do this stuff in the mail header files. Ideally the best place to do this is in the NSPR or XP header files - which sit directly on the system code.
[edit] Be careful of the scoping of variables declared inside
for() statements
Non-portable example:
void A::foo() { for (int i = 0; i < 10; i++) { // <span class="remark">do something</span> } // <span class="remark"><strong>i</strong> might get referenced</span> // <span class="remark"> after the loop.</span> ... }
This is actually an issue that comes about because the C++ standard has changed over time. The original C++ specification would scope the i as part of the outer block (in this case function
A::foo()). The standard changed so that now the i in is scoped within the
for() {} block. Most compilers use the new standard. Some compilers (for example, Microsoft Visual C++ when used without an option supported only in newer versions, or the HP-UX compiler when used without a compiler option that we use) still use the old standard. It's probably better to be on the safe side and declare the iterator variable outside of the
for() loop in functions that are longer than a few lines. Then you'll know what you are getting on all platforms:
Portable example:
void A::foo() { int i; for (i = 0; i < 10; i++) { // <span class="remark">do something</span> } // <span class="remark"><strong>i</strong> might get referenced</span> // <span class="remark"> after the loop.</span> ... }
Also you should not reuse a for loop variable in subsequent for loops or otherwise redeclare the variable. This is permitted by the current standard, but many compilers will treat this as an error. See the example below:
Non-portable example:
void A::foo() { for (int <strong>i</strong>; 0;) { // <span class="remark">do something</span> } for (int <strong>i</strong>; 0;) { // <span class="remark">do something else</span> } }
Portable example:
void A::foo() { for (int <strong>i</strong>; 0;) { // <span class="remark">do something</span> } for (int <strong>j</strong>; 0;) { // <span class="remark">do something else</span> } }
[edit] Declare local initialized aggregates as static
Non-portable example:
void A:: func_foo() { char* foo_int[] = {"1", "2", "C"}; ... }
This seemingly innocent piece of code will generate a "loader error" using the HP-UX compiler/linker. If you really meant for the array to be static data, say so:
Portable example:
void A:: func_foo() { static char *foo_int[] = {"1", "2", "C"}; ... }
Otherwise you can keep the array as an automatic, and initialize by hand:
Portable example:
void A:: func_foo() { char *foo_int[3]; foo_int[0] = XP_STRDUP("1"); foo_int[1] = XP_STRDUP("2"); foo_int[2] = XP_STRDUP("C"); // <span class="remark">or something equally Byzantine...</span> ... }
[edit] Expect complex inlines to be non-portable
Non-portable example:
class FooClass { ... int fooMethod(char* p) { if (p[0] == '\0') return -1; doSomething(); return 0; } ... };
It's surprising, but many C++ compilers do a very bad job of handling inline member functions. Cfront based compilers (like those on SCO and HP-UX) are prone to give up on all but the most simple inline functions, with the error message "sorry, unimplemented". Often times the source of this problem is an inline with multiple return statements. The fix for this is to resolve the returns into a single point at the end of the function. But there are other constructs which will result in "not implemented". For this reason, you'll see that most of the C++ code in Mozilla does not use inline functions. We don't want to legislate inline functions away, but you should be aware that there is some danger in using them, so do so only when there is some measurable gain (not just a random hope of performance win). Maybe you should just not go there.
Portable example:
class FooClass { ... int fooMethod(char* p) { int return_value; if (p[0] == '\0') { return_value = -1; } else { doSomething(); return_value = 0; } return return_value; } ... };
Or
class FooClass { ... int fooMethod(char* p); ... }; int FooClass::fooMethod(char* p) { if (p[0] == '\0') return -1; doSomething(); return 0; }
[edit] Don't use return statements that have an inline function in the return expression
For the same reason as the previous tip, don't use return statements that have an inline function in the return expression. You'll get that same "sorry, unimplemented" error. Store the return value in a temporary, then pass that back.
[edit] Be careful with the include depth of files and file size
Be careful with the include depth of files and file size. The Microsoft Visual C++1.5 compiler will generate internal compiler errors if you have a large include depth or large file size. Be careful to limit the include depth of your header files as well as your file size.
[edit] Use virtual declaration on all subclass virtual member functions
Non-portable example:
class A { virtual void foobar(char*); }; class B : public A { void foobar(char*); };
Another drag. In the class declarations above,
A::foobar() is declared as virtual. C++ says that all implementations of void
foobar(char*) in subclasses will also be virtual (once virtual, always virtual). This code is really fine, but some compilers want the virtual declaration also used on overloaded functions of the virtual in subclasses. If you don't do it, you get warnings. While this is not a hard error, because this stuff tends to be in headers files, you'll get so many warnings that's you'll go nuts. Better to silence the compiler warnings, by including the virtual declaration in the subclasses. It's also better documentation:
Portable example:
class A { virtual void foobar(char*); }; class B : public A { virtual void foobar(char*); };
[edit] Always declare a copy constructor and assignment operator
One feature of C++ that can be problematic is the use of copy constructors. Because a class's copy constructor defines what it means to pass and return objects by value (or if you prefer, pass by value means call the copy constructor), it's important to get this right. There are times when the compiler will silently generate a call to a copy constructor, that maybe you do not want. For example, when you pass an object by value as a function parameter, a temporary copy is made, which gets passed, then destroyed on return from the function. Maybe you don't want this to happen, maybe you'd always like instances of your class to be passed by reference. If you do not define a copy constructor the C++ compiler will generate one for you (the default copy constructor), and this automatically generated copy constructor might, well, suck. So you have a situation where the compiler is going to silently generate calls to a piece of code that might not be the greatest code for the job (it may be wrong).
Ok, you say, "no problem, I know when I'm calling the copy constructor, and I know I'm not doing it". But what about other people using your class? The safe bet is to do one of two things: if you want your class to support pass by value, then write a good copy constructor for your class. If you see no reason to support pass by value on your class, then you should explicitly prohibit this, don't let the compiler's default copy constructor do it for you. The way to enforce your policy is to declare the copy constructor as private, and not supply a definition. While you're at it, do the same for the assignment operator used for assignment of objects of the same class. Example:
class foo { ... private: // <span class="remark">These are not supported</span> // <span class="remark">and are not implemented!</span> foo(const foo& x); foo& operator=(const foo& x); };
When you do this, you ensure that code that implicitly calls the copy constructor will not compile and link. That way nothing happens in the dark. When a user's code won't compile, they'll see that they were passing by value, when they meant to pass by reference (oops).
[edit] Be careful of overloaded methods with like signatures
It's best to avoid overloading methods when the type signature of the methods differs only by 1 "abstract" type (e.g.
PR_Int32 or
int32). What you will find as you move that code to different platforms, is suddenly on the Foo2000 compiler your overloaded methods will have the same type-signature.
[edit] Type scalar constants to avoid unexpected ambiguities
Non-portable code:
class FooClass { // <span class="remark">having such similar signatures</span> // <span class="remark">is a bad idea in the first place.</span> { // <span class="remark">having such similar signatures</span> // <span class="remark">is a bad idea in the first place.</span> void doit(long); void doit(short); }; void B::foo(FooClass* xyz) { xyz->doit(45L); }
[edit] Type scalar constants to avoid unexpected ambiguities
Some platforms (e.g. Linux) have native definitions of types like Bool which sometimes conflict with definitions in XP code. Always use PRBool (PR_TRUE, PR_FALSE).
[edit] Don't use mutable
Not all C++ compilers support the
mutable keyword:
You'll have to use the "fake this" approach to cast away the constness of a data member:
void MyClass::MyConstMethod() const { MyClass * mutable_this = NS_CONST_CAST(MyClass *,this); // Treat mFoo as mutable mutable_this->mFoo = 99; }
[edit] Use nsCOMPtr in XPCOM code
Mozilla has recently adopted the use of nsCOMPtr in XPCOM code.
See the nsCOMPtr User Manual for usage details.
[edit] Don't use reserved words as identifiers.
[edit] Stuff that is good to do for C or C++
[edit] Always use the nspr types for intrinsic types
Always use the nspr types for intrinsic integer types. The only exception to this rule is when writing machine dependent code that is called from xp code. In this case you will probably need to bridge the type systems and cast from an nspr type to a native type.
[edit] Do not wrap include statements with an
#ifdef
Do not wrap include statements with an
#ifdef. The reason is that when the symbol is not defined, other compiler symbols will not be defined and it will be hard to test the code on all platforms. An example of what not to do:
Bad code example:
// don't do this #ifdef X #include "foo.h" #endif
The exception to this rule is when you are including different system files for different machines. In that case, you may need to have a
#ifdef SYSTEM_X include.
[edit]
#include statements should include only simple filenames
Non-portable example:
#include "directory/filename.h"
Mac compilers handle
#include path names in a different manner to other systems. Consequently
#include statements should contain just simple file names. Change the directories that the compiler searches to get the result you need, but if you follow the Mozilla module and directory scheme, this should not be required.
Portable example:
#include "filename.h"
[edit] Macs complain about assignments in boolean expressions
Another example of code that will generate warnings on a Mac:
Generates warnings code:
if ((a = b) == c) ...
Macs don't like assignments in if statements, even if you properly wrap them in parentheses.
More portable example:
a=b; if (a == c) ...
[edit] Every source file must have a unique name
Non-portable file tree:
feature_x private.h x.cpp feature_y private.h y.cpp
For Mac compilers, every file has to have a unique name. Don't assume that just because your file is only used locally that it's OK to use the same name as a header file elsewhere. It's not ok. Every filename must be different.
Portable file tree:
feature_x xprivate.h x.cpp feature_y yprivate.h y.cpp
[edit] Use
#if 0 rather than comments to temporarily kill blocks of code
Non-portable example:
int foo() { ... a = b + c; /* * Not doing this right now. a += 87; if (a > b) (* have to check for the candy factor *) c++; */ ... }
This is a bad idea, because you always end up wanting to kill code blocks that include comments already. No, you can't rely on comments nesting properly. That's far from portable. You have to do something crazy like changing
/**/ pairs to
(**) pairs. You'll forget. And don't try using
#ifdef NOTUSED, the day you do that, the next day someone will quietly start defining
NOTUSED somewhere. It's much better to block the code out with a
#if 0,
#endif pair, and a good comment at the top. Of course, this kind of thing should always be a temporary thing, unless the blocked out code fulfills some amazing documentation purpose.
Portable example:
int foo() { ... a = b + c; #if 0 /*<span class="remark"> Not doing this right now. </span>*/ a += 87; if (a > b) /*<span class="remark"> have to check for the candy factor </span>*/ c++; #endif ... }
[edit] Turn on warnings for your compiler, and then write warning free code
This might be the most important tip. Beware lenient compilers! What generates a warning on one platform will generate errors on another. Turn warnings on. Write warning free code. It's good for you.
[edit] Use the same type for all bitfields in a
struct (or
class in C++)
Some compilers (even recent ones like MSVC++ 8) mishandle code which uses different types for bitfields and fail to properly pack the bits, even when they should be packed. For example, the following struct might be miscompiled to have a size of 8 bytes, even though it fits in 1:
struct { char ch : 1; int i : 1; };
[edit] Use an unsigned type (not
PRBool) for a bitfield which represents a boolean value
If you want to represent a bool value in a single bit, use an unsigned type to do so. If you use a signed type (this includes
PRBool), its value when set will be -1 instead of +1, which violates XPCOM convention.
[edit] Revision History
- 0.5 Initial Revision. 3-27-1998 David Williams
- 0.6 Added "C++ Style casts" and "mutable" entries. 12-24-1998 Ramiro Estrugo
- 0.7 Added "nsCOMPtr" entry and mozillaZine resource link. 12-02-1999 Ramiro Estrugo
- 0.8 Added "reserved words" entry. 2-01-2001 Scott Collins
[edit] Further reading
Here are some books and pages which provide further good advice on how to write portable C++ code.
- Scott Meyers, Effective C++ : 50 Specific Ways to Improve Your Programs and Designs
- Robert B. Murray, C++ Strategies and Tactics
- mozillaZine has a list of books on C++, Anti-C++, OOP (and other buzzwords). This list was compiled from the suggestions of Mozilla developers.
- others?
[edit] Original Document Information
- Author(s): David Williams
- Other Contributors: Scott Collins, Christopher Blizzard, and David Baron
- Last Updated Date: August 10, 2007
- Copyright Information: Portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. | http://developer.mozilla.org/en/docs/C%2B%2B_Portability_Guide | crawl-001 | refinedweb | 5,273 | 62.17 |
Hot questions for Using Neural networks in non linear regression
Question:
Is there any difference in the architecture of a neural net for regression (time series prediction) and for classification?
I did some regression testing but I get quite bad results.
I'm currently using a basic feed forward net, with one hidden layer with 2 to 4 neurons,
tanh activation function and momentum.
Answer:
It depends on a lot of factors :
In case of classification you can have a binary classification problem (where you want to discriminate between two classes) or multinomial classification problem. In both cases you could use different architectures for achieving the goal of the best data modeling.
In case of sequence regression - you could also use loads of different architectures - starting from normal feedforward network which receives one series as input and returns second as output to a lot different recurent architectures.
So the question you asked is similiar to : are tools useful for building cars different from tools useful for building bridges - it's too ambiguous and you have to specify more details.
Question:
I don't understand why my code wouldn't run. I started with the TensorFlow tutorial to classify the images in the mnist data set using a single layer feedforward neural net. Then modified the code to create a multilayer perceptron that maps out 37 inputs to 1 output. The input and output training data are being loaded from Matlab data file (.mat)
Here is my code..
from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy.io import loadmat %matplotlib inline import tensorflow as tf from tensorflow.contrib import learn X = np.array(loadmat("Data/DataIn.mat")['TrainingDataIn']) Y = np.array(loadmat("Data/DataOut.mat")['TrainingDataOut']) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5) total_len = X_train.shape[0] # Parameters learning_rate = 0.001 training_epochs = 500 batch_size = 10 display_step = 1 dropout_rate = 0.9 # Network Parameters n_hidden_1 = 19 # 1st layer number of features n_hidden_2 = 26 # 2nd layer number of features n_input = X_train.shape[1] n_classes = 1 # tf Graph input X = tf.placeholder("float32", [None, 37]) Y = tf.placeholder("float32", [None]) def multilayer_perceptron(X, weights, biases): # Hidden layer with RELU activation layer with linear activation out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1], 0, 0.1)), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], 0, 0.1)), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], 0, 0.1)) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1], 0, 0.1)), 'b2': tf.Variable(tf.random_normal([n_hidden_2], 0, 0.1)), 'out': tf.Variable(tf.random_normal([n_classes], 0, 0.1)) } # Construct model pred = multilayer_perceptron(X, weights, biases) tf.shape(pred) tf.shape(Y) print("Prediction matrix:", pred) print("Output matrix:", Y) # Define loss and optimizer cost = tf.reduce_mean(tf.square(pred-Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Launch the graph with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(total_len/batch_size) print(total_batch) # Loop over all batches for i in range(total_batch-1): batch_x = X_train[i*batch_size:(i+1)*batch_size] batch_y = Y_train[i*batch_size:(i+1)*batch_size] # Run optimization op (backprop) and cost op (to get loss value) _, c, p = sess.run([optimizer, cost, pred], feed_dict={X: batch_x, Y: batch_y}) # Compute average loss avg_cost += c / total_batch # sample prediction label_value = batch_y estimate = p err = label_value-estimate print ("num batch:", total_batch) # Display logs per epoch step if epoch % display_step == 0: print ("Epoch:", '%04d' % (epoch+1), "cost=", \ "{:.9f}".format(avg_cost)) print ("[*]----------------------------") for i in xrange(5): print ("label value:", label_value[i], \ "estimated value:", estimate[i]) print ("[*]============================") print ("Optimization Finished!") # Test model correct_prediction = tf.equal(tf.argmax(pred), tf.argmax(Y)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print ("Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))
when I run the code I get error messages:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-6b8af9192775> in <module>() 93 # Run optimization op (backprop) and cost op (to get loss value) 94 _, c, p = sess.run([optimizer, cost, pred], feed_dict={X: batch_x, ---> 95 Y: batch_y}) 96 # Compute average loss 97 avg_cost += c / total_batch ~\AppData\Local\Continuum\Anaconda3\envs\ann\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata) 787 try: 788 result = self._run(None, fetches, feed_dict, options_ptr, --> 789 run_metadata_ptr) 790 if run_metadata: 791 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) ~\AppData\Local\Continuum\Anaconda3\envs\ann\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 973 'Cannot feed value of shape %r for Tensor %r, ' 974 'which has shape %r' --> 975 % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) 976 if not self.graph.is_feedable(subfeed_t): 977 raise ValueError('Tensor %s may not be fed.' % subfeed_t) ValueError: Cannot feed value of shape (10, 1) for Tensor 'Placeholder_7:0', which has shape '(?,)'
Answer:
I've encountered this problem before. The difference is that a Tensor of shape
(10, 1) looks like
[[1], [2], [3]], while a Tensor of shape
(10,) looks like
[1, 2, 3].
You should be able to fix it by changing the line
Y = tf.placeholder("float32", [None])
to:
Y = tf.placeholder("float32", [None, 1])
Question:
My goal is to create a neural network with a single hidden layer (with ReLU activation) that is able to approximate a simple univariate square root function. I have implemented the network with numpy, also did a gradient check, everything seems to be fine, except for the result: for some reason I can only obtain linear approximations, like this: noisy sqrt approx
Tried changing the hyperparameters, without any success. Any ideas?
import numpy as np step_size = 1e-6 input_size, output_size = 1, 1 h_size = 10 train_size = 500 x_train = np.abs(np.random.randn(train_size, 1) * 1000) y_train = np.sqrt(x_train) + np.random.randn(train_size, 1) * 0.5 #initialize weights and biases Wxh = np.random.randn(input_size, h_size) * 0.01 bh = np.zeros((1, h_size)) Why = np.random.randn(h_size, output_size) * 0.01 by = np.zeros((1, output_size)) for i in range(300000): #forward pass h = np.maximum(0, np.dot(x_train, Wxh) + bh1) y_est = np.dot(h, Why) + by loss = np.sum((y_est - y_train)**2) / train_size dy = 2 * (y_est - y_train) / train_size print("loss: ",loss) #backprop at output dWhy = np.dot(h.T, dy) dby = np.sum(dy, axis=0, keepdims=True) dh = np.dot(dy, Why.T) #backprop ReLU non-linearity dh[h <= 0] = 0 #backprop Wxh, and bh dWxh = np.dot(x_train.T, dh) dbh = np.sum(dh1, axis=0, keepdims=True) Wxh += -step_size * dWxh bh += -step_size * dbh Why += -step_size * dWhy by += -step_size * dby
Edit: It seems the problem was the lack of normalization and the data being non-zero centered. After applying these transformation on the training the data, I have managed to obtain the following result: noisy sqrt2
Answer:
I can get your code to produce a sort of piecewise linear approximation:
if I zero-centre and normalise your input and output ranges:
# normalise range and domain x_train -= x_train.mean() x_train /= x_train.std() y_train -= y_train.mean() y_train /= y_train.std()
Plot is produced like so:
x = np.linspace(x_train.min(),x_train.max(),3000) y = np.dot(np.maximum(0, np.dot(x[:,None], Wxh) + bh), Why) + by import matplotlib.pyplot as plt plt.plot(x,y) plt.show()
Question:
I am trying to run a MLP regressor on my dataset with one hidden layer. I am doing a standardization of my data but I want to be clear as whether it matters if I do the standardization after or before splitting the dataset in Training and Test set. I want to know if there will be any difference in my prediction values if I carry out standardization before data split.
Answer:
Yes and no. If mean and variance of the training and test set are different, standardization can lead to a different outcome.
That being said, a good training and test set should be similar enough so that the data points are distributed in a similar way, and post-split standardization should give the same results.
Question:
I am new to ML, and I have a dataset:
Where:
X = {X_1, X_2, X_3, X_4, X_5, X_6, X_7}; Y = Y;
I'm trying to find the possible relationship between X and Y like Y = M(X) using Deep Learning. To my knowledge, this is a regression task since the data type of my target Y is real.
I have tried some regression algorithms like LMS and Stepwise regression but none of those gives me a promising result. So I'm turning into the deep neural network solution, so:
- Can ANN do this regression task?
- How to design the network, especially the type of layers, activation function, etc.?
- Is there some existing NN architecture I can refer to?
Any help is appreciated.
Answer:
I don't have a solution for the machine learning part, but I do have a solution that would maybe work (since you asked for any other solutions).
I will say it might be difficult to use machine learning, since not only do you need to find a relationship (assuming there is one), but you need to find the right type of model (is it linear, quadratic, exponential, sinusoidal, etc.) and then you need to find the parameters for those models.
In the R programming language, it is easy to set up a multiple linear regression, for example. Here is a sketch of the R code you would use to find a linear regression.
data = load("data.Rdata") # or load a table or something regression = lm(Y ~ X1 + X2 + X3 + X4 + X5 + X6 + x7, data = data) print(summary(regression))
Edit: you might get better answers here: | https://thetopsites.net/projects/neural-network/non-linear-regression.shtml | CC-MAIN-2021-31 | refinedweb | 1,615 | 50.23 |
On Sat, 14 Apr 2007 03:42:52 -0700, samjnaa wrote: > Please check for sanity and approve for posting at python-dev. > > In Visual Basic there is the keyword "with" which allows an object- > name to be declared as governing the following statements. For > example: > > with quitCommandButton > .enabled = true > .default = true > end with > > This is syntactic sugar for: > > quitCommandButton.enabled=true > quitCommandButton.default=true Which is very much like Pascal's with block. This question has been asked before: Despite what the Effbot says, I believe that there is no ambiguity that can't be resolved. Specifying that names used in a using-block have a leading dot makes it obvious to the compiler which names are shortened: using longname: x = .attribute # must be longname.attribute If we forbid nested using-blocks, then all you need is a pre-processor to change ".attribute" to "longname.attribute". There's never any ambiguity. But if you want to be really ambitious, one might allow nested using-blocks. Now the compiler can't resolve names with leading dots at parse-time, and has to search namespaces at runtime, but that's no different from what Python already does. using longname: using anotherlongname: x = .attr In this case, at Python has to determine at runtime which object has an attribute "attr". If that sounds familiar, it should: that's exactly what happens when you say instance.attribute: Python searches instance.__dict__ then instance.__class__.__dict__, and any superclasses. There is one slight ambiguity left: should Python search longname first or anotherlongname? But that decision has come up before, for nested scopes in functions. It seems obvious to me that Python should search deepest to most shallow, the same way that function nested scopes work. So the above nested block would be equivalent to: try: x = anotherlongname.attr except AttributeError: try: x = longname.attr except AttributeError: raise UsingError('no such attribute') One might even allow a construct like this: using longname, anotherlongname: x = .attr In this case, the search resolution order would be from left to right, that is, longname before anotherlongname. -- Steven. | https://mail.python.org/pipermail/python-list/2007-April/426966.html | CC-MAIN-2019-30 | refinedweb | 348 | 58.99 |
django-loginurl 0.1.4
Allowing an anonymous user to log in by only visiting a URL
This is a simple application for Django that allows an anonymous visitor to log in as a user by only visiting a URL.
By default, the URL is only valid once and cannot be used multiple times. Other schemes that involve the number of visit and/or an expiry date can also be created. For example, it is possible to create a log in URL that only valid for 5 visits before next week using this application.
Configuration
Add django-loginurl application into your Django project. Modify your settings.py like the following:
INSTALLED_APPS = ( ... 'loginurl', ... )
Add the authentication backend of this django-loginurl application to your project's settings.py.
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'loginurl.backends.LoginUrlBackend', )
The first authentication backend is the default and if your project uses the Django's standard authentication mechanism, you will need that.
Consult the Django documentation for more information regarding the backend. See
Include the application's urls.py to your project.
urlpatterns = patterns('', ... (r'^loginurl/', include('loginurl.urls')), ... )
This will make requests to loginurl/ are handled by django-loginurl. If the configuration is put inside the project's urls.py, the log in URL will look like the following:
Scheduled Task
To keep your database clean from expired secret keys, a scheduled task need to be set up. This task should do one of the following.
- Call loginurl_cleanup command from the Django's management script, or
- Open a special URL that will trigger the clean up, loginurl/cleanup/. e.g.
You can use crontab or the web based one to set this up. A daily or weekly task should be enough.
Usage
If your application need to create a one time log in URL, what you need to do is calling loginurl.utils.create with a user object as the parameter. The resulting object is an instance of loginurl.models.Key that has a property called key that contains a unique key for the log in URL.
import loginurl.utils def create_login_url(user): key = loginurl.utils.create(user) url = '' % key.key return url
Acknowledgement
This code has been developed in the context of the research activities of the FET project (Grant agreement no. 231807).
Epiwork: developing the framework for an epidemic forecast infrastructure.
See
- Author: Fajran Iman Rusadi
- Download URL:
- License: BSD
- Categories
- Package Index Owner: fajran
- DOAP record: django-loginurl-0.1.4.xml | http://pypi.python.org/pypi/django-loginurl/0.1.4 | crawl-003 | refinedweb | 412 | 58.08 |
On Sun, Jul 7, 2013 at 3:14 AM, Jeff King <p...@peff.net> wrote: > The pack revindex stores the offsets of the objects in the > pack in sorted order, allowing us to easily find the on-disk > size of each object. To compute it, we populate an array > with the offsets from the sha1-sorted idx file, and then use > qsort to order it by offsets. > > That does O(n log n) offset comparisons, and profiling shows > that we spend most of our time in cmp_offset. However, since > we are sorting on a simple off_t, we can use numeric sorts > that perform better. A radix sort can run in O(k*n), where k > is the number of "digits" in our number. For a 64-bit off_t, > using 16-bit "digits" gives us k=4. > > > > Signed-off-by: Jeff King <p...@peff.net> > --- > I think there are probably still two potential issues here: > > 1. My while() loop termination probably has issues when we have to use > all 64 bits to represent the pack offset (not likely, but...) > > 2. We put "int pos[65536]" on the stack. This is a little big, but is > probably OK, as I think the usual small stack problems we have seen > are always in threaded code. But it would not be a big deal to heap > allocate it (it would happen once per radix step, which is only 4 > times for the whole sort). > > pack-revindex.c | 77 > +++++++++++++++++++++++++++++++++++++++++++++++++++++---- > 1 file changed, 72 insertions(+), 5 deletions(-) > >. > { > - const struct revindex_entry *a = a_; > - const struct revindex_entry *b = b_; > - return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0; > + /* > + * We need O(n) temporary storage, so we sort back and forth between > + * the real array and our tmp storage. To keep them straight, we > always > + * sort from "a" into buckets in "b". > + */ > + struct revindex_entry *tmp = xcalloc(n, sizeof(*tmp)); > + struct revindex_entry *a = entries, *b = tmp; > + int digits = 0; > + > + /* > + * We want to know the bucket that a[i] will go into when we are using > + * the digit that is N bits from the (least significant) end. > + */ > +#define BUCKET_FOR(a, i, digits) ((a[i].offset >> digits) & 0xffff) > + > + while (max / (((off_t)1) << digits)) { Is there any reason this shouldn't be simplified to just: while (max >> digits) { I glanced briefly at the assembly and it appears that gcc does actually emit a divide instruction to accomplish this, which I think we can avoid by just rearranging the operation. > + struct revindex_entry *swap; > + int i; > + int pos[65536] = {0}; > + > + /* > + * We want pos[i] to store the index of the last element that > + * will go in bucket "i" (actually one past the last element). > + * To do this, we first count the items that will go in each > + * bucket, which gives us a relative offset from the last > + * bucket. We can then cumulatively add the index from the > + * previous bucket to get the true index. > + */ > + for (i = 0; i < n; i++) > + pos[BUCKET_FOR(a, i, digits)]++; > + for (i = 1; i < ARRAY_SIZE(pos); i++) > + pos[i] += pos[i-1]; > + > + /* > + *, digits)]] = a[i]; > + > + /* > + * Now "b" contains the most sorted list, so we swap "a" and > + * "b" for the next iteration. > + */ > + swap = a; > + a = b; > + b = swap; > + > + /* And bump our digits for the next round. */ > + digits += 16; > + } > + > + /* > + * If we ended with our data in the original array, great. If not, > + * we have to move it back from the temporary storage. > + */ > + if (a != entries) { > + int i; > + for (i = 0; i < n; i++) > + entries[i] = tmp[i]; I think I recall that somebody investigated whether a for loop like you have above was faster for copying structures than memcpy. I forget whether it was conclusive. Did you happen to compare them? <snip> -Brandon -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at | https://www.mail-archive.com/git@vger.kernel.org/msg31659.html | CC-MAIN-2018-47 | refinedweb | 640 | 70.13 |
How To Make A Speech Synthesis Editor
When Steve Jobs unveiled the Macintosh in 1984, it said “Hello” to us from the stage. Even at that point, speech synthesis wasn’t really a new technology: Bell Labs developed the vocoder as early as in the late 30s, and the concept of a voice assistant computer made it into people’s awareness when Stanley Kubrick made the vocoder the voice of HAL9000 in 2001: A Space Odyssey (1968).
It wasn’t before the introduction of Apple’s Siri, Amazon Echo, and Google Assistant in the mid 2015s that voice interfaces actually found their way into a broader public’s homes, wrists, and pockets. We’re still in an adoption phase, but it seems that these voice assistants are here to stay.
In other words, the web isn’t just passive text on a screen anymore. Web editors and UX designers have to get accustomed to making content and services that should be spoken out loud.
We’re already moving fast towards using content management systems that let us work with our content headlessly and through APIs. The final piece is to make editorial interfaces that make it easier to tailor content for voice. So let’s do just that!
What Is SSML
While web browsers use W3C’s specification for HyperText Markup Language (HTML) to visually render documents, most voice assistants use Speech Synthesis Markup Language (SSML) when generating speech.
A minimal example using the root element
<speak>, and the paragraph (
<p>) and sentence (
<s>) tags:
<speak> <p> <s>This is the first sentence of the paragraph.</s> <s>Here’s another sentence.</s> </p> </speak>
Where SSML gets existing is when we introduce tags for
<emphasis> and
<prosody> (pitch):
<speak> <p> <s>Put some <emphasis strength="strong">extra weight on these words</emphasis></s> <s>And say <prosody pitch="high" rate="fast">this a bit higher and faster</prosody>!</s> </p> </speak>
SSML has more features, but this is enough to get a feel for the basics. Now, let’s take a closer look at the editor that we will use to make the speech synthesis editing interface.
The Editor For Portable Text
To make this editor, we’ll use the editor for Portable Text that features in Sanity.io. Portable Text is a JSON specification for rich text editing, that can be serialized into any markup language, such as SSML. This means you can easily use the same text snippet in multiple places using different markup languages.
Installing Sanity
Sanity.io is a platform for structured content that comes with an open-source editing environment built with React.js. It takes two minutes to get it all up and running.
Type
npm i -g @sanity/cli && sanity init into your terminal, and follow the instructions. Choose “empty”, when you’re prompted for a project template.
If you don’t want to follow this tutorial and make this editor from scratch, you can also clone this tutorial’s code and follow the instructions in
README.md.
When the editor is downloaded, you run
sanity start in the project folder to start it up. It will start a development server that use Hot Module Reloading to update changes as you edit its files.
How To Configure Schemas In Sanity Studio
Creating The Editor Files
We’ll start by making a folder called ssml-editor in the /schemas folder. In that folder, we’ll put some empty files:
/ssml-tutorial/schemas/ssml-editor ├── alias.js ├── emphasis.js ├── annotations.js ├── preview.js ├── prosody.js ├── sayAs.js ├── blocksToSSML.js ├── speech.js ├── SSMLeditor.css └── SSMLeditor.js
Now we can add content schemas in these files. Content schemas are what defines the data structure for the rich text, and what Sanity Studio uses to generate the editorial interface. They are simple JavaScript objects that mostly require just a
name and a
type.
We can also add a
title and a
description to make a bit nicer for editors. For example, this is a schema for a simple text field for a
title:
export default { name: 'title', type: 'string', title: 'Title', description: 'Titles should be short and descriptive' }
Portable Text is built on the idea of rich text as data. This is powerful because it lets you query your rich text, and convert it into pretty much any markup you want.
It is an array of objects called “blocks” which you can think of as the “paragraphs”. In a block, there is an array of children spans. Each block can have a style and a set of mark definitions, which describe data structures distributed on the children spans.
Sanity.io comes with an editor that can read and write to Portable Text, and is activated by placing the
block type inside an
array field, like this:
// speech.js export default { name: 'speech', type: 'array', title: 'SSML Editor', of: [ { type: 'block' } ] }
An array can be of multiple types. For an SSML-editor, those could be blocks for audio files, but that falls outside of the scope of this tutorial.
The last thing we want to do is to add a content type where this editor can be used. Most assistants use a simple content model of “intents” and “fulfillments”:
- Intents Usually a list of strings used by the AI model to delineate what the user wants to get done.
- Fulfillments This happens when an “intent” is identified. A fulfillment often is — or at least — comes with some sort of response.
So let’s make a simple content type called
fulfillment that use the speech synthesis editor. Make a new file called fulfillment.js and save it in the /schema folder:
// fulfillment.js export default { name: 'fulfillment', type: 'document', title: 'Fulfillment', of: [ { name: 'title', type: 'string', title: 'Title', description: 'Titles should be short and descriptive' }, { name: 'response', type: 'speech' } ] }
Save the file, and open schema.js. Add it to your studio like this:
// schema.js import createSchema from 'part:@sanity/base/schema-creator' import schemaTypes from 'all:part:@sanity/base/schema-type' import fullfillment from './fullfillment' import speech from './speech' export default createSchema({ name: 'default', types: schemaTypes.concat([ fullfillment, speech, ]) })
If you now run
sanity start in your command line interface within the project’s root folder, the studio will start up locally, and you’ll be able to add entries for fulfillments. You can keep the studio running while we go on, as it will auto-reload with new changes when you save the files.
Adding SSML To The Editor
By default, the
block type will give you a standard editor for visually oriented rich text with heading styles, decorator styles for emphasis and strong, annotations for links, and lists. Now we want to override those with the audial concepts found in SSML.
We begin with defining the different content structures, with helpful descriptions for the editors, that we will add to the
block in SSMLeditorSchema.js as configurations for
annotations. Those are “emphasis”, “alias”, “prosody”, and “say as”.
Emphasis
We begin with “emphasis”, which controls how much weight is put on the marked text. We define it as a string with a list of predefined values that the user can choose from:
// emphasis.js export default { name: 'emphasis', type: 'object', title: 'Emphasis', description: 'The strength of the emphasis put on the contained text', fields: [ { name: 'level', type: 'string', options: { list: [ { value: 'strong', title: 'Strong' }, { value: 'moderate', title: 'Moderate' }, { value: 'none', title: 'None' }, { value: 'reduced', title: 'Reduced' } ] } } ] }
Alias
Sometimes the written and the spoken term differ. For instance, you want to use the abbreviation of a phrase in a written text, but have the whole phrase read aloud. For example:
<s>This is a <sub alias="Speech Synthesis Markup Language">SSML</sub> tutorial</s>
The input field for the alias is a simple string:
// alias.js export default { name: 'alias', type: 'object', title: 'Alias (sub)', description: 'Replaces the contained text for pronunciation. This allows a document to contain both a spoken and written form.', fields: [ { name: 'text', type: 'string', title: 'Replacement text', } ] }
Prosody
With the prosody property we can control different aspects how text should be spoken, like pitch, rate, and volume. The markup for this can look like this:
<s>Say this with an <prosody pitch="x-low">extra low pitch</prosody>, and this <prosody rate="fast" volume="loud">loudly with a fast rate</prosody></s>
This input will have three fields with predefined string options:
// prosody.js export default { name: 'prosody', type: 'object', title: 'Prosody', description: 'Control of the pitch, speaking rate, and volume', fields: [ { name: 'pitch', type: 'string', title: 'Pitch', description: 'The baseline pitch for the contained text', options: { list: [ { value: 'x-low', title: 'Extra low' }, { value: 'low', title: 'Low' }, { value: 'medium', title: 'Medium' }, { value: 'high', title: 'High' }, { value: 'x-high', title: 'Extra high' }, { value: 'default', title: 'Default' } ] } }, { name: 'rate', type: 'string', title: 'Rate', description: 'A change in the speaking rate for the contained text', options: { list: [ { value: 'x-slow', title: 'Extra slow' }, { value: 'slow', title: 'Slow' }, { value: 'medium', title: 'Medium' }, { value: 'fast', title: 'Fast' }, { value: 'x-fast', title: 'Extra fast' }, { value: 'default', title: 'Default' } ] } }, { name: 'volume', type: 'string', title: 'Volume', description: 'The volume for the contained text.', options: { list: [ { value: 'silent', title: 'Silent' }, { value: 'x-soft', title: 'Extra soft' }, { value: 'medium', title: 'Medium' }, { value: 'loud', title: 'Loud' }, { value: 'x-loud', title: 'Extra loud' }, { value: 'default', title: 'Default' } ] } } ] }
Say As
The last one we want to include is
<say-as>. This tag lets us exercise a bit more control over how certain information is pronounced. We can even use it to bleep out words if you need to redact something in voice interfaces. That’s @!%&© useful!
<s>Do I have to <say-asfrakking</say-as> <say-asspell</say-as> it out for you!?</s>
// sayAs.js export default { name: 'sayAs', type: 'object', title: 'Say as...', description: 'Lets you indicate information about the type of text construct that is contained within the element. It also helps specify the level of detail for rendering the contained text.', fields: [ { name: 'interpretAs', type: 'string', title: 'Interpret as...', options: { list: [ { value: 'cardinal', title: 'Cardinal numbers' }, { value: 'ordinal', title: 'Ordinal numbers (1st, 2nd, 3th...)' }, { value: 'characters', title: 'Spell out characters' }, { value: 'fraction', title: 'Say numbers as fractions' }, { value: 'expletive', title: 'Blip out this word' }, { value: 'unit', title: 'Adapt unit to singular or plural' }, { value: 'verbatim', title: 'Spell out letter by letter (verbatim)' }, { value: 'date', title: 'Say as a date' }, { value: 'telephone', title: 'Say as a telephone number' } ] } }, { name: 'date', type: 'object', title: 'Date', fields: [ { name: 'format', type: 'string', description: 'The format attribute is a sequence of date field character codes. Supported field character codes in format are .' }, { name: 'detail', type: 'number', validation: Rule => Rule.required() .min(0) .max(2), description: 'The detail attribute controls the spoken form of the date. For detail='1' only the day fields and one of month or year fields are required, although both may be supplied' } ] } ] }
Now we can import these in an annotations.js file, which makes things a bit tidier.
// annotations.js export {default as alias} from './alias' export {default as emphasis} from './emphasis' export {default as prosody} from './prosody' export {default as sayAs} from './sayAs'
Now we can import these annotation types into our main schemas:
// schema.js import createSchema from "part:@sanity/base/schema-creator" import schemaTypes from "all:part:@sanity/base/schema-type" import fulfillment from './fulfillment' import speech from './ssml-editor/speech' import { alias, emphasis, prosody, sayAs } from './annotations' export default createSchema({ name: "default", types: schemaTypes.concat([ fulfillment, speech, alias, emphasis, prosody, sayAs ]) })
Finally, we can now add these to the editor like this:
// speech.js export default { name: 'speech', type: 'array', title: 'SSML Editor', of: [ { type: 'block', styles: [], lists: [], marks: { decorators: [], annotations: [ {type: 'alias'}, {type: 'emphasis'}, {type: 'prosody'}, {type: 'sayAs'} ] } } ] }
Notice that we also added empty arrays to
styles, and
decorators. This disables the default styles and decorators (like bold and emphasis) since they don’t make that much sense in this specific case.
Customizing The Look And Feel
Now we have the functionality in place, but since we haven’t specified any icons, each annotation will use the default icon, which makes the editor hard to actually use for authors. So let’s fix that!
With the editor for Portable Text it’s possible to inject React components both for the icons and for how the marked text should be rendered. Here, we’ll just let some emoji do the work for us, but you could obviously go far with this, making them dynamic and so on. For
prosody we’ll even make the icon change depending on the volume selected. Note that I omitted the fields in these snippets for brevity, you shouldn’t remove them in your local files.
// alias.js import React from 'react' export default { name: 'alias', type: 'object', title: 'Alias (sub)', description: 'Replaces the contained text for pronunciation. This allows a document to contain both a spoken and written form.', fields: [ /* all the fields */ ], blockEditor: { icon: () => '🔤', render: ({ children }) => <span>{children} 🔤</span>, }, };
// emphasis.js import React from 'react' export default { name: 'emphasis', type: 'object', title: 'Emphasis', description: 'The strength of the emphasis put on the contained text', fields: [ /* all the fields */ ], blockEditor: { icon: () => '🗯', render: ({ children }) => <span>{children} 🗯</span>, }, };
// prosody.js import React from 'react' export default { name: 'prosody', type: 'object', title: 'Prosody', description: 'Control of the pitch, speaking rate, and volume', fields: [ /* all the fields */ ], blockEditor: { icon: () => '🔊', render: ({ children, volume }) => ( <span> {children} {['x-loud', 'loud'].includes(volume) ? '🔊' : '🔈'} </span> ), }, };
// sayAs.js import React from 'react' export default { name: 'sayAs', type: 'object', title: 'Say as...', description: 'Lets you indicate information about the type of text construct that is contained within the element. It also helps specify the level of detail for rendering the contained text.', fields: [ /* all the fields */ ], blockEditor: { icon: () => '🗣', render: props => <span>{props.children} 🗣</span>, }, };
Now you have an editor for editing text that can be used by voice assistants. But wouldn’t it be kinda useful if editors also could preview how the text actually will sound like?
Adding A Preview Button Using Google’s Text-to-Speech
Native speech synthesis support is actually on its way for browsers. But in this tutorial, we’ll use Google’s Text-to-Speech API which supports SSML. Building this preview functionality will also be a demonstration of how you serialize Portable Text into SSML in whatever service you want to use this for.
Wrapping The Editor In A React Component
We begin with opening the SSMLeditor.js file and add the following code:
// SSMLeditor.js import React, { Fragment } from 'react'; import { BlockEditor } from 'part:@sanity/form-builder'; export default function SSMLeditor(props) { return ( <Fragment> <BlockEditor {...props} /> </Fragment> ); }
We have now wrapped the editor in our own React component. All the props it needs, including the data it contains, are passed down in real-time. To actually use this component, you have to import it into your
speech.js file:
// speech.js import React from 'react' import SSMLeditor from './SSMLeditor.js' export default { name: 'speech', type: 'array', title: 'SSML Editor', inputComponent: SSMLeditor, of: [ { type: 'block', styles: [], lists: [], marks: { decorators: [], annotations: [ { type: 'alias' }, { type: 'emphasis' }, { type: 'prosody' }, { type: 'sayAs' }, ], }, }, ], }
When you save this and the studio reloads, it should look pretty much exactly the same, but that’s because we haven’t started tweaking the editor yet.
Convert Portable Text To SSML
The editor will save the content as Portable Text, an array of objects in JSON that makes it easy to convert rich text into whatever format you need it to be. When you convert Portable Text into another syntax or format, we call that “serialization”. Hence, “serializers” are the recipes for how the rich text should be converted. In this section, we will add serializers for speech synthesis.
You have already made the blocksToSSML.js file. Now we’ll need to add our first dependency. Begin by running the terminal command
npm init -y inside the
ssml-editor folder. This will add a package.json where the editor’s dependencies will be listed.
Once that’s done, you can run
npm install @sanity/block-content-to-html to get a library that makes it easier to serialize Portable Text. We’re using the HTML-library because SSML has the same XML syntax with tags and attributes.
This is a bunch of code, so do feel free to copy-paste it. I’ll explain the pattern right below the snippet:
// blocksToSSML.js import blocksToHTML, { h } from '@sanity/block-content-to-html' const serializers = { marks: { prosody: ({ children, mark: { rate, pitch, volume } }) => h('prosody', { attrs: { rate, pitch, volume } }, children), alias: ({ children, mark: { text } }) => h('sub', { attrs: { alias: text } }, children), sayAs: ({ children, mark: { interpretAs } }) => h('say-as', { attrs: { 'interpret-as': interpretAs } }, children), break: ({ children, mark: { time, strength } }) => h('break', { attrs: { time: '${time}ms', strength } }, children), emphasis: ({ children, mark: { level } }) => h('emphasis', { attrs: { level } }, children) } } export const blocksToSSML = blocks => blocksToHTML({ blocks, serializers })
This code will export a function that takes the array of blocks and loop through them. Whenever a block contains a
mark, it will look for a serializer for the type. If you have marked some text to have
emphasis, it this function from the serializers object:
emphasis: ({ children, mark: { level } }) => h('emphasis', { attrs: { level } }, children)
Maybe you recognize the parameter from where we defined the schema? The
h() function lets us defined an HTML element, that is, here we “cheat” and makes it return an SSML element called
<emphasis>. We also give it the attribute
level if that is defined, and place the
children elements within it — which in most cases will be the text you have marked up with
emphasis.
{ "_type": "block", "_key": "f2c4cf1ab4e0", "style": "normal", "markDefs": [ { "_type": "emphasis", "_key": "99b28ed3fa58", "level": "strong" } ], "children": [ { "_type": "span", "_key": "f2c4cf1ab4e01", "text": "Say this strongly!", "marks": [ "99b28ed3fa58" ] } ] }
That is how the above structure in Portable Text gets serialized to this SSML:
<emphasis level="strong">Say this strongly</emphasis>
If you want support for more SSML tags, you can add more annotations in the schema, and add the annotation types to the
marks section in the serializers.
Now we have a function that returns SSML markup from our marked up rich text. The last part is to make a button that lets us send this markup to a text-to-speech service.
Adding A Preview Button That Speaks Back To You
Ideally, we should have used the browser’s speech synthesis capabilities in the Web API. That way, we would have gotten away with less code and dependencies.
As of early 2019, however, native browser support for speech synthesis is still in its early stages. It looks like support for SSML is on the way, and there is proof of concepts of client-side JavaScript implementations for it.
Chances are that you are going to use this content with a voice assistant anyways. Both Google Assistant and Amazon Echo (Alexa) support SSML as responses in a fulfillment. In this tutorial, we will use Google’s text-to-speech API, which also sounds good and support several languages.
Start by obtaining an API key by signing up for Google Cloud Platform (it will be free for the first 1 million characters you process). Once you’re signed up, you can make a new API key on this page.
Now you can open your PreviewButton.js file, and add this code to it:
// PreviewButton.js import React from 'react' import Button from 'part:@sanity/components/buttons/default' import { blocksToSSML } from './blocksToSSML' // You should be careful with sharing this key // I put it here to keep the code simple const API_KEY = '<yourAPIkey>' const GOOGLE_TEXT_TO_SPEECH_URL = '' + API_KEY const speak = async blocks => { // Serialize blocks to SSML const ssml = blocksToSSML(blocks) // Prepare the Google Text-to-Speech configuration const body = JSON.stringify({ input: { ssml }, // Select the language code and voice name (A-F) voice: { languageCode: 'en-US', name: 'en-US-Wavenet-A' }, // Use MP3 in order to play in browser audioConfig: { audioEncoding: 'MP3' } }) // Send the SSML string to the API const res = await fetch(GOOGLE_TEXT_TO_SPEECH_URL, { method: 'POST', body }).then(res => res.json()) // Play the returned audio with the Browser’s Audo API const audio = new Audio('data:audio/wav;base64,' + res.audioContent) audio.play() } export default function PreviewButton (props) { return <Button style={{ marginTop: '1em' }} onClick={() => speak(props.blocks)}>Speak text</Button> }
I’ve kept this preview button code to a minimal to make it easier to follow this tutorial. Of course, you could build it out by adding state to show if the preview is processing or make it possible to preview with the different voices that Google’s API supports.
Add the button to
SSMLeditor.js:
// SSMLeditor.js import React, { Fragment } from 'react'; import { BlockEditor } from 'part:@sanity/form-builder'; import PreviewButton from './PreviewButton'; export default function SSMLeditor(props) { return ( <Fragment> <BlockEditor {...props} /> <PreviewButton blocks={props.value} /> </Fragment> ); }
Now you should be able to mark up your text with the different annotations, and hear the result when pushing “Speak text”. Cool, isn’t it?
You’ve Created A Speech Synthesis Editor, And Now What?
If you have followed this tutorial, you have been through how you can use the editor for Portable Text in Sanity Studio to make custom annotations and customize the editor. You can use these skills for all sorts of things, not only to make a speech synthesis editor. You have also been through how to serialize Portable Text into the syntax you need. Obviously, this is also handy if you’re building frontends in React or Vue. You can even use these skills to generate Markdown from Portable Text.
We haven’t covered how you actually use this together with a voice assistant. If you want to try, you can use much of the same logic as with the preview button in a serverless function, and set it as the API endpoint for a fulfillment using webhooks, e.g. with Dialogflow.
If you’d like me to write a tutorial on how to use the speech synthesis editor with a voice assistant, feel free to give me a hint on Twitter or share in the comments section below.
Further Reading on SmashingMag:
- Experimenting With speechSynthesis
- Enhancing User Experience With The Web Speech API
- Accessibility APIs: A Key To Web Accessibility
- Building A Simple AI Chatbot With Web Speech API And Node.js
| https://www.smashingmagazine.com/2019/03/sanity-portabletext-speech-synthesis/ | CC-MAIN-2019-35 | refinedweb | 3,700 | 60.65 |
Unit tests are no longer hype, but daily business. Developers love writing tests, and even do test-driven development. But testing units of code often is a problem: most parts of a software system do not work in isolation, but collaborate with other parts to get their jobs done. In unit testing, we do not want to test these collaborating objects, but only the unit under test. Mock objects provide a solution to this dilemma: they can be set up to behave as expected, so they are a perfect replacement for collaborators of the unit under test.
Writing mock objects on your own can be tedious, but there are a lot of mock frameworks out there to help you with this task. EasyMock is a library for creating mocks for interfaces on the fly using the dynamic proxy API. It's been around for a couple of years now, and besides being very stable and robust, another advantage is that it is well known. So here comes EasyMock2, ready to rock--er, mock--the world. My first idea was to introduce only the new features of version 2, but I recognized that there are still a lot of people out there not using EasyMock at all. So I'm going to show what you can do with EasyMock using the new version 2.2 API.
For those out there who already know EasyMock: What's so special about version 2? Well, for me it eliminates the weaknesses of EasyMock1; the price is that it depends on JDK1.5. Have a look at the new features:
No more need for a dedicated control object.
Heavy usage of generics eliminates casts.
New matcher API allows fuzzy parameter matching.
Check call order of more than one mock.
Dynamically respond to mock method calls.
Curious? Let's get started.
Personally, I prefer learning by example. That's why we will develop some code here in a test-first manner using EasyMock2. You're not familiar with test-first development? Don't worry, it's quite natural; but reading one of these papers first will help.
Last Exit to Springfield
What's the problem we have to solve? Here we go: the application we're building is the SimpsonViewer, which one can use to watch episodes of The Simpsons. The application is based on an IoC container like Hivemind and is divided into client and server parts. We have a web service that delivers Simpsons episodes, the
ISimpsonService. The client uses this service to fetch episodes and renders them to the user. A flaw in our application is that every time the user selects an episode she likes to watch, the client fetches the episode from the server, even if this episode has already been retrieved. So we'd like to introduce a client-side proxy that transparently caches the episodes. Let's start with the
ISimpsonService:
public interface ISimpsonService { IEpisode getEpisode(int number); }
Quite easy. The
IEpisode interface looks like this:
public interface IEpisode { int getNumber(); String getTitle(); InputStream getDataAsStream(); }
Not that complicated. Now we have to implement our
ClientSimpsonService, which is the client-side proxy for the web service:
public class ClientSimpsonService implements ISimpsonService { private ISimpsonService remoteSimpsonService; public ClientSimpsonService(ISimpsonService remoteSimpsonService) { this.remoteSimpsonService = remoteSimpsonService; } public IEpisode getEpisode(int episodeNumber) { return null; } }
The
ClientSimpsonService gets the remote service as a constructor parameter injected by the IoC container. We could also have done this with a setter, but I prefer passing mandatory parameters in the constructor, so we can "fail fast" if the service is not set up correctly.
OK, this is an implementation, but it's not very useful right now. That's fine, as we want to develop in a test-first style, so let's specify the expected behavior of the code in a unit test. We want to fail fast if the service is not set up correctly; in this case, this means we have to check that we actually get the
remoteSimpsonService passed in:
public class ClientSimpsonServiceTest extends TestCase { public void testClientSimpsonService() { try { new ClientSimpsonService(null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } }
So passing a
null should raise an
IllegalArgumentException. Developing test-first means "write the easiest implementation that does the job."
public class ClientSimpsonService implements ISimpsonService { ... public ClientSimpsonService(ISimpsonService remoteSimpsonService) { this.remoteSimpsonService = remoteSimpsonService; throw new IllegalArgumentException(); } ... }
You can't be serious! Run the test, please. Green, isn't it? That means our test case doesn't prove much yet. The constructor should not always throw an
IllegalArgumentException, but instead only does so if the parameter is
null. So we have to write a test that does not fail if we pass an
ISimpsonEpisode instance. Too bad we don't have any other implementation we could use. But here comes EasyMock to the rescue:
import static org.easymock.EasyMock.createMock; import junit.framework.TestCase; public class ClientSimpsonServiceTest extends TestCase { private ISimpsonService remoteSimpsonServiceMock; protected void setUp() throws Exception { super.setUp(); remoteSimpsonServiceMock = createMock(ISimpsonService.class); } public void testClientSimpsonService() { try { new ClientSimpsonService(null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } new ClientSimpsonService(remoteSimpsonServiceMock); } }
What's happening here? In a few words: we used EasyMock to create an instance that implements the
ISimpsonEpisode interface on the fly and passes it to the constructor and everything should be fine. This means our test should now run red--yep, as expected. And now the implementation that makes our bar green again:
public class ClientSimpsonService implements ISimpsonService { ... public ClientSimpsonService(ISimpsonService remoteSimpsonService) { if (remoteSimpsonService == null) { throw new IllegalArgumentException( "'remoteSimpsonService' must not be null"); } this.remoteSimpsonService = remoteSimpsonService; } ... }
I can hear you yelling: "Why is he taking such damn small steps? I would have written the correct code in the first place." No doubt about it. But would your test look the same? The point is: taking small steps, and using the simplest implementation you can think of, forces you to write the right tests. Always check that adding a test turns the test bar red. If not, there is something wrong with your test.
Now let's move on to the
getEpisode() method. Let's ignore the caching for now and start with testing that the client delegates the call to the remote service. Er, how do we do that? Well, EasyMock allows us the specify expectations:
import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import junit.framework.TestCase; public class ClientSimpsonServiceTest extends TestCase { private IEpisode episode17Mock; private ISimpsonService remoteSimpsonServiceMock; protected void setUp() throws Exception { super.setUp(); episode17Mock = createMock(IEpisode.class); remoteSimpsonServiceMock = createMock(ISimpsonService.class); } ...); }
We'll take this step by step:
We expect that our remote service mock's
getEpisode()method is called with the parameter
17.
The previous
expect()call returns an
IExpectationsSetters, which we use to instruct EasyMock to return the
episode17Mockfor that call.
We switch the mock to replay mode, which means that from now on it is expecting the call.
We call our client's
getEpisode()method with the parameter
17.
We verify that our expectations have been met, which means that
getEpisode(17)has been called on the
remoteSimpsonServiceMock.
We check if the service returned the
episode17Mock.
Run the test, and--yep, red. An
AssertionError has been thrown. Let's have a look at the
StackTrace:
java.lang.AssertionError: Expectation failure on verify: getEpisode(17): expected: 1, actual: 0 at org.easymock.internal.MocksControl.verify(MocksControl.java:70) at org.easymock.EasyMock.verify(EasyMock.java:1301) at example1.ClientSimpsonServiceTest.testGetEpisode(ClientSimpsonServiceTest.java:41) ...
The
verify() failed, since the expected call
getEpisode(17) has not been made. This makes sense: we did not call the remote service (-mock) yet. And again, we write the easiest implementation that colors the test bar green:
public class ClientSimpsonService implements ISimpsonService { ... public IEpisode getEpisode(int episodeNumber) { return remoteSimpsonService.getEpisode(episodeNumber); } }
Run the test and--ta da, green again. Hey, easy on the clutch. How is that working? You're right, it's time for some words on EasyMock. Using EasyMock always follows the same steps:
Create a mock.
Set up your expectations.
Set the mock to replay mode.
Call your code under test.
Verify that your expectations have been met.
How is EasyMock creating a mock? It uses the DynamicProxy API to generate a class that implements the desired interface on the fly. This has a great advantage over writing your own mock. First of all, you don't have to write one ;-). Another advantage is that it is robust to interface changes, which means that if things have been altered (that are not explicitly used in your test case), you don't have to worry about it. If you write your own mock, you have to follow every interface change. (Once upon a time, I was working in a project where management decided to use an API that was still in its beta state. Besides having no robust implementation, even mocking was a pain, since the API interfaces changed almost weekly!) There is nothing much to say about
replay()and
verify(). But what you can do to set up expectations is worth having a look. Setting up your expectations means you tell EasyMock which calls to expect on a certain mock, and what to return for that call. You can certainly expect more than one call, e.g.:
expect(remoteSimpsonServiceMock.getEpisode(17)) .andReturn(episode17Mock); expect(remoteSimpsonServiceMock.getEpisode(43)) .andReturn(episode43Mock); replay(remoteSimpsonServiceMock);
If you are expecting the same call more than once, there is a shortcut. Let's say we expect the call exactly twice:
expect(remoteSimpsonServiceMock.getEpisode(17)) .andReturn(episode17Mock) .times(2); ...
Since
andReturn() (and all other methods of
IExpectationsSetters) returns the
IExpectationsSetters instance itself, these calls can be easily chained. There are also some methods that specify a fuzzy number of method calls:
atLeastOnce()
anyTimes()
times(from, to)
If you don't specify a call count, it is implicitly
once(). Sometimes you want your mock to return values for method calls, but you don't care how often it is called or even if it is called at all: you want to use it as a stub. EasyMock supports this by using the methods
andStubReturn() and
asStub().
Another thing to note is that after
verify(), the mock is not burned; you can reuse it by calling
reset():
import static org.easymock.EasyMock.reset; ... public class ClientSimpsonServiceTest extends TestCase { ...); reset(remoteSimpsonServiceMock); expect(remoteSimpsonServiceMock.getEpisode(43)). andReturn(episode43Mock); replay(remoteSimpsonServiceMock); result = clientSimpsonService.getEpisode(43); verify(remoteSimpsonServiceMock); assertEquals(episode43Mock, result); } ... }
Introducing the Cache
What have we got so far? Our
ClientSimpsonServicedelegates to the remote service. Fine. But the feature we wanted to introduce was client-side caching, so let's start implementing that. Again, we will specify our test first. How do we test caching? Let's think about it: once an episode is fetched, it must not be retrieved from the remote service again. This means that if we ask for the same episode twice, it should be retrieved from the server just once; the second time it should be retrieved from the cache:
public void testGetEpisodeCaches())); // not expected since it should be cached assertEquals(episode17Mock, clientSimpsonService.getEpisode(17)); verify(remoteSimpsonServiceMock); }
Hmm, not that complicated. We set up the remote service mock to expect one call to
getEpisode(17), but we call it twice on the client service. Curious about the test result? Run the test--red, as expected. And here is the
StackTrace:
java.lang.AssertionError: Unexpected method call getEpisode(17): getEpisode(17): expected: 1, actual: 1 (+1) at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45) at $Proxy1.getEpisode(Unknown Source) at example2.ClientSimpsonService.getEpisode(ClientSimpsonService.java:20) at example2.ClientSimpsonServiceTest.testGetEpisodeCaches(ClientSimpsonServiceTest.java:62) ...
Yep, when the unexpected call comes, EasyMock complains that
getEpisode(17) has been called one more time (
+1) than expected. Note: In EasyMock1, the message would have been
getEpisode(17): expected: 1, actual: 2 .
To see if our test checks the right thing, we choose the simplest implementation we can think of:
public class ClientSimpsonService implements ISimpsonService { private IEpisode cachedEpisode; ... public IEpisode getEpisode(int episodeNumber ) { if (cachedEpisode == null ) { cachedEpisode = remoteSimpsonService.getEpisode(episodeNumber); } return cachedEpisode; }
This is ridiculous. Absolutely right, but our test saysgreen. OK, so our test isn't worth a nickel yet. Let's change that by asking for more than one episode:
public class ClientSimpsonServiceTest extends TestCase { private IEpisode episode42Mock; ... protected void setUp() throws Exception { ... episode42Mock = createMock(IEpisode.class); } ... public void testGetEpisodeCaches() throws Exception { expect(remoteSimpsonServiceMock.getEpisode(17)) .andReturn(episode17Mock); expect(remoteSimpsonServiceMock.getEpisode(42)) .andReturn(episode42)); assertEquals(episode42Mock, clientSimpsonService.getEpisode(42)); // not expected since it should be cached assertEquals(episode17Mock, clientSimpsonService.getEpisode(17)); assertEquals(episode42Mock, clientSimpsonService.getEpisode(42)); verify(remoteSimpsonServiceMock); } }
Run the test and--red. Fine, the test now specifies the required behavior. And the final code to satisfy our test looks like this:
public class ClientSimpsonService implements ISimpsonService { private Map<Integer, IEpisode> episodeCache = new HashMap<Integer, IEpisode>(); ... public IEpisode getEpisode(int episodeNumber) { IEpisode episode = episodeCache.get(episodeNumber); if (episode == null) { episode = remoteSimpsonService.getEpisode(episodeNumber); episodeCache.put(episodeNumber, episode); } return episode; } }
Run the test again. Yippee, it's green. So we're done with caching.
Testing Exceptions
Currently, if an episode is not found,
null is returned. That's OK, but client code always has to check for
null before using an episode. We'll take a different approach: If an episode cannot be retrieved, an
EpisodeNotFoundException is thrown:
public interface ISimpsonService { IEpisode getEpisode(int number) throws EpisodeNotFoundException; }
After changing the interface, our compiler complains that
ClientSimpsonService calls
getEpisode()on the remote service and does not handle the
EpisodeNotFoundException. Eclipse suggests corrections if you press
CTRL-
1; we decide to use
Surround with try/catch:
public IEpisode getEpisode(int episodeN; }
Now it compiles, but is that the desired behavior of our
ClientSimpsonService? Nope. It should pass the exception thrown by the server, so let's write a test for that:
public void testGetEpisodeThrowsException() throws Exception { EpisodeNotFoundException exception = new EpisodeNotFoundException(); expect(serverSimpsonServiceMock.getEpisode(666)). andThrow(exception); replay(serverSimpsonServiceMock); ISimpsonService clientSimpsonService = new ClientSimpsonService(serverSimpsonServiceMock); try { clientSimpsonService.getEpisode(666); fail("Expected EpisodeNotFoundException"); } catch (EpisodeNotFoundException e) { // expected } verify(serverSimpsonServiceMock); }
In our previous tests, we always used the
IExpectationsSetters to set up return values. This time, we use the method
andThrow() to set up throwables, meaning that on the call
getEpisode(17)the mock is throwing the
EpisodeNotFoundException. After that, we call
getEpisode(17) on our
ClientSimpsonService and fail if the exception is not thrown. Run the test and--yep, it's red. (You should always run the test before fixing the code; checking for red is a test for your test.) To fix our
ClientSimpsonService, we simply remove the
try/
catch and add a
throwsdeclaration:
public IEpisode getEpisode(int episodeNumber) throws EpisodeNotFoundEx; }
And out test is green again! EasyMock also supports stub behavior for throwables by the method
andStubThrow().
The Mapper API
Suppose we'd like to introduce a method that allows us to retrieve a collection of episodes:
public interface ISimpsonService { IEpisode getEpisode(int number) throws EpisodeNotFoundException; List<IEpisode> getEpisodes(int[] numbers); }
Writing a test for this method seems to be straightforward. It's similar to our test for the
getEpisode() method, only the parameter is an array and the return value is a
List:
public void testGetEpisodes() { List<IEpisode> expectedResult = Arrays.asList(new IEpisode[] {episode17Mock, episode42Mock}); expect(remoteSimpsonServiceMock.getEpisodes); }
Hmm, quite easy. It's the same with our
ClientSimpsonService implementation:
public class ClientSimpsonService implements ISimpsonService { ... public List<IEpisode> getEpisodes(int[] episodeNumbers) { return remoteSimpsonService.getEpisodes(episodeNumbers); } }
Run the test, and--er, red?!? What? Why is that? Let's see the error message:
java.lang.AssertionError: Unexpected method call getEpisodes([I@1dff3a2): getEpisodes([I@a9ae05): expected: 1, actual: 0 at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45) at $Proxy1.getEpisodes(Unknown Source) at example4.ClientSimpsonService.getEpisodes(ClientSimpsonService.java:30) at example4.ClientSimpsonServiceTest.testGetEpisodes(ClientSimpsonServiceTest.java:92) ...
We expected an array new
int[] {17, 42} and we passed an
int[] {17, 42}. So what's the problem? Ever asked yourself how EasyMock decides if passed parameters match the expectations? It uses the
equals() method, which is quite fine in most circumstances. Most, but not all. For example, you can't compare arrays using the
equals method (that's why there is a static method
Arrays.equals(Object [] a, Object[] b) and signatures for all kind of primitive types as well). For those circumstances, EasyMock2 introduced the new matcher API. In our case here, we need an array matcher:
import static org.easymock.EasyMock.aryEq; ... public class ClientSimpsonServiceTest extends TestCase { ... public void testGetEpisodes() { List<IEpisode> expectedResult = Arrays.asList(new IEpisode[] {episode17Mock, episode42Mock}); expect(remoteSimpsonServiceMock.getEpisodes( aryEq); } }
Run the test again, and ta da: green!
And now the EasyMock1-wise-guys choir: What's the big deal? EasyMock1 already provided an array matcher! Right, but besides the fact that its usage wasn't quite that elegant, there wasn't this choice of matchers:
eq(X value),
eq(X value, X delta)
anyBoolean(),
anyByte(),
anyChar(),
anyDouble(),
anyFloat(),
anyInt(),
anyLong(),
anyObject(),
anyShort()
aryEq(X value)
isNull(),
notNull()
same(X value)
isA(Class clazz)
lt(X value),
leq(X value),
geq(X value),
gt(X value)
startsWith(String prefix), contains(String substring), endsWith(String suffix),
matches(String regex), find(String regex)
and(X first, X second),
or(X first, X second),
not(X value)
What's Left?
There are still some features worth getting to know. Since I had no use for them in our trivial example, I will just explain them shortly here:
Nice Mocks
Mocks created by EasyMock usually throw an
AssertionError for all unexpected method calls. Sometimes you need a mock that nicely returns default values instead of complaining all the time. Mocks created by
EasyMock.createNiceMock() return empty values (
0,
null, or
false) for unexpected method calls.
Strict Mocks
By default, the order of method calls is not checked by EasyMock. If you need this, you have to create a Strict Mock with
EasyMock.createStrictMock(). You can even switch from strict to normal by
EasyMock.checkOrder(Object mock, boolean enableOrderCheck).
Checking Call Order Between Mocks
If there is more than one mock involved with your test, you might want to check the call order between mocks. This means that if you have
mock1 and
mock2, you can check that
mock1.a() is called before
mock2.b(). Before I show you how to achieve that, let me introduce the
IMockControl: when you call
EasyMock.createMock(), an
IMockControl is also created and maintained for you under the hood. When you now call, for example,
replay(myMock), the associated
IMockControl is retrieved and
replay() is called on it. You can also create an
IMockControlexplicitly using
EasyMock.createControl() or--since we want to check call order--
createStrictControl(). Now you can use this instance to create two or even more mocks, which are all under control of this single
IMockControl.
Note: In EasyMock1, you always had to create and maintain an explicit
MockControl object.
Dynamically Respond to Mock Method Calls
There might be the rare case that you need to execute some code when a mock object is called, maybe to trigger some side effects. Or maybe you don't know the parameters passed to the mock up front, so you need to create the appropriate return value on the fly? For those situations, EasyMock 2.2 introduced the
IAnswer interface and the static methods
andAnswer() and
andStubAnswer().
Note: The method
callback(Runnable), which has been introduced with 2.0, has now been replaced by the more flexible
andAnswer() in Version 2.2.
What about Mocking Classes with EasyMock?
So far we've used EasyMock to create mocks for interfaces, but how about mocking classes? Is that possible? No. Er, yes. Er, well, EasyMock itself is capable of mocking interfaces only. But there is another project called EasyMock Class Extension that fills this gap. Just use the
org.easymock.classextension.EasyMock.*methods instead. You may even mock abstract classes. Unfortunately (but not surprisingly), you can't mock final classes.
Mocking Methods
Another valuable feature is EasyMock Class Extension's ability to mock only certain methods. This means that you can mock one (or more) methods but leave the rest of the objects' functionality untouched. The point is that you do not need to rebuild all of the objects' behavior in your setup, but only those calls you have to avoid in your testing environment.
That's It, Dude
Wake up, we're done. Didn't talk you into a coma with all those nifty little details? That's good news. We have gone through some common usage examples of EasyMock, and even scratched the surface of some sophisticated features. What's next? Check out EasyMock and give it a try in your current project. Or replay the examples we have gone through; you will find all the example code of this article in the Resources section. If you're still not sick of all that theory, you could read the EasyMock documentation. That's all I have to say; hope to see you again on my next article. And remember:
You're damned if you do, and you're damned if you don't.
--Bart Simpson
Resources
- Source code of this article
- EasyMock
- EasyMock 2.2 documentation
- Test-driven development from Wikipedia
- "Test-Driven Development: A Conversation with Martin Fowler, Part V" | https://community.oracle.com/docs/DOC-983560 | CC-MAIN-2017-34 | refinedweb | 3,549 | 50.12 |
So far, we've settled on a dictionary-based representation for our database of records, and we've reviewed some Python data structure concepts along the way. As mentioned, though, the objects we've seen so far are temporarythey live in memory and they go away as soon as we exit Python or the Python program that created them. To make our people persistent, they need to be stored in a file of some sort.
One way to keep our data around between program runs is to write all the data out to a simple text file, in a formatted way. Provided the saving and loading tools agree on the format selected, we're free to use any custom scheme we like.
So that we don't have to keep working interactively, let's first write a script that initializes the data we are going to store (if you've done any Python work in the past, you know that the interactive prompt tends to become tedious once you leave the realm of simple one-liners). Example 2-1 creates the sort of records and database dictionary we've been working with so far, but because it is a module, we can import it repeatedly without having to retype the code each time. In a sense, this module is a database itself, but its program code format doesn't support automatic or end-user updates as is.
Besides allowing us to associate meaningful labels with data rather than numeric positions, dictionaries are often more flexible than lists, especially when there isn't a fixed size to our problem. For instance, suppose you need to sum up columns of data stored in a text file where the number of columns is not known or fixed:
>>> print open('data.txt').read( ) 001.1 002.2 003.3 010.1 020.2 030.3 040.4 100.1 200.2 300.3
Here, we cannot preallocate a fixed-length list of sums because the number of columns may vary. Splitting on whitespace extracts the columns, and float converts to numbers, but a fixed-size list won't easily accommodate a set of sums (at least, not without extra code to manage its size). Dictionaries are more convenient here because we can use column positions as keys instead of using absolute offsets Most of this code uses tools added to Python in the last five years; see Chapter 4 for more on file iterators, Chapter 21 for text processing and alternative summers, and the library manual for the 2.3 enumerate and 2.4 sorted functions this code uses:
>>> sums = {} >>> for line in open('data.txt'): cols = [float(col) for col in line.split( )] for pos, val in enumerate(cols): sums[pos] = sums.get(pos, 0.0) + val >>> for key in sorted(sums): print key, '=', sums[key] 0 = 111.3 1 = 222.6 2 = 333.9 3 = 40.4 >>> sums {0: 111.3, 1: 222.59999999999999, 2: 333.90000000000003, 3: 40.399999999999999}
Dictionaries are often also a handy way to represent matrixes, especially when they are mostly empty. The following two-entry dictionary, for example, suffices to represent a potentially very large three-dimensional matrix containing two nonempty valuesthe keys are coordinates and their values are data at the coordinates. You can use a similar structure to index people by their birthdays (use month, day, and year for the key), servers by their Internet Protocol (IP) numbers, and so on.
>>> D = {} >>> D[(2, 4, 6)] = 43 # 43 at position (2, 4, 6) >>> D[(5, 6, 7)] = 46 >>> X, Y, Z = (5, 6, 7) >>> D.get((X, Y, Z), 'Missing') 46 >>> D.get((0, Y, Z), 'Missing') 'Missing' >>> D {(2, 4, 6): 43, (5, 6, 7): 46}
# initialize data to be stored in files, pickles, shelves # records bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'} sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'mus'} tom = {'name': 'Tom', 'age': 50, 'pay': 0, 'job': None} # database db = {} db['bob'] = bob db['sue'] = sue db['tom'] = tom if _ _name_ _ == '_ _main_ _': # when run as a script for key in db: print key, '=>\n ', db[key]
As usual, the _ _name_ _ test at the bottom of Example 2-1 is true only when this file is run, not when it is imported. When run as a top-level script (e.g., from a command line, via an icon click, or within the IDLE GUI), the file's self-test code under this test dumps the database's contents to the standard output stream (remember, that's what print statements do by default).
Here is the script in action being run from a system command line on Windows. Type the following command in a Command Prompt window after a cd to the directory where the file is stored, and use a similar console window on other types of computers:
...\PP3E\Preview> python initdata.py bob => {'job': 'dev', 'pay': 30000, 'age': 42, 'name': 'Bob Smith'} sue => {'job': 'mus', 'pay': 40000, 'age': 45, 'name': 'Sue Jones'} tom => {'job': None, 'pay': 0, 'age': 50, 'name': 'Tom'}
Now that we've started running script files, here are a few quick startup hints:
On some platforms, you may need to type the full directory path to the Python program on your machine, and on recent Windows systems you don't need python on the command line at all (just type the file's name to run it).
You can also run this file inside Python's standard IDLE GUI (open the file and use the Run menu in the text edit window), and in similar ways from any of the available third-party Python IDEs (e.g., Komodo, Eclipse, and the Wing IDE).
If you click the program's file icon to launch it on Windows, be sure to add a raw_input( ) call to the bottom of the script to keep the output window up. On other systems, icon clicks may require a #! line at the top and executable permission via a chmod command.
I'll assume here that you're able to run Python code one way or another. Again, if you're stuck, see other books such as Learning Python for the full story on launching Python programs.
Now, all we have to do is store all of this in-memory data on a file. There are a variety of ways to accomplish this; one of the most basic is to write one piece of data at a time, with separators between each that we can use to break the data apart when we reload. Example 2-2 shows one way to code this idea.
#################################################################### # save in-memory database object to a file with custom formatting; # assume 'endrec.', 'enddb.', and '=>' are not used in the data; # assume db is dict of dict; warning: eval can be dangerous - it # runs strings as code; could also eval( ) record dict all at once #################################################################### dbfilename = 'people-file' ENDDB = 'enddb.' ENDREC = 'endrec.' RECSEP = '=>' def storeDbase(db, dbfilename=dbfilename): "formatted dump of database to flat file" dbfile = open(dbfilename, 'w') for key in db: print >> dbfile, key for (name, value) in db[key].items( ): print >> dbfile, name + RECSEP + repr(value) print >> dbfile, ENDREC print >> dbfile, ENDDB dbfile.close( ) def loadDbase(dbfilename=dbfilename): "parse data to reconstruct database" dbfile = open(dbfilename) import sys sys.stdin = dbfile db = {} key = raw_input( ) while key != ENDDB: rec = {} field = raw_input( ) while field != ENDREC: name, value = field.split(RECSEP) rec[name] = eval(value) field = raw_input( ) db[key] = rec key = raw_input( ) return db if _ _name_ _ == '_ _main_ _': from initdata import db storeDbase(db)
This is a somewhat complex program, partly because it has both saving and loading logic and partly because it does its job the hard way; as we'll see in a moment, there are better ways to get objects into files than by manually formatting and parsing them. For simple tasks, though, this does work; running Example 2-2 as a script writes the database out to a flat file. It has no printed output, but we can inspect the database file interactively after this script is run, either within IDLE or from a console window where you're running these examples (as is, the database file shows up in the current working directory):
...\PP3E\Preview> python make_db_file.py ...\PP3E\Preview> python >>> for line in open('people-file'): ... print line, ... bob job=>'dev' pay=>30000 age=>42 name=>'Bob Smith' endrec. sue job=>'mus' pay=>40000 age=>45 name=>'Sue Jones' endrec. tom job=>None pay=>0 age=>50 name=>'Tom' endrec. enddb.
This file is simply our database's content with added formatting. Its data originates from the test data initialization module we wrote in Example 2-1 because that is the module from which Example 2-2's self-test code imports its data. In practice, Example 2-2 itself could be imported and used to store a variety of databases and files.
Notice how data to be written is formatted with the as-code repr( ) call and is re-created with the eval( ) call which treats strings as Python code. That allows us to store and re-create things like the None object, but it is potentially unsafe; you shouldn't use eval( ) if you can't be sure that the database won't contain malicious code. For our purposes, however, there's probably no cause for alarm.
To test further, Example 2-3 reloads the database from a file each time it is run.
from make_db_file import loadDbase db = loadDbase( ) for key in db: print key, '=>\n ', db[key] print db['sue']['name']
And Example 2-4 makes changes by loading, updating, and storing again.
from make_db_file import loadDbase, storeDbase db = loadDbase( ) db['sue']['pay'] *= 1.10 db['tom']['name'] = 'Tom Tom' storeDbase(db)
Here are the dump script and the update script in action at a system command line; both Sue's pay and Tom's name change between script runs. The main point to notice is that the data stays around after each script exitsour objects have become persistent simply because they are mapped to and from text files:
...\PP3E\Preview> python dump_db_file.py bob => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} sue => {'pay': 40000, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} tom => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom'} Sue Jones ...\PP3E\Preview> python update_db_file.py ...\PP3E\Preview> python dump_db_file.py bob => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} sue => {'pay': 44000.0, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} tom => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom Tom'} Sue Jones
As is, we'll have to write Python code in scripts or at the interactive command line for each specific database update we need to perform (later in this chapter, we'll do better by providing generalized console, GUI, and web-based interfaces instead). But at a basic level, our text file is a database of records. As we'll learn in the next section, though, it turns out that we've just done a lot of pointless work.
The formatted file scheme of the prior section works, but it has some major limitations. For one thing, it has to read the entire database from the file just to fetch one record, and it must write the entire database back to the file after each set of updates. For another, it assumes that the data separators it writes out to the file will not appear in the data to be stored: if the characters => happen to appear in the data, for example, the scheme will fail. Perhaps worse, the formatter is already complex without being general: it is tied to the dictionary-of-dictionaries structure, and it can't handle anything else without being greatly expanded. It would be nice if a general tool existed that could translate any sort of Python data to a format that could be saved on a file in a single step.
That is exactly what the Python pickle module is designed to do. The pickle module translates an in-memory Python object into a serialized byte streama string of bytes that can be written to any file-like object. The pickle module also knows how to reconstruct the original object in memory, given the serialized byte stream: we get back the exact same object. In a sense, the pickle module replaces proprietary data formatsits serialized format is general and efficient enough for any program. With pickle, there is no need to manually translate objects to data when storing them persistently.
The net effect is that pickling allows us to store and fetch native Python objects as they are and in a single stepwe use normal Python syntax to process pickled records. Despite what it does, the pickle module is remarkably easy to use. Example 2-5 shows how to store our records in a flat file, using pickle.
from initdata import db import pickle dbfile = open('people-pickle', 'w') pickle.dump(db, dbfile) dbfile.close( )
When run, this script stores the entire database (the dictionary of dictionaries defined in Example 2-1) to a flat file named people-pickle in the current working directory. The pickle module handles the work of converting the object to a string. Example 2-6 shows how to access the pickled database after it has been created; we simply open the file and pass its content back to pickle to remake the object from its serialized string.
import pickle dbfile = open('people-pickle') db = pickle.load(dbfile) for key in db: print key, '=>\n ', db[key] print db['sue']['name']
Here are these two scripts at work, at the system command line again; naturally, they can also be run in IDLE, and you can open and inspect the pickle file by running the same sort of code interactively as well:
...\PP3E\Preview> python make_db_pickle.py ...\PP3E\Preview> python dump_db_pickle.py bob => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} sue => {'pay': 40000, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} tom => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom'} Sue Jones
Updating with a pickle file is similar to a manually formatted file, except that Python is doing all of the formatting work for us. Example 2-7 shows how.
import pickle dbfile = open('people-pickle') db = pickle.load(dbfile) dbfile.close( ) db['sue']['pay'] *= 1.10 db['tom']['name'] = 'Tom Tom' dbfile = open('people-pickle', 'w') pickle.dump(db, dbfile) dbfile.close( )
Notice how the entire database is written back to the file after the records are changed in memory, just as for the manually formatted approach; this might become slow for very large databases, but we'll ignore this for the moment. Here are our update and dump scripts in actionas in the prior section, Sue's pay and Tom's name change between scripts because they are written back to a file (this time, a pickle file):
...\PP3E\Preview> python update_db_pickle.py ...\PP3E\Preview> python dump_db_pickle.py bob => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} sue => {'pay': 44000.0, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} tom => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom Tom'} Sue Jones
As we'll learn in Chapter 19, the Python pickling system supports nearly arbitrary object typeslists, dictionaries, class instances, nested structures, and more. There, we'll also explore the faster cPickle module, as well as the pickler's binary storage protocols, which require files to be opened in binary mode; the default text protocol used in the preceding examples is slightly slower, but it generates readable ASCII data. As we'll see later in this chapter, the pickler also underlies shelves and ZODB databases, and pickled class instances provide both data and behavior for objects stored.
In fact, pickling is more general than these examples may imply. Because they accept any object that provides an interface compatible with files, pickling and unpickling may be used to transfer native Python objects to a variety of media. Using a wrapped network socket, for instance, allows us to ship pickled Python objects across a network and provides an alternative to larger protocols such as SOAP and XML-RPC.
As mentioned earlier, one potential disadvantage of this section's examples so far is that they may become slow for very large databases: because the entire database must be loaded and rewritten to update a single record, this approach can waste time. We could improve on this by storing each record in the database in a separate flat file. The next three examples show one way to do so; Example 2-8 stores each record in its own flat file, using each record's original key as its filename with a .pkl prepended (it creates the files bob.pkl, sue.pkl, and tom.pkl in the current working directory).
from initdata import bob, sue, tom import pickle for (key, record) in [('bob', bob), ('tom', tom), ('sue', sue)]: recfile = open(key+'.pkl', 'w') pickle.dump(record, recfile) recfile.close( )
Next, Example 2-9 dumps the entire database by using the standard library's glob module to do filename expansion and thus collect all the files in this directory with a .pkl extension. To load a single record, we open its file and deserialize with pickle; we must load only one record file, though, not the entire database, to fetch one record.
import pickle, glob for filename in glob.glob('*.pkl'): # for 'bob','sue','tom' recfile = open(filename) record = pickle.load(recfile) print filename, '=>\n ', record suefile = open('sue.pkl') print pickle.load(suefile)['name'] # fetch sue's name
Finally, Example 2-10 updates the database by fetching a record from its file, changing it in memory, and then writing it back to its pickle file. This time, we have to fetch and rewrite only a single record file, not the full database, to update.
import pickle suefile = open('sue.pkl') sue = pickle.load(suefile) suefile.close( ) sue['pay'] *= 1.10 suefile = open('sue.pkl', 'w') pickle.dump(sue, suefile) suefile.close( )
Here are our file-per-record scripts in action; the results are about the same as in the prior section, but database keys become real filenames now. In a sense, the filesystem becomes our top-level dictionaryfilenames provide direct access to each record.
...\PP3E\Preview> python make_db_pickle_recs.py ...\PP3E\Preview> python dump_db_pickle_recs.py bob.pkl => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} tom.pkl => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom'} sue.pkl => {'pay': 40000, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} Sue Jones ...\PP3E\Preview> python update_db_pickle_recs.py ...\PP3E\Preview> python dump_db_pickle_recs.py bob.pkl => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} tom.pkl => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom'} sue.pkl => {'pay': 44000.0, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} Sue Jones
Pickling objects to files, as shown in the preceding section, is an optimal scheme in many applications. In fact, some applications use pickling of Python objects across network sockets as a simpler alternative to network protocols such as the SOAP and XML-RPC web services architectures (also supported by Python, but much heavier than pickle).
Moreover, assuming your filesystem can handle as many files as you'll need, pickling one record per file also obviates the need to load and store the entire database for each update. If we really want keyed access to records, though, the Python standard library offers an even higher-level tool: shelves.
Shelves automatically pickle objects to and from a keyed-access filesystem. They behave much like dictionaries that must be opened, and they persist after each program exits. Because they give us key-based access to stored records, there is no need to manually manage one flat file per recordthe shelve system automatically splits up stored records and fetches and updates only those records that are accessed and changed. In this way, shelves provide utility similar to per-record pickle files, but are usually easier to code.
The shelve interface is just as simple as pickle: it is identical to dictionaries, with extra open and close calls. In fact, to your code, a shelve really does appear to be a persistent dictionary of persistent objects; Python does all the work of mapping its content to and from a file. For instance, Example 2-11 shows how to store our in-memory dictionary objects in a shelve for permanent keeping.
from initdata import bob, sue import shelve db = shelve.open('people-shelve') db['bob'] = bob db['sue'] = sue db.close( )
This script creates one or more files in the current directory with the name people-shelve as a prefix; you shouldn't delete these files (they are your database!), and you should be sure to use the same name in other scripts that access the shelve. Example 2-12, for instance, reopens the shelve and indexes it by key to fetch its stored records.
import shelve db = shelve.open('people-shelve') for key in db: print key, '=>\n ', db[key] print db['sue']['name'] db.close( )
We still have a dictionary of dictionaries here, but the top-level dictionary is really a shelve mapped onto a file. Much happens when you access a shelve's keysit uses pickle to serialize and deserialize, and it interfaces with a keyed-access filesystem. From your perspective, though, it's just a persistent dictionary. Example 2-13 shows how to code shelve updates.
from initdb import tom import shelve db = shelve.open('people-shelve') sue = db['sue'] # fetch sue sue['pay'] *= 1.50 db['sue'] = sue # update sue db['tom'] = tom # add a new record db.close( )
Notice how this code fetches sue by key, updates in memory, and then reassigns to the key to update the shelve; this is a requirement of shelves, but not always of more advanced shelve-like systems such as ZODB (covered in Chapter 19). Also note how shelve files are explicitly closed; some underlying keyed-access filesystems may require this in order to flush output buffers after changes.
Finally, here are the shelve-based scripts on the job, creating, changing, and fetching records. The records are still dictionaries, but the database is now a dictionary-like shelve which automatically retains its state in a file between program runs:
...\PP3E\Preview> python make_db_shelve.py ...\PP3E\Preview> python dump_db_shelve.py bob => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} sue => {'pay': 40000, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} Sue Jones ...\PP3E\Preview> python update_db_shelve.py ...\PP3E\Preview> python dump_db_shelve.py tom => {'pay': 0, 'job': None, 'age': 50, 'name': 'Tom'} bob => {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'} sue => {'pay': 60000.0, 'job': 'mus', 'age': 45, 'name': 'Sue Jones'} Sue Jones
When we ran the update and dump scripts here, we added a new record for key tom and increased Sue's pay field by 50 percent. These changes are permanent because the record dictionaries are mapped to an external file by shelve. (In fact, this is a particularly good script for Suesomething she might consider scheduling to run often, using a cron job on Unix, or a Startup folder or msconfig entry on Windows.) | https://flylib.com/books/en/2.726.1.21/1/ | CC-MAIN-2019-43 | refinedweb | 3,864 | 69.92 |
Well, I was working on a project in which I required a rating control. This rating control is developed using web control class in which we have 4 properties. By using these properties, we can use the rating control.
I Googled and found paid rating controls. Then I decided to develop my own rating control.
Using this control is very easy. We have a class Voting in MyVote namespace. In the Voting class, we have 4 properties.In this control, we have 4 properties in MyVotele or code.
Voting
MyVote
MyVotele
View online demo.
VoteCount
MouseOver_ImagePath
MouseOut_ImagePath
StarCount
In a *.aspx page, you have to register a control:
<%@ Register TagPrefix="MyBar" Namespace="MyVote" %>
In a *.aspx page between form tags, write this:
<MyBar:voting
</MyBar:voting>
This control is very easy to use in different. | http://www.codeproject.com/Articles/27787/Rating-Control-using-Custom-Web-Control | CC-MAIN-2015-32 | refinedweb | 135 | 69.79 |
SVG content can be styled by either CSS (see "Cascading Style Sheets (CSS) level 2" specification [CSS2]) or XSL (see "XSL Transformations (XSLT) Version 1.0" [XSLT1]).
SVG content using CSS or XSL for styling"
[ESS].
SVG supports various relevant properties and approaches common to CSS and XSL, plus selected semantics and features of CSS (see the "Cascading Style Sheets (CSS) level 2" Recommendation [CSS2].
SVG uses styling properties to describe many of its document parameters. In particular, SVG uses styling.)
Additionally, SVG defines a new
@color-profile
at-rule [CSS2-ATRULES]
for defining color profiles to use within SVG content.
Attribute definitions:
The 'style' element allows authors to put style sheet rules embedded within SVG content. 'style' elements are only allowed as children of 'defs' elements. December 1999//EN" ""> <svg width="4in" height="3in"> <defs> <style><!.
An XSL style sheet ([XSLT1]) can also
be embedded within a 'style' element,
in which case it is not necessary to enclose the style sheet within
a
CDATA construct, since XSL style sheets are expressed in XML. attributes>
The following CSS style rules would tell visual user agents to display informational messages in green, warning messages in yellow, and error messages in red:
text.info { color: green } text.warning { color: yellow } text.error { color: red }
Attribute definitions:
The default style sheet language for the style attribute is "text/css" unless any HTTP headers specify the "Content-Style-Type", in which case the last one in the character stream determines the default style sheet language. following define the scope/range of style sheets:
A value other than display: none indicates that the given element
shall
be rendered by the SVG user agent.
The user agent's default style sheet for elements in the SVG namespace for visual media [CSS2-VISUAL] must include the following entries:
svg, symbol, marker, pattern, view { overflow: hidden }
Refer the description of SVG's use of the 'overflow' property for more information.
Also, refer to the "Cascading Style Sheets (CSS) level 2" specification [CSS2].
The SVGStyleElement interface corresponds to the 'style' element. | http://www.w3.org/TR/1999/WD-SVG-19991203/styling.html | CC-MAIN-2016-44 | refinedweb | 342 | 53.1 |
31 July 2012 08:28 [Source: ICIS news]
SINGAPORE (ICIS)--Butadiene rubber (BR) prices in ?xml:namespace>
Domestic BR prices fell by yuan (CNY) 1,500-1,700/tonne ($235-266/tonne) from 10 July to CNY20,800-21,500/tonne on 30 July, according to Chemease, an ICIS service in
Buyers have retreated to the sidelines to wait for further decline in prices before replenishing their stocks, market sources said.
Falling natural rubber (NR) prices weighed on the BR market. NR prices in the Shanghai Futures Exchange (SHFE) for January delivery closed at CNY22,810/tonne on 30 July, down by CNY445/tonne compared with the previous week’s on 23 July. NR and BR substitute each other in tyre production and their prices tend to move in tandem.
Falling BD prices also weakened the confidence of BR players. Some industry sources confirmed that BD prices fell by CNY1,000/tonne on 30 July to CNY19,000-19,300/tonne in east
BR supply is expected to be stable in August but demand from the downstream users is weak.
TSRC-UBE (
However, other major BR plants in China, such as Sinopec Shanghai Gaoqiao’s 120,000 tonne/year BR plant, Sinopec Beijing Yanshan’s 120,000 tonne/year BR plant and Daqing Petrochemical’s 80,000 tonne/year BR plant, are running at 100% capacity, said the market sources, adding that domestic the average BR operating rate is above 70% capacity.
Downstream demand is weak because of the low operating rates at the facilities of tyre makers and other producers that use rubber as a raw material, such as shoe makers. Major Chinese tyre producers Linglong Tyre and Triangle Tyre said that the operating rates of some small- and medium-sized producers were running at only 20-30% of capacity. As a result, the BR market is subdued.
Some industry sources said that they are worried that the BR price downtrend will continue on the back of poor demand in Aug | http://www.icis.com/Articles/2012/07/31/9582215/chinas-br-prices-may-extend-fall-on-poor-demand-weaker-bd.html | CC-MAIN-2014-52 | refinedweb | 332 | 54.76 |
in reply to
If you believe in Lists in Scalar Context, Clap your Hands
I think the problem is program code vs. execution.
Look at this code:
sub foo {
...
return ($x, $y, $z);
}
[download]
Now this code:
my $x = foo();
This is a function call in scalar context. Now, together
with the definition of the subroutine above, the sub
somehow returns the list in scalar context. By definition.
Which, during runtime turns out to be a scalar,
because the list never existed, because perl knows the
context early enough. So I would agree there is no list
in scalar context during runtime, but for me it's clearly
describing what code does. Whenever I read another
post "There is no list in scalar context" I think, *sigh*,
yeah, there might never exist such a list, but it's a
good description of the behaviour.
By the definition, this sub returns a list.
Note also that:
sub look_ma_I_am_returning_an_empty_list {
return ();
}
[download]
it returns the value of the last expression, evaluated in the context the function was called in
For a start, you'd have to modify that with s[was][will be].
Like I say, the alternatives suck! Bigtime!... :).
Used as intended
The most useful key on my keyboard
Used only on CAPS LOCK DAY
Never used (intentionally)
Remapped
Pried off
I don't use a keyboard
Results (439 votes),
past polls | http://www.perlmonks.org/?node_id=719320 | CC-MAIN-2015-11 | refinedweb | 230 | 67.69 |
The QPaintEvent class contains event parameters for paint events. More...
#include <QPaintEvent>
Inherits QEvent.
The QPaintEvent class contains event parameters for paint events. the processing of a paint event.
See also QPainter, QWidget::update(), QWidget::repaint(), and QWidget::pain().
Constructs a paint event object with both a paintRegion and a paintRect, both of which represent the area of the widget that needs to be updated.
Returns true if the paint event region (or rectangle) has been erased with the widget's background; otherwise returns false.
Qt 4 always erases regions that require painting. The exception to this rule is if the widget sets the Qt::WA_OpaquePaintEvent or Qt::WA_NoSystemBackground attributes. If either one of those attributes is set and the window system does not make use of subwidget alpha composition (currently X11 and Windows, but this may change), then the region is not erased. | http://doc.trolltech.com/4.2/qpaintevent.html | crawl-002 | refinedweb | 144 | 65.93 |
:
No installation instructions: this port has been deleted.
The package name of this deleted port was: apache20
apache20
PKGNAME: apache
distinfo: There is no distinfo for this port.
NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered.
No options to configure20
Reason:
The rc.d script has been renamed:
apache2.sh -> apache2
You'll need to update any crons wrappers, etc. for the new paths.
Author: clement@FreeBSD.org
Reason:
BDB framework provided by bsd.database.mk is now used by www/apache20
port. WITH_BERKELEYDB knob is deprecated in favor of WITH_BDB and
WITH_BDB_VER/WITH_BDB_BASE, see documentation for more details ('make
show-options').
Number of commits found: 122 (showing only 100 on this page)
1 | 2 »
- remove www/apache20 and devel/apr0
- s/USE_APACHE= 20+/USE_APACHE= 22+/
- unify s/YES/yes/
- cleanup APACHE_VERSION <= 22 usage
- add entry to MOVED)
- apache20 has no SLAVE_PORTS so cleanup and simplify Makefile.modules
- use port framework instead pkg-install to check for www user
- no REVISION bump, logic / functionality has not changed
with hat apache@
- cleanup conflicts (remove no longer existent ports)
- remove explicit ABI version number from LIB_DEPENDS
Bump pcre library dependency due to 8.30 update
Add (vendor) patch for deprecated pcre_info()
- Fix WITH_LDAP support by adding =shared
PR: ports/147806 (sync with the rest of them)
With Hat: apache@
- bump PORTREVISION (devel/apr0 update)
- set EXPIRATION date to 2012-02-01
- Close a race condition that sometimes resulted in configure.in patches being
ignored
- DEPRECATE and set EXPIRATION_DATE
apache 2.3.10 will be release next week, 2.3.11 will be 1st beta shortly
after that. 2.4.0 GA will follow not long after. Once 2.4.0 is released
2.0.x will be EOL upstream at httpd ASF.
Get this in before 7.4/8.2 to help raise awareness and start migration plans.
- Work is already well in to move the default apache to www/apache22, help is appreciated
there
with the goal to have this be true before 9.0.
- www/apache13* are on track to be deprecated after 9.0. apache1.3.x support
has
been EOL upstream at ASF almost 1 year already.
With Hat: apache@
Discussed with: httpd@dev.a.o, private@dev.a.o, #bsdports
Sync to new bsd.autotools.mk
- forced commit, no changes, try to help QAT
- missed one
- Update to 2.0.64
- normalize patch-pcre.diff into makepatch format
- All 4 CVE patches are included upstream and part of 2.0.64
- part of the local apxs.in changes are upstream now too
- some patches were regenerated for offset updates
** There is NO security update here. **
Changes:
With Hat: apache@
<ChangeLog>
*) SECURITY: CVE-2010-1452 (cve.mitre.org)
mod_dav: Fix Handling of requests without a path segment.
PR: 49246 [Mark Drayton, Jeff Trawick]
Punt autoconf267->autoconf268
Autotools update. Read ports/UPDATING 20100915 for details.
Approved by: portmgr (for Mk/bsd.port.mk part)
Tested by: Multiple -exp runs
- conflicts with www/apache22*
- Fix the exactly one s/REG_EXTENDED/AP_REG_EXTENDED/ I missed.
- This is a non default option in the compile so no PORTREVISION bump
Reported by: henrik@iaeste.dk
With Hat: apache@
- force a retry for QAT, no changes
- I was so busy run-time testing this I didn't notice the new file.
fix the pkg-plist
Reported by: QAT
- Partial httpd SVN MFC of r15338
[]
Essentially this internalizes the pcre POSIX API in the ap_ namespace.
Thus fixing the use of an external pcre library and hence mod_redirect
and other consumers.
- This includes an MMN bump which means you will need to recompile all your
modules. With ports this will happen when you upgrade via portmaster or
portupgrade. If you have any modules outside of ports they will need to
be recompiled too.
- There is a small chance you will need to change some of your custom modules
to adapt to the ap_regex_t and ap_regmatch_t api changes.
- For security, speed, maintenance, and simplification in the ports/ framework
this route was chosen instead of reverting the devel/pcre change in 2.0.63_4.
PR: ports/146604
Reported by: Stefan Bethke <stb@lassitu.de>, serveral on ports@, apache@
With Hat: apache@
- Fix 5 seen in 3rd party module failures due to converting from bundled apr to
ports apr.
Reported by: pav via pointyhat
With Hat: apache@
- lib/apache2 is empty and doesn't exist
- Bump PORTREVISION
Reported by: Geraint Edwards <gedge@yadn.org> via apache@
- whitespace only
- Bump PORTREVISION
With Hat: apache@
- Whitespace
With Hat: apache@
- Force devel/apr0. Bundled srclib/apr is never used now.
With Hat: apache@
- Whitespace only
With hat: apache@
- drop KQUEUE_SUPPORT, patch doesn't apply cleaning to devel/apr0
Patches to devel/apr0 are welcome, send-pr.
With Hat: apache@6928
Submitted by: Alexey V.Degtyarev <alexey@renatasystems.org>
With Hat: apache@
- Fix some runtime devel/pcre conversion fallout
the bundled pcre defined REG_NOSUB as 0 b/c its not used
the devel/pcre port (8.0.0) defines it as 0x0020 which is causing havoc
The REG_NOSUB was never used by pcre in www/apache20
So, replace it with 0 in the www/apache20 code forcibly
- Bump PORTERVISION
PR: ports/146399
Reported by: ervin valentin <ervin23@gmail.com>
With Hat: apache@
- Carry the bundled apr patch through current freebsd versions.
clement@ added this patch in 1.201 of Makefile for fbsd 6.x
This only adds -funsigned-char to CFLAGS and I haven't seen
it break anything or anyone report any issues with not having the update.
It was also only neccessary in apr 0.9.x not apr 1.x+
This was remove entirely in
- Bump PORTREVISION
With Hat: apache@
- Dupliate $] fix in apxs in www/apache22
- Rename rc.d script apache2.sh -> apache2
- Bump PORTREVISION
With Hat: apache@
- Fix openssl rengotiation patch [1]
- Fix the openssl from ports flag
- Bump PORTREVISION
- Also patch 2 more CVEs
*)]
PR: ports/146389 [1]
Submitted by: several [1]
With Hat: apache@
- Back out the OPTIONS framework for now. Makefile.modules MODULES options
also be in OPTIONS or they aren't passed to make.
Thats one huge subtlety. I'll fix this later, but don't have time now.
Reported by: kevin brintnall <kbrint@qwest.net> via e-mail
Pointy hat: myself
With Hat: apache@
- That was the wrong patch file, too much git/cvs for me
- Fix -A and -a options for apxs to correctly ignore whitespace.
This will fix about 100 pkg-plist left overs for httpd.conf
- Bump PORTREVISION
- This will be in 2.0.64
PR: ports/133704
Obtained from:
Reported by: olli hauer <ohauer@gmx.de> (and very good pr!)
With Hat: apache@
- This file is never included.
$ grep -R Makefile.modules.3rd ${PORTSDIR}/
UPDATING: - Makefile.modules.3rd contains modules selection for apache 2.x and
1.3.x
www/apache20/CVS/Entries:/Makefile.modules.3rd/1.23/Sun Aug 2 19:35:56 2009//
With Hat: apache@
- Add DBM=ndbm support
PR: ports/83644
Submitted by: Oliver Brandmueller <ob@gruft.de>
With Hat: apache@
-@
- duplicate www/apache22 re-fix for /etc/ftpusers in www/apache20
PR: ports/144422
Reported by: several
With hat: apache@
- Apply SECURITY: CVE-2009-3555 (cve.mitre.org)
to www/apache20 as well.
PR: ports/140357
Submitted by: Eygene Ryabinkin <rea-fbsd@codelabs.ru>
With Hat: apache@
- Take stab at adding OPTIONS framework in limited capacity.
Some options were intentionally omitted.
- Remove a legacy option kludge
PR: ports/146199
Requested by: Nick Hibma <nick@anywi.com>
With Hat: apache@
- Force devel/pcre and abandon the bundled pcre:
0) its like 7yrs old
0) the new version have speed,bug,&security fixes
0) www/apache22 already does this
0) www/apache23+ no longer bundle pcre [or apr* for that matter]
- Bump PORTREVISION
With Hat: apache@
- Set the ITK version.
With Hat: apache@
- Sync with the www/apache22 layout for mpm itk and *only* conditionally
apply this patch. [Note, they are different revisions]
With Hat: apache@
- Regenerate patch files with make makepatch for they have
piled up and additional patches conflict.
This also will help when we try to syncronize www/apache20&www/apache22
With Hat: apache@
- Fix build for !root users
duplicated from www/apache22 and devel/apr
Originally:
PR: ports/13876 [based on]
Submitted by: Mel Flynn <mel@rachie.is-a-geek.net>
With Hat: apache@
- Fix compile with security/openssl
- No PORTREVISION bump [security/openssl is not the default]
PR: ports/146218
Submitted by: Kazuo Dohzono <dohzono@axion-software.com>
Obtained from:
With Hat: apache@
[I will contemplate sending this back to dev@httpd for branches/2.0.x for
2.0.64]
- openssl patch is unconditionally applied
With Hat: apache@
- Fix another IGNORE message
- Fix some whitespace
- Silence portlitn for IGNORE message
- CFLAGS is already in CONFIGURE_ENV
With Hat: apache@
- add caudium14 conflict
- fix caudium12 conflict
With Hat: apache@
- Fix typo preventing install/deinstall when /etc/ftpusers was present
Note if you already have www/apache20 or www/apache22 installed this is
not worth updating for; however, you should verify your [if you use it]
${PREFIX}/etc/apacheXX/extra/httpd-userdir.conf:
DisableUser dir setting correct lists the users you don't want
to have the ~/dir visible via http requests.
PR: ports/144422
Reported by: several
With hat: apache@
Cleanse uneeded RC_SUBR variables
Approved by: pgolluci.
- Backport apr-util security fixes pending the 2.2.12 release (forthcomming)
Security:
PR: ports/135310
Submitted by: Eygene Ryabinkin <rea-fbsd@codelabs.ru>
With Hat: apache
- Mark SAFE apache@ ports MAKE_JOBS_SAFE=yes
- Re-assign www/apache* ports to apache@
- Previous MATAINERs please welcome yourself to the apache@ team.
Approved by: portmgr (pav, flz), secteam (simon), clement
- Remove conditional checks for FreeBSD 5.x and older
Approved by: pav
- apache 2.0.x doesn't support BDB 4.7
- Revert previous patch to "fix" missing rc.d scripts. It
actually breaks profiles.
- Fix CVE-2008-2939 for mod_proxy_ftp
(XSS attacks when using wildcards in the path of the FTP URL)
- Bump PORTREVISION
- Fix grammatical error
Reported and fixed by: glarkin@
- Fix plist when NOPORTDOCS is defined [1]
- Sometimes, rc scripts aren't included in package
Try to fix this. [2]
- Bump PORTREVISION
PR: ports/124671 [2]
Reported by: QA Tindy [1],
George Donnelly [2]
Special thanks to: pgollucci@)
- Workaround a sh segfault on 6-STABLE
Reported by: many
- Fix recursive use of WITH_BDB_VER when WITH_BERKELEYDB and WITH_BDB_VER
are both defined.
Reported by: Vivek Khera <VIVEK@KHERA.ORG>
- Update to 2.0.63
- Use BDB from bsd.database.mk instead of homebrew [1]
PR: ports/119712 [1]
Submitted by: mm [1]
Switch autoconf dependencies from 2.53 or 2.59 to 2.61.
PR: ports/116639
Submitted by: aDe
- Fix profiles support in startup script [1]
- move envvars support to the beginning of apache2_checkconfig() to be
sure we're using envvars during configtest [2]
PR: ports/116401 [1],
ports/116329 [2]
Submitted by: kevin brintnall <kbrint@rufus.net> [1],
Ruud Althuizen <ruud@il.fontys.nl>
- Re-add apache2ssl_enable support
Noticed by: Oliver Brandmueller <ob at e-Gitt dot NET>
- Update to 2.0.61
- sync' startup script with www/apache22
- mod_dumpio to EXPERIMENTAL_MODULES
Requested by: pav
- Fix typo
- Add itk MPM
mpm-itk allows you to run each of your vhost under a separate UID and GID
WWW:
- use LD_CONFIG
Add support for setting WITH_BERKELEYDB to db44
- Update to 2.0.59
- Fix security issue in mod_rewrite.
All people using mod_rewrite are strongly encouraged to update.
Updates to latest versions will follow soon.
Notified by: so@ (simon)
Obtained from: Apache Security Team
Security: CVE-2006-3747
Remove USE_REINPLACE from categories starting with W
- Remove obsolete patch which add support to Windows Update Service when
apache acts as a proxy.
Reported by: Bjoern Voigt <bjoern@cs.tu-berlin.de>
- Fix build with WITH_KQUEUE_SUPPORT
Pointed out by: Marian Cerny <cerny@icomvision.com>
- Fix plist
Spotted by: mnag
Pointy hat to: clement
Oops I forgot to "cvs rm" a secfix
Spotted by: krion
- Update to 2.0.58.
Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD
18 vulnerabilities affecting 35 ports have been reported in the past 14 days
* - modified, not new
All vulnerabilities | http://www.freshports.org/www/apache20/?page=2 | CC-MAIN-2016-30 | refinedweb | 2,024 | 57.27 |
Retrieve the display modes supported by a specified display.
#include <screen/screen.h>
int screen_get_display_modes(screen_display_t display, int max, screen_display_mode_t *param)
The handle of the display whose display modes are being queried.
The maximum number of display modes that can be written to the array of modes pointed to by param.
The buffer where the retrieved display modes will be stored.
Function Type: Flushing Execution
This function returns the video modes that are supported by a display. All elements in the list are unique. Note that several modes can have identical resolutions and differ only in refresh rate or aspect ratio. You can obtain the number of modes supported by querying the SCREEN_PROPERTY_MODE_COUNT property. No more than max modes will be stored.
0 if a query was successful and the display mode is stored in param, or -1 if an error occurred (errno is set). | http://www.qnx.com/developers/docs/qnxcar2/topic/com.qnx.doc.qnxcar2.screen/topic/screen_get_display_modes.html | CC-MAIN-2019-47 | refinedweb | 145 | 65.52 |
(This is the first of two articles on changes to the C Runtime (CRT) in the Visual Studio “14” CTP. This article discusses the major architectural changes to the libraries; the second article will enumerate the new features, bug fixes, and breaking changes.).
On the one hand, this model of introducing differently named and completely independent sets of libraries each release makes it a bit easier for us to add new features and fix bugs. We can make breaking changes, e.g. to fix nonconforming or buggy behavior, at any time without worrying about breaking existing software components that depend on already-released versions of these libraries.
However, we have frequently heard from you, our customers, that this model is burdensome and in some cases makes it difficult to adopt new versions of Visual C++ due to dependencies on modules built with an older version of Visual C++ or the need to support plugins built with a particular version of Visual C++.
This problem has grown especially acute in recent years for two reasons. First, we have accelerated the release schedule of Visual Studio in order to make new features available more frequently. Second, it has become very important to support devices smaller than desktops or laptops, like phones, and accumulating multiple copies of very similar libraries on such devices is less than ideal.
Even for us, this model of introducing new versions of the libraries can be painful at times. It makes it very expensive for us to fix bugs in already-released versions of the libraries because we are no longer actively working in the codebases for those versions, so fixes must be individually backported and tested. The result is that we usually fix only serious security vulnerabilities in old versions of the libraries. Other bugs are generally fixed only for the next major version.
We can’t fix the past: the versions of these libraries that have already been released are not going away. But we are going to try to make improvements to this experience for the future. This is a major undertaking and will take some time, but we plan to make gradual process, starting with…
The Refactoring of the CRT
The CRT sits at the bottom of the Visual C++ libraries stack: the rest of the libraries depend on it and practically all native modules depend on it as well. It contains two kinds of stuff: [1] the C Standard Library and various extensions, and [2] runtime functionality required for things like process startup and exception handling. Because the CRT sits at the bottom of the stack, it is the logical place to start the process of stabilizing the libraries..
We are also working to unify the CRTs used for different platforms. In Visual Studio 2013, we built separate “flavors” of the CRT for different platforms. For example, we had separate CRTs for desktop apps, Windows Store apps, and Windows Phone apps. We did so because of differences in which Windows API functions are available on different platforms.
In Windows Store and Windows Phone apps, only a subset of the Windows API is available for use, so we need to implement some functions differently and cannot implement other functions at all (for example, there’s no console in Windows Store and Windows Phone apps, so we don’t provide the console I/O functionality in the CRT). The CRT for desktop apps must run on all supported operating systems (in Visual Studio 2013 this included Windows XP) and must provide the full set of functionality, including legacy functionality.
In order to unify these different CRTs, we have split the CRT into three pieces:
VCRuntime (vcruntime140.dll): This DLL contains all of the runtime functionality required for things like process startup and exception handling, and functionality that is coupled to the compiler for one reason or another. We may need to make breaking changes to this library in the future.
AppCRT (appcrt140.dll): This DLL contains all of the functionality that is usable on all platforms. This includes the heap, the math library, the stdio and locale libraries, most of the string manipulation functions, the time library, and a handful of other functions. We will maintain backwards compatibility for this part of the CRT.
DesktopCRT (desktopcrt140.dll): This DLL contains all of the functionality that is usable only by desktop apps. Notably, this includes the functions for working with multibyte strings, the exec and spawn process management functions, and the direct-to-console I/O functions. We will maintain backwards compatibility for this part of the CRT.
While I’ve named the release DLLs in the list, there are also equivalent debug DLLs and release and debug static CRT libraries for each of these. The usual lib files (
msvcrt.lib,
libcmt.lib, etc.) are built such that the newly refactored CRT is a drop-in replacement for the old CRT at build-time, so long as
/nodefaultlib is not used.
While we have retained the version number in the DLL for this CTP, we plan to remove it from the AppCRT and DesktopCRT before the final release of Visual Studio “14,” since we will be updating those DLLs in-place. Finally, we are still working on the final packaging of functionality, so we may move things among the DLLs before the final release.
Windows Store and Windows Phone apps will be able to use the functionality from the VCRuntime and the AppCRT only; desktop apps will be able to use all of that functionality plus the functionality from the DesktopCRT. In this first Visual Studio “14” CTP, all apps depend on all three parts of the refactored CRT; this is merely a temporary state of affairs that will be fixed eventually.
The Problem of Maintainability
One of the biggest problems that we had to solve in order to consider stabilizing the libraries in this way was the problem of maintainability. The CRT is a very old codebase, with many source files dating back to the 1980s. In many parts of the code, optimization techniques that were valid and useful decades ago not only obfuscated the code and made it difficult to maintain, but also hampered the modern compiler’s ability to optimize the code. In other areas, years of bolted-on features and bug fixes had turned once-beautiful C code into a hideous maintenance nightmare. If we were going to consider stabilizing the libraries so that we could update them in-place, we’d need to improve the maintainability first, otherwise we’d incur great cost to fix bugs and make improvements later..
This isn’t merely a theoretical problem. In Visual Studio 2013, we added many of the C99 functions that were previously missing (see Pat’s blog post from last year). However, there were a number of things that we were unable to implement. Two of the most conspicuous missing features were [1] the
snprintf function and [2] the format string enhancements like the
z and
t length modifiers for the
size_t and
ptrdiff_t types. It was late in the product cycle when we started looking at implementing these, and decided we simply could not implement them with confidence that we weren’t breaking anything.
So, as part of this great refactoring of the CRT, we have done an enormous amount of work to simplify and improve the quality of the code, so that it is easier to add features and fix bugs in the future. We have converted most of the CRT sources to compile as C++, enabling us to replace many ugly C idioms with simpler and more advanced C++ constructs. The publicly callable functions are still declared as C functions, of course (
extern "C" in C++), so they can still be called from C. But internally we now take full advantage of the C++ language and its many useful features.
We have eliminated most of the manual resource management in the code through the introduction of several special-purpose smart pointer and handle types. Enormous functions have been split into smaller, maintainable pieces. We have eliminated 75%(2) of the conditional compilation preprocessor directives (
#ifdef,
#else, etc.) by converting internal implementation details to use C++ features like templates and overloading. We have converted most of the CRT source files to use a common coding style.
As part of this work, we’ve completely rewritten the core implementations of the
printf and
scanf functions (now with no
#ifdefs!). This has enabled us to implement the remaining C99 features for the stdio library, to improve correctness checks in the library, and to fix many conformance bugs and quirks. Just as importantly, this work has enabled us to discover and fix substantial performance issues in the library.. When writing characters to a
FILE we need to be careful to handle many cases like buffer exhaustion, end-of-line conversions, and character conversions. When writing characters to a string, we should simply be able to write through and increment the result pointer. After the refactoring, we were easily able to identify this performance problem and, more importantly, fix it. The
sprintf functions are now up to 8 times faster than they were in previous releases.
This is merely one example of where we’ve done major work and how that work has helped us to improve the quality of the library. In the next article we will enumerate all of the major features, bug fixes, and breaking changes to the CRT in the Visual Studio “14” CTP, similar to what Stephan wrote last week for the STL.
What Next?
We are nearing completion of the CRT refactoring. Undoubtedly there are bugs, and we encourage you to try out the Visual Studio “14” CTP and report any bugs that you find on Microsoft Connect. If you report bugs now, there’s a really good chance that we can fix them before the final release of Visual Studio “14.” We’ve already gotten a few bug reports; thank you to those of you who reported them!
We are investigating opportunities for similar stabilization efforts with other libraries. Given that the separately-compiled STL components (msvcp140.dll) are also very commonly used, we are considering our options for a similar stabilization of that functionality.
Note that near-term we are only considering stabilization of the separately-compiled code. We do not plan to make stability guarantees about any C++ Standard Library types or any inline code in the C++ headers. So, for example, if you pass a
std::vector to a function, both the caller and callee will still need to be compiled with the same STL headers and options. There are very long-term efforts to try to come up with a solution to this more general problem; for example, see Herb Sutter’s recent C++ Standardization Committee proposal N4028: Defining a Portable C++ ABI.
James McNellis (james.mcnellis@microsoft.com)
Senior Software Development Engineer, Visual C++ Libraries
(1) We ship most of the sources for the CRT with Visual Studio; you can find them in the Visual Studio installation directory under VCcrtsrc.
(2) In Visual Studio 2013 there are 6,830
#if,
#ifdef,
#ifndef,
#elif, and
#else directives in the sources that we ship with the product; in the Visual Studio “14” CTP there are 1,656. These numbers do not include directives in headers and they do include the STL source files which are largely untouched by this refactoring effort, so this isn’t a perfect measurement, but it’s indicative of the amount of cleanup that’s been done.
Join the conversationAdd Comment
Great job! Very cool.
One thing you didn't mention that I'm curious about — what is the behavior when I compile something using a new CRT feature in VS2015, but the user only has VS2014's CRT installed and tries to run the app?
Not sure about the new names, shouldn't they begin 'ms'. Makes them more immediately recognisable as Microsoft product.
This is very good news indeed. My team was struggling with the zoo of C++ runtime libraries required since time immemorial.
But what about compatibility of static libraries between compiler releases? As currently stands, it seems Microsoft guarantees forward/backward compatibility within VS release (2010, 2012, 2013, etc.), but there are no compatibility guarantees between compiler versions. There are not even any workarounds (like limiting features used in APIs) or guidelines to make sure that, for example, VS2013 can successfully build against VS2010-produced .lib.
In a large org feeding into one binary, this makes VS adoption all-or-nothing deal, slowing it considerably.
Removing the version number from the dll name will make it harder to maintain backwards compatibility in the future (from your perspective). From my perspective as a developer I'm not interested in a dll that carries all the baggage from the past. Please reconsider this change.
On another note I have always wondered why you aren't able to deploy the crt through Windows Update as important updates? It makes no sense that every single application compiled with VS must include the CRT redistributable.
What about the deployment story? Sad as it is, using vcredist seems to be a lingering, but frequent means of deploying the vc runtime (plus MFC et al.), but that has its own headaches (oh- you need the update 4 version, but you only have the update 2 version installed….ugh.)
Great work!
Here's to hoping we will one day see C99 support in full. The compiler seems to have some important pieces already in place in C++ mode. Our project (neovim) uses some C99 features like declare-anywhere, compound literals, VLAs (but we could live without that, only have one in the codebase), automatic cast from void (looks so much cleaner), designated initializers (cleanliness as well) and that's about it. We'd love to see it work with MSVC as well. As it stands, we'll have to get mingw/gcc or clang to compile it, to provide a working version to our windows users. I'll be watching out for news!
Any changes related to the "known dll" msvcrt.dll system component that may affect mingw/mingw-w64 toolchain users?
Nicolas> declare-anywhere, compound literals […] designated initializers
Implemented in VS 2013. See blogs.msdn.com/…/c-11-14-stl-features-fixes-and-breaking-changes-in-vs-2013.aspx from last year.
> automatic cast from void (looks so much cleaner)
This isn't a C99 feature. C89 allowed void * to implicitly convert to X *. (C++98 sensibly removed this massive hole in the type system.)
"Here's to hoping we will one day see C99 support in full. "
Please, please, please.
awesome, finally, thank you thank you thank you! The missing backwards compatibility always had me release many versions of my library, instead of a single one. I'm so happy when this is over.
Thanks for a great write-up!
I'm wondering functions like _snprintf. _snprintf (not _sprintf) has been there for a long time. So far, I used a wrapper function for simulating snprintf behavior. It looks like _snprintf is a separate implementation. Can you give us more information about _-prefixed functions? Thanks!
"In order to unify these different CRTs, we have split the CRT into three pieces:"
please read that.
I wonder how this compares to MSVCRT from the VC4.2/5/6 days.
Was this work inspired by the refactoring made in GCC and LLVM?
It might sound nuts for a Microsoft product but didn't you guys think of using LLVM instead of playing catch up? The license is permissive, you don't have to contribute code if you don't want to and you can use it at your own desire… I think everyone would win from that.
Btw, I understand you've put a lot of effort in but you should seriously consider this option. The cloud and the server adapted to the reality of the current situation…
I agree with Lilian, how awesome would it be to have Visual Studio with clang instead. It seems the clang guys are working on it, but Microsoft is trying to catch up with their own compiler.
Cory: what is the behavior when I compile something using a new CRT feature in VS2015, but the user only has VS2014's CRT installed and tries to run the app?
Apps that use the CRT will still be responsible for ensuring that the right version of the CRT is installed. For example, if you build an app with VS15, you’ll need to ensure that you install the redist for the VS15 CRT. If the VS14 CRT is already installed, the VS15 CRT will replace it, and anything that was using the VS14 CRT will continue to work with the new VS15 CRT. [Disclaimer: I’m not saying there will be anything called VS15; I’m merely using this as a placeholder for “the thing that comes after Visual Studio ‘14’.”]
BG: Not sure about the new names, shouldn't they begin 'ms'. Makes them more immediately recognizable as Microsoft product.
Most Microsoft-provided DLLs are not prefixed with “ms.” As an example, relatively few operating system DLLs in the system directory (system32 or syswow64) are prefixed with “ms.”
Sergey: What about compatibility of static libraries between compiler releases?
All objects built into a single module (DLL or EXE) should be built using the same compiler and library headers, and with the same compilation options. Trying to mix-and-match objects compiled with different compilers or with different library headers (or with different options that affect things like object layout or inlining) will very likely result in one-definition rule (ODR) violations, which are often quite difficult to debug.
If you need to build parts of your system with different compilers or library headers (or with different options), you should split your system into multiple modules (DLLs) so that the parts built with each toolchain and library set are isolated.
CMC: “using vcredist seems to be a lingering, but frequent means of deploying the vc runtime (plus MFC et al.), but that has its own headaches”
Apps will still be required to ensure that the correct version of the Visual C++ Libraries are installed. There will still be a redist, just like there is today; the only difference is that some DLLs will be updated in-place by newer redists.
Jon: Any changes related to the "known dll" msvcrt.dll system component that may affect mingw/mingw-w64 toolchain users?
There are no changes to any operating system components (like msvcrt.dll) in what we have delivered in the Visual Studio “14” CTP.
Kay: I'm wondering functions like _snprintf. _snprintf (not _sprintf) has been there for a long time…Can you give us more information about _-prefixed functions?
If you call _snprintf with an insufficiently large buffer, the buffer is not null-terminated and a negative value is returned. If you call snprintf with an insufficiently large buffer, the buffer is null terminated, and the value returned is the number of characters that would have been written to the buffer had it been sufficiently large.
Lilian: Didn't you guys think of using LLVM instead of playing catch up?
Even if we switched to use a different toolchain, we’d still need a good C Standard Library implementation on the Windows platforms. The MinGW toolchain on Windows uses the old Visual C++ 6 CRT (msvcrt.dll). When I last looked at the Clang/LLVM package for Windows, they compiled and linked with a recent version of the Visual C++ CRT.
1- Can you please point out which "C99 Standard Library features" and "C99 Core Language features" are missing from VS2013 Update 2 and VS2014 CTP 1?
2- Will we get <uchar.h> in VS2013 and / or VS214?
3- Does <tgmath> stand a chance to make its way to MSVC ever?
4- Since some C11 features are pre-requisite for many C++14 features, can we expect full/partial C11 support in VS at some point?
Thanks for this great elaborated article James and please keep coming back on VC blog!
Will MFC MBCS lib for vs14 would be continue proveded?
What difference does it make how the toolchain works when the whole windows platform is unstable due to careless defects such as cryptolocker or sasser ? No one who cares about reliability would ever use a microsoft product.
This is huge! Big relief to plugin developers, once mainstream products move on the VS2014 (Autodesk for example)
"142 different variations of printf"!
Out of curiosity I took a look at the output.c file you mentioned and what it looks like in the VS2013RTM.
It's dungeons and dragons there! You guys are brave, fearless people for even considering touching it
Great work!
A question somebody asked earlier: with this new in-place approach would it be possible to make the CRT part of the system release and updates? What is the driver for it being a separate redist, that developer needs to worry about?
This all sounds great but I'll only believe it when I see it.
a) Congrats on the refactoring and speed improvements
b) So it's DLL hell all over again? One CRT.DLL to rule them all, and woe if you're unknowingly depending on an old version's quirks? (ah well, you can always deploy the exact version in the app directory.)
c) quote:"… and anything that was using the VS14 CRT will continue to work with the new VS15 CRT" – yeah, *right*. I admire your confidence.
I'm not so sure this (one crt DLL to rule them all) is a such good thing, then again, I'm not sure the per-VS-Versions were a good thing either.
Have thoughts gone into versioning the CRT (et al.) independently from VS?
@Terry:
What, and go to a platform that gives us heartbleed?
Remember that a lot of the Operating System defects are found due to Windows being a more popular desktop system, so it is more profitable. That doesn't make it any less secure, it just means that there is more worth in finding these defects.
If the situation was reversed, how different do you think it would be? People would be scouring the *nix code to find these defects due to them being worth more and probably finding a lot more than you realise.
Anyway, on a more interesting topic.
On the topic of the refactored CRT and MSVCRT. Are the large portion of the runtime functions going to be in the backwards compatible parts of the CRT and things like the exception handling, type lookup and other things in the versioned parts? I'm curious about this because MSVCRT is normally used for getting access to the runtime functions and the other services are statically linked.
This could give one more reason to stop using MSVCRT and a viable alternative.
Does it properly support UTF-8 now? That has always been a long term complaint and one that needs to be redressed.
Guys here is what you should do:
– Download the free Windows 8.1 VM: modern.ie/…/virtualization-tools
– Download the free VS2014 CPT.
– Run VM and install VS2014 CPT in it.
On a good internet connection and strong powerful machine, all this can be setup in less than 30 minutes (I dedicated 4 GB of RAM to the readymade VM from the aforementioned Internet Explorer website).
Get all the answers by "TRYING" it out and _then_ send the feedback here or Connect; what's working and what's not, performance comparisons (befores and afters), geeky interesting stuff! Its C-Lang we are talking about, so act like it here PLEASE!
And how about the ups-this-was-a-breaking-change-even-intended-as-bug-fix updates?
After having some separate and great co-existing .NET framework version now we have in already 3 inplace updates for .NET4 and all of them came with such "bug fixes".
Like "Martin Ba" I recommend to check releasing CRT independed of VS version.
Great job. Implementation of legacy C functions using C++ templates will go a long way in making these functions superefficient and portable.
I find this astounding, does anyone else?
QUOTE.
END QUOTE
@Ed Patterson,
Yeah that was the ouch moment for me. James didn't mentioned how they fixed it though! I mean do they still depend on FILE object? Although, I am happy to see that significant performance, I would love to know more (as you can tell I am so into performance: blogs.msdn.com/…/bugs-fixed-in-the-spring-update.aspx)
@Super Mario:
He basically describes it in the post "When writing characters to a string, we should simply be able to write through and increment the result pointer". So, they write directly to a string, instead of a file.
As James (kinda) said, look in C:Program Files (x86)Microsoft Visual Studio 14.0VCcrtsrcappcrtoutput.cpp. there are two main functions, common_vfprintf and common_vsprintf. They defer to an internal output_processor class template. vfprintf provides a template parameter that delegates its writes to a FILE, vsprintf provides a template parameter that delegates its writes to a string.
So, basically: classes, templates, variadic templates, and lambdas (well, the lambdas aren't a key component of that, the change). Which are all weird to see in the implementation of a C API. But, they all make sense given the desired cleanup to tear apart the #if's, and the normal way of doing that in C++ would be classes and templates (or classes and virtual functions).
Also, the "getting rid of number from dll name" had odd timing given this recent-ish post blogs.msdn.com/…/10516280.aspx and its compatibility issue notes.
Tony Rance: I don’t have a list of which C99 and C11 language features are and are not supported. For library features, the Visual Studio “14” CTP includes almost everything from the C99 Standard Library that does not require compiler support. For example, <tgmath.h> and various pragmas are not supported for this reason. There are a few omissions that we know of (_Exit is missing; our wcstok has the incorrect signature), and there undoubtedly a few bugs, but otherwise everything should be implemented. If you find any C99 library conformance issues that could be resolved without additional compiler support, please report them on Microsoft Connect.
We do plan to implement <uchar.h>, we just haven’t done so yet. It’s high on our list of priorities, as is support for Unicode string literals.
Krzysztof Kawa: Even if the CRT was integrated into the operating system and even if it was pushed out to “older” OSes via Windows Update, app installers would still need to include a redist of some kind (perhaps a Windows Update package) to handle the case where the CRT hasn’t yet been installed on the machine (not everyone installs Windows Updates immediately, especially non-security updates). We have considered many options for improving the distribution experience, and there’s no “perfect” solution.
Crescens2k: Yes. The VCRuntime (the “versioned parts”) contains the exception handling and RTTI logic, support for various compiler features (/GS checks, the purecall handler, and other miscellaneous things), and some of the string handling functions (like memcpy, strlen, etc.). Everything else is in the AppCRT and DesktopCRT (the “backwards compatible parts”).
Kantos: No, UTF-8 locales are not supported.
Ed Patterson, Super Mario, Michael: Right. We generalized the formatting operation over an abstract “OutputAdapter” that handles the writing of characters to a FILE, to the console, to a string, or wherever. We can use most C++ features that do not require runtime support.
@James McNellis
I see apps crashing without explanation because of some missing KBxyz pretty frequently. Skype and facebook video chat do that to name some popular ones 😉 I'm not saying this is a good thing but it just wouldn't be anything new. Oh well, I guess dlls were both greatest and worst inventions of their time and we'll need to live with them for what they are.
Btw. I would love to hear what other ideas you considered. I bet that would be a great read 😉 I can imagine a few of my own and they too are flawed in one way or another or radically changing things (rendering them impossible to introduce now).
Very nice. I would hope that those silly Luddites who avoid C++ and stick with C because they think that it's faster will read this.
Is it correct that, at this time, calls to sprintf are "deferred" to fprintf except when using Visual Studio 14? If so, does the same apply to sscanf and fscanf?
"If so, does the same apply to sscanf and fscanf?"
Yes. But the temporary FILE object thing is a bit misleading. Someone may think that it involves an actual temporary file but that's not the case, there's no actual file involved. It's just that the input/output char array is used as the buffer of a FILE object created by the sscanf/sprints functions, without fopen being involved.
"Someone may think that it involves an actual temporary file", I did and it's nice to know it doesn't.
BG> Not sure about the new names, shouldn't they begin 'ms'. Makes them more immediately recognisable as Microsoft product.
I agree. It would be best if the files would be names according to some "namespace" such as mscrt_app.dll, mscrt_desktop.dll and mscrt.dll.
To be succinct in up-to 140 chars: ISO C++11/14 will be vcruntime140.dll…, C++17/19 ought to be vcruntime17.dll with minor version updating taken care of by Windows Update.
Is this correct?
Wow, what a pendulum swing. Still trying to make sense of it
Windows 95 era – msvcrt.dll – DLL Hell – causes chaos when you break existing subtle memory behaviour (crashing many apps) – KnownDLL era as well.
Windows 2000 era – msvcrt.dll under system file protection – better
Visual Studio 2002/2003 era – msvcr70/71 installed to system32 – isolated to the version you build with but DLL Hell in system32 (worse if bad installers come along and mess with yours since they're not under WFP)
Visual Studio 2005/2008 era – msvcr80/90 installed to WinSxS, but for all intents and purposes same DLL Hell issues as before since there are redirects set up so that manifests always get the latest, some hacks though
Visual Studio 2010/2012/2013 era – msvcr100/110/120 we're back to system32 same model as 2002 and 2003 but maybe they're protected a bit better by trustedinstaller. Still DLL Hell.
Visual Studio 2015+ – new DLLs can came along in system32 any time in the future and blow your app up or introduce security bugs (no longer isolated by compiler version) – super DLL Hell era. Onus is completely on Microsoft for "getting it right".
My question is, how do you intend to handle the DLL Hell issue?
Glad to see Microsoft finally supports C99!!
Please take this opportunity fix your unicode situation in your C runtime. We ought to be able to pass UTF-8 strings to the standard I/O functions. When I write cross-platform code, I always have to stand on my head because on Windows, I have to convert everything to utf16.
Even if you give a set of API routines with differing names, ie…open_utf8()… that is easy to deal with. Having to deal with two different text encodings with existing compilers is a major pain.
Perhaps the better solution is to provide a proper codepage so that existing ANSI functions can be configured to handle UTF8 input and output.
The other problem you have is the interfacing of char16_t to wchar_t. If was very awkward trying to work with c++11 code using Win32 APIs and your standard C library functions. It would be nice if the utf16 versions of functions would accept the output of std::u16string::c_str() without casts and std::u16string functions would accept wchar_t/wchar_t* without casts on Windows. However, the system is adjusted to make the code cleanly work without macro hacking or casts all over the place is fine with me.
@James,
Seriously! What is the alternate of System.Linq in your big-boy beloved language? Have you heard of .NET Native yet? Yes Microsoft has already invested their resources on .NET native to sidestep GC and VM.
Nevertheless, C++ remains the most portable language of the World in #2014! No need to create another proprietary spaghetti language like that..
Try to be:
1- "appreciative" of what has been done and what's scheduled to come your way.
2. "productive" by providing the useful feedback.
Thanks for the answer Stephan!
One thing confuses me though:
> This isn't a C99 feature. C89 allowed void * to implicitly convert to X *. (C++98 sensibly removed this massive hole in the type system.)
Yes, that's true, but is there any way at all we can force MSVC to accept these things in the same mode (compilation run)? We use both cast-less void conversions AND designated initializers AND compound literals…
Put shortly: how are we supposed to invoke cl.exe? Or run from within MSVC? We are interested in bringing our open-source project to Windows, but we haven't been having a too easy time and we don't want to backpedal on leaving C89 behind.
Nicolas:
Um. invoke cl.exe as normal?
>type Thing.c
#include <stdlib.h>
typedef struct {
int y, x;
} Point;
struct foo { int a; char b[2]; } structure;
int main(void) {
// implicit cast from void*
Point* p = malloc(sizeof(Point));
// designated initializers
Point x = { .x = -10, .y = 5401};
p->x = 10;
p->y = 104;
// compound literals
structure = ((struct foo) {p->x + x.y, 'a', 0});
free(p);
return 0;
}
>cl Thing.c
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.30501 for x86
Thing.c
Microsoft (R) Incremental Linker Version 12.00.30501.0
/out:Thing.exe
Thing.obj
If you wanted to be explicit, there's the /TC and /Tc command line options to force C compilation regardless of the file extension. In Visual Studio, it's settable with the "Compile As" option. Which is <CompileAs> in the vcxproj file. And as Stephan said, that's all just in VS2013.
Or did you want those three things AND C++ stuff? It looks like neovim only has .c files, since it's using CMake, does CMake have an option to force that setting? Or does it force the CompileAs option to something other than Default?
Hey Michael,
Thanks a lot for the reply. In your example I see many of the C99 features I would like to see (except for declare-anywhere), so perhaps we've been missing just some small things.
You are correct in your assertion that neovim has only .c files. We try to adhere strictly to the C99 standard. So if you say all of these things are possible, then I'm not sure why we're (currently) still failing. But we'll get there.
For reference, this is the "getting neovim on msvc" issue: github.com/…/696.
Sorry for double-posting Michael, but we got a bit further after confirming that MSVC 2013 nominally _does_ support declare anywhere.
The reason we were confused is because of some (seemingly) obscure frontend/parser bug. It's detailed in this neovim issue: github.com/…/696
It seems like MSVC 2013 doesn't accept declaring after a braceless control statement:
if (1)
printf("fails!");
Point x = { .x = -10, .y = 5401};
doesn't work
if (1) {
printf("fails!");
}
Point x = { .x = -10, .y = 5401};
works.
Because braceless statements do appear in our code, I thought declare-anywhere was not supported.
@Nicolas: tried that with Visual Studio 2013 Update 2 installation, but can't reproduce the issue
I created a file test.c with following content:
#include<stdio.h>
int main()
{
printf("Hello Worldn");
if (1)
printf("Hellon");
if (2)
{
printf("World");
}
return 0;
}
Then in Developer Command Prompt:
C:temp>cl test.c && test
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.30501 for x86
test.c
Microsoft (R) Incremental Linker Version 12.00.30501.0
/out:test.exe
test.obj
Hello World
Hello
World
C:temp>
As you can see, it seems to work just fine..
Also, you can submit the issues you discovered at connect.microsoft.com/…/CreateFeedbackForm.aspx
Sorry, this code in test.c does compile with "cl test.c" with no warning (I think @equalsraf must have missed something in his example on github):
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int y, x;
} Point;
struct foo { int a; char b[2]; } structure;
int main(void) {
// implicit cast from void*
Point* p = malloc(sizeof(Point));
// designated initializers
p->x = 10;
if (1)
printf("fails!");
Point x = { .x = -10, .y = 5401 };
system("pause");
return 0;
}
Will there be a non-Unicode (Multi-Byte) version of MFC available for Visual Studio "14"? One isn't included in this CTP, and our 10+-year-old project, which has been continuously maintained and developed, relies upon it.
I don't think that it was the refactoring of *sprintf() to avoid FILE that improved its performance 8x – I think it was the fact that Microsoft removed the DecodePointer() calls from *sprintf(). DecodePointer() is an NT kernel call (NtQueryInformationProcess), which will always ruin your day when going for performance. | https://blogs.msdn.microsoft.com/vcblog/2014/06/10/the-great-c-runtime-crt-refactoring/ | CC-MAIN-2016-30 | refinedweb | 6,264 | 62.78 |
What The Heck Is Business Logic Anyway?
For the last year, I've been trying hard to become a better programmer. This journey has involved both writing a ton of code as well as constantly evaluating and re-evaluating the way I think about software application architecture. Of course, I can only do so much on my own; which is why I turn - daily - to the blogosphere to see what people are saying about software development. From everything that I've read / watched so far, the consistent message seems to be:
Put your "business logic" in your domain model and your "application logic" in your application layer. Further breaking down the domain model, most things should live in your domain entities; and, whatever doesn't make sense in a single entity can (and only if necessary) be moved into a domain service.
This sounds really good, and makes for fancy diagrams; but, the problem that I keep running into is that nobody seems to be good as actually defining what in the heck "business logic" is; and, more importantly, how it's different from "application logic".
Imagine, if you will, that I am building a Forum / Discussion site that has discussion threads, users, and moderators. Now, let's say that I have a feature that allows a discussion thread to be renamed. In order to carry out this action, I have to take a number of steps:
If the user (performing the rename) is a Moderator:
- Make sure the user is logged-in.
- Make sure the user is a moderator.
- Make sure the name isn't empty.
- Make sure the name length abides by the rules of the persistence engine (ie. DB column).
- Make sure the name it's blacklisted.
- Rename the discussion thread.
- Persist the change.
- Email the owner (ie. user who created the thread), notifying them of the change.
If the user (performing the rename) is the thread owner:
- Make sure the user is logged-in.
- Make sure the user is the one who started the thread.
- Make sure there are no existing responses within the thread by other users.
- Make sure the thread is not more than 3 days old.
- Make sure the name isn't empty.
- Make sure the name length abides by the rules of the persistence engine (ie. DB column).
- Make sure the name it's blacklisted.
- Rename the discussion thread.
- Persist the change.
Now, if my "business" were to be building and running a Forum / Discussion site, then all of this could feel like "business logic" - heck, it's my business! However, I am sure that there are people who would look at this list say that there's absolutely no business logic here whatsoever - that this is all purely application logic. And, of course, I'm sure there are people somewhere in the middle.
What makes this conversation even more interesting is when people further define the software application layering by stipulating that the "application layer" should be very "thin", and that the "domain model" layer should be very "thick."
This creates an odd dilema. By using the relative-size definition, it requires the above list of steps to be part of the "business logic." If it were not, it would leave us with an application layer that was far thicker than our domain model layer... which, apparently, it cannot / should not be.
However, if we consider the list to be mostly "business logic", then it means that this list of steps - or, at least, many of them - should reside within a domain entity. This leaves me with the gut feeling that we're creating "God Objects," which do far more than they aught to.
A third option is put some of the steps in the application layer, some of the steps into a "domain service," and then leave little more than a name-setter with length validation in the discussion thread, "domain entity." Of course, if we do this, people will condemn you for creating an "anemic domain model," but give you little-to-no insight as to what you should have done better.
Oh, and if none of this fits the bill, people will simply tell you that your site simply doesn't require a "domain model" at all - that is has no "behavior;" which, is frustrating when you think to yourself, "but my site does a lot of stuff!"
As you can probably tell, this is a topic that frustrates me greatly. I feel completely ignorant; and I feel that my research leads me nowhere. If anything, I'd say that the more I read, think, and experiment, the more I tend to believe that having domain entities is hardly worth-while. It seems like I'd get the same amount of DRY'ness and encapsulation if my "domain model" had little more than domain services (ie. an anemic domain model without the overhead of entities).
I think this is what people call a "Transaction Script" approach? (maybe).
If anyone can give me any clarity on the topic, I would be forever indebted to you and would probably shower you with all kinds of awesome praise.
Reader Comments why I respond here in the first place, besides telling you that I like reading your blog and that the title of this one caught my eye tonight on FBs startpage, next to the phrase that you're posting for the first time in months (I'm a blogger as well and didn't post new blogs for months either, which I miss actually a lot)is that you made me curious about the phrase "business logic".
The first thing I thought (as being a non-programmer) was that it must have had something to do with business-like manners. Meaning short, to-the-point, and profitable. The second thing was, let's see what google say about it. Maybe Dutch google would pop up the answer you're looking for. And pro's probably skip the results google returns which seem to obvious. To be honest, the idea to be showered with all kinds of awesome praises was partly why I did that :)
Business-logic is defined on Wiki and there was a link to Business-rule-management system. Then I was lost already. I have not the slightest bit of hope that you don't already know what's written there. So much for the awesome praises.
However, I do hope that someone will seriously help you to tackle this question and that you won't be frustrated any further by my reply. Frustrations in general are not very helpful to find the answers you're looking for. But hey, that's my topic, as being a psychology student ;)
Best wishes,
Debby
I couldn't agree more. I'm anxiously waiting to see how people weigh in on this topic.
Ben, I found the accepted answer to this SO question to be a concise answer to your question:
My understanding of the answer, from an MVC perspective, is that the "Model" is the layer that contains the business logic. In a perfect world (i.e., never), the model could be plugged into any framework and it would just work because it doesn't care about the way it's being used in the application. In this case, the application logic would be contained in the "Controller" layer of our application. The business logic doesn't need to know how it's being used by the application, and the application logic doesn't need to know what the business logic is doing.
I don't think this necessarily lends itself to a "God Object," unless you would consider the controller itself to be that object. The application layer knows all the rules and how these rules interact (user must be logged in, name cannot be empty), but it doesn't know how to determine if the rules are being broken - it only knows who to ask to find out if they are being broken. On the other hand, the business layer is there to tell you if a rule is being broken, but it doesn't need to know the overarching goal of evaluating that single rule - it just checks if the user is logged in, but it doesn't know that that is one of a dozen rules that has to be run before a post can successfully be renamed.
I feel like I rambled a bit there, so (anyone) please feel free to poke holes in it. Also, I may be 100% wrong in which case I would love to hear any rebuttals. :) structure and no rules (think JSON data store) there would be little to no Business logic.[1]
Sure, there will sometimes be overlap, but the key is to figure out if you're trying to keep the user from doing something dumb/unauthorized, or if you're trying to ensure your data doesn't degenerate into useless entropy.
I also find that Application logic may involve state ("the user must be logged-in and an admin", "this request should be cached") whereas Business logic usually doesn't. (Unless you want to be pedantic and call setters "state mutators", but that's just being obtuse.)
I remember an argument years back in which someone (maybe Hal Helms or Sean Corfield) very smartly asserted that objects (and by extension data) should never be able to exist in an invalid state. The stuff that ensures that is the case is Business logic.
--
1. Yes, a JSON data store still has Business logic in the form of validating that incoming data is correctly-formatted JSON, but you get my point.
Here are what would go through my mind for deciding where to implement the business logic.
Purely manipulating properties of the object itself?
> Implement in a method of the object class.
Front-end dependent?
> Implement in the handler layer of your MVC framework.
Complex task that needs other services to complete?
> Implement in a service where it is easy to hook up to other services through dependency injection. Make sure the sub-tasks are implemented in the appropriate services. Aim for readability over everything. You may also consider inject the service back to the object through a factory if the task makes sense to be exposed as obj.doTaskX(). Once things are working, spend the time to re-factoring until the code is easily readable and the flow of sub-task can be traced clearly.
Thanks for a thought provoking post-- takes me back to early VB days when "n-tier" programming with Microsoft products was all the rage. Funny part is, I don't recall hearing anyone use the phrase "business logic" in the entire time I've done web programming.
If you'd asked me to explain "business logic" back then, I'd have said something like "it's where you capture requirements that are unique to this client/department to keep them separate from the parts that can be reused in other projects." So, for example, all applications have user accounts that require passwords to authenticate-- but the password policies for a valid/strong password will be different from one department to the next, so that's a "business rule" you would capture in your middle tier. This leaves your first tier free for reuse with different "business rules" in other applications.
I could be full of nonsense, of course, but that's my recollection of how it was explained to me.
Ben -- I can definitely understand your frustration! With things like overloaded terms, misused terms, differing experiences, and changing technology, it sure gets confusing out there. Thanks for providing a concrete example for discussion. Here's how I've often seen the division of responsibilities between the application and business layers decided.
Looking at the individual steps that you've identified, we can group the specific lines into these broader categories.
1. Make sure the user is authorized to rename this thread
2. Make sure that the thread is able to be renamed
3. Make sure that the new thread name is valid
4. Change the name
5. Send notifications
This high-level list hopefully conceptually includes everything you've got in your lists above, just with a little less detail. If I were writing an application layer, I'd start by putting these five statements into it. In other words, each of these five steps would be (roughly) a single call to some domain object, or maybe to another service.
Then, the actual implementation of each of these five steps would go into the business layer. That way, the application layer is orchestrating the domain model (i.e., making the calls into it) but not doing the actual work.
From there, you might choose to move small bits of code up into the app layer or down into the domain. For example, it'd probably make sense to have the name validation done as part of the call to thread.rename().
Naturally, you can slice up the code in all sorts of different ways and still get the same functionality. A good design is defined by how well it serves you as the programmer, today and in the future. So if using a domain model isn't a natural fit for the app, I wouldn't force it.
Does that help at all? was. But the way it was explain to me by our senior analyst is that "Business Logic" is the way the Business manages, calculates, or uses data. This "logic" is presented to the Developer {me} in a set of requirements. The Developer {me} takes the requirements and implements them in the application.
So for example for the last year Pepsi has created several metrics for measuring efficiency for all their plants that manufacturer and bottle soda and water.
So the business creates different metrics that measures the rate of the machines, the people on staff, any stoppage of production given specific reasons which helps them determine how efficient that plant is running.
Now as a developer that has not been in the plant, I have no way of knowing what those measures are for calculating efficiency and what I should be looking for. I depend on the Business team (which are business analyst that already track these things in Excel Spreadsheets) to give me that information so I can correctly implement it into the application that I will be updating.
So in my case "Business Logic" are a set of requirements that reflect the current business practices.
My example is different from yours and I imagine others who are in a different line of business. Your business is programming and is where I'm assuming it makes its money from, I work for a company who sells a product and the IT department is just a part of it, but not the main part.
But Like Sean Walsh mention in the comments about MVC which is a framework my company uses. We will implement the business logic in the "Model". Currently I'm doing that through the use of Stored Procedures that generate reports for the user through and desktop application.
Hope that Helps
Cris
"Hope you still working out - I miss Equinox" thing.
Theories fine but doing or having done it is better. You can always rejig it later. specific to an application...
So I believe that the methodology used to get any relevant information with respect to the request from application is "Business logic"
You can find the full article here -
@Debby,
I appreciate you trying :) Thanks!
@Sean,
Thanks for that SO link. I actually have read that articles like 2-3 times in the last few weeks. Inevitably it comes up on Google searches when looking at Application/Business logic.
You bring up another point of confusion that I have from reading all the articles / blogs / tutorials, and that is "How much to do I put in the Controller layer?"
It seems that everything I read says that the Controller should do *almost* nothing more than taking requests and handing those requests off to the "core" application. Currently, I do handle some of the security of the application in the Controller workflow - namely, is user XYZ logged-in or not.
Beyond that, however, I have been (as of lately) deferring more localized permissions (ie. can edit? can delete?) to the service / model layer. The seemingly-nice thing about this is that I can use the same, simple application API when a user is accessing the site through two different access points (such as website vs. RESTful API). It's nice to not have to duplicate the access logic in two different controllers.... though, clearly both "applications" (in the web server sense) have to handle their own authentication approaches (ex. cookies vs Basic Auth vs. oAuth).
@Rick,
One thing that you said really connected with some of the thoughts I've been mulling over:
" If your system was never touched by users (such as an automated system, like an ETL process) there would be little or no Application logic."
The other day, I started to think about Scheduled Tasks in ColdFusion, and I had a moment of clarity - with a scheduled task, there is no user! If there is no user, I can't use a pathway into the domain model that requires user-authentication and permissions.
Granted, my access point for the scheduled task (an HTTP entry point) will have to have some security, like Basic Authentication of HTTPS; but, after that, the request has been "fully authenticated." By fact of it's *my* code, it's already authorized to do whatever my code tells it to do (except for, as you say, violating data rules).
This access-duality was what really got my machinery firing. If an authenticated user can call method XYZ(); and, a scheduled task can call method XYZ(); THEN, there better be no user-based permissions checking encapsulated within method XYZ(). As such, one can only conclude that user-based permissions must be executed in a higher layer, prior to the invocation of method XYZ().
As far as objects and valid state, I know I've heard Hal Helms talk about that:
@Henry,
I've become a big fan of Dependency Injection (DI). In my recent project, we've been using Sean Corfield's DI/1.
When you say, "Implement in the handler layer of your MVC framework," what do you mean by "handler layer"? Do you mean the Controller of the MVC paradigm? Or do you mean the next layer that the Controller talks to?
@Andrew,
It's funny that you talk about code reuse across applications. I think this is one of those things that's incredibly hard [for me] to think about. Since the extent of my cross-application re-use has been, "I like the way I did that in the other app, let me copy-paste the objects into this project," it's hard for me to think about actually sharing components in a meaningful way.
While I do "borrow" from other apps, all of the applications that I have built in the last 10 years exist as islands unto themselves. The don't share libraries with other applications; and when I build them, I don't have the foresight to create components intended for cross-app reuse.
Maybe if I started to perform more "reuse analysis," it would actually help me figure out where things should be put?
@Dave,
What you just said is so on-target with so many of the thoughts that I've been having. If I can just add one more thing to it, I'd say "transaction management" would be the thing that ties all of that together:
This way, going back to what I was saying to @Rick, if I had a scheduled task that had to so the same operation, I could simply use the following steps:
Clearly, with a scheduled task, the authentication cannot be used (since there is no user).
@Cris,
Admittedly, the software that I build very rarely has highly complex calculations. Most of what I deal with involves permissions, data entry, and data aggregation (and maybe some scheduled tasks to clean up old data / expired data). Maybe this is part of why the journey has been difficult - the underyling code is not terribly complex, so it doesn't have an overwhelming "smell" as to where it should be.
I think I'm getting closer though - these conversations are really helping.
@Cris,
On a workout-tangent, I haven't worked out in MONTHS :( This current project has dominated every aspect of my life (unfortunately) and I cannot express in words how excited I am to get my life back on track (soon).
@Adam,
I guess, what I know now is that the my approaches in the past have not been the easiest things to maintain. This is why I am itching to improve the way I architect my software.
@Madhu,
That's really funny that Doug has an articles (5 years ago) with almost the same exact title :) I know Doug - he's a very bright guy.
Welcome back, @Ben!
To avoid confounding the topic with software engineering jargon: Business logic constitutes the rules the business wants the software to obey. If you're a contractor/employee, the business is your customer/employer. If you're the boss who commissioned the software to be written, the business is you; you say what the business rules are.
Those who work on the software define application logic as a way to instantiate the business rules. But software environments change and it's possible to define an instance of the business rules for HTML using one kind of application logic, and a completely different instance for XML / web services using completely different application logic.
Like it or not, our industry is subject to trends and fashion. You get something working perfectly, so you want to just let it be. If it ain't broke, don't fix it. But then along comes some new UI, or some new platform, and even though there's nothing wrong with it, you have to rearchitect the whole damn thing to be cool and keep your customers.
Yet all instances have to obey the same business rules.
I wrote and maintain a 15 year old search engine that has really kept up with the times: It allows you to view results tabularly, as a detail report, as a summary report, as csv, as another spreadsheet import format different from csv, for desktop browsers, for mobile devices, as web services, etc. I haven't been asked to generate charts and graphs yet, but you know from some SVG/Canvas code I showed you once (for a different search engine) that that's possible too.
Yet all of these different instantiations of the same search obey the same business rules (sorry that some have to be cryptic):
(1) We can't let searchers retrieve ridiculously large result sets and slow the servers down for everybody else. So insufficient search criteria has to be regarded as an error.
(2) Privacy-protected data is never divulged without https, login and sufficient privilege.
(3) Certain kinds of data are not retrieved unless certain search criteria are entered.
(4) Consistent search behavior. Specifically, adding a new category of search criteria (e.g.: state code) narrows a search, but entering multiple values for that category (e.g.: NY, NJ, CT, MA) broadens it.
All of those business rules derived from what my customer wanted the search engine to be. All instantiations (faces, views) obey those business rules. But only web views provide accessibility enhancements for blind users with screen reading browsers, which implies structuring HTML, JS and CSS in a particular way. That's application logic.
In the long run, to achieve this kind of flexibility, you have to segregate business rules from application rules. Business rules reside nearer to the data. Application rules reside nearer to the user, or the platform/middleware through which you talk to the user.
One last observation and I'll leave you to your holiday shopping:
Stored procedures are a good place for business rules, if that option is available. If all developers have to funnel their updates through stored procedures, the rules will be consistently enforced across all applications. Of course, you have to write the procedures intelligently to avoid inefficiencies, deadlocks, etc, but stored procedures are pretty darned close to the data. If a rule doesn't seem like it belongs in the procedure, if it seems to specific to user interface, it's probably an application rule.
... er, I meant, TOO specific to user interface. Sheesh.
Don'tcha just hate it when you write something long and thoughtful, but your proofreading breaks down in the very last sentence?
Not enough coffee, apparently.
@WebManWalking,
Thinking of business logic as the stuff your client asks for in order to build the software, is typically how I have been thinking about it. But, I think the problem with that is that [from my point of view] is that it doesn't allow the "application layer" to orchestrate business logic.
If the requirements of the software say that for some actions, steps 1, 2, 3, and 4 have to take place, then it seems that in order to "enforce" that all of that happens, all of that orchestration has to be inside the "domain model", not inside the application layer (since it's business logic).
But, I think using the application layer as a place to orchestrate business logic has value (even if it requires a workflow to be enforced outside of the domain model).
... too hungry to think more deeply at this moment :)
Redundancy's okay.
In one of my banking applications, fixed interest rate loans require initial interest rate but not spread over prime. Variable interest loans require spread over prime, but not initial interest rate.
In the web pages, users have come to expect immediate feedback. Clicking the Fixed radio button results in initial interest rate being marked mandatory and spread over prime being marked optional, in our case, via JS that adds or removes classes. Clicking Variable results in the opposite.
Yeah, that's in the application logic. But that's okay. In fact, accessibility for cognitively disabled users pretty much requires that kind of implications-revealing feedback.
In a web service, you wouldn't have that sort of bleed-over of business logic into application logic. That's okay too.
It's not like rigorously normalizing a database, where you're trying to make sure each data element appears in only one place on the database. A rule doesn't have to reside only in business logic or application logic, never both.
The important thing is, in the absence of upfront application logic, business logic catches and prevents violations of business rules.
My $0.02.
Pg53 @ Pro Spring MVC w Web Flow ...
Application Layering ...
"Layers should be thought of as conceptual boundaries"
Presentation =
This is most likely to be a web-based solution. The presentation layer should be as thin as
possible. It should also be possible to provide alternative presentation layers like a web
front-end or maybe even a web service façade. This should all operate on a well-designed
service layer.
Service =
The entry point to the actual system containing the business logic. It provides a coarse grained
interface that enables use of the system. This is also the layer that should be the
transactional boundary of the system (and probably security, too). This layer shouldn't
know anything (or as little as possible) about persistence or the view technology used.
Data Access =
An interface-based layer that provides access to the underlying data access technology,
but without exposing it to the upper layers. This layer abstracts the actual persistence
framework (e.g., JDBC, JDO, or JPA). Note that this layer should not contain business
logic.
"Communication between the layers is from top to bottom. The service layer can access the data
access layer, but the data access layer cannot access the service layer. If you see these kinds of circular
dependencies creep into your application, take a few steps back and reconsider your design. Circular
dependencies (or bottom to top dependencies) are almost always a sign of bad design and lead to
increased complexity and a harder-to-maintain application."
@Edward,
I've definitely been thinking of the service layer as my conceptual boundary to my core application. I'm exactly pleased with some of the choices I've made (hence this post), but I have been using a consistent approach with passing the authenticated user ID through to the service layer on all the calls. For example:
My controller layer handles the authentication (using calls to the security layer to check for username / password or whatever); then, subsequent calls back into the service layer will always pass the auth user ID as the first argument.
That said, I would like to extract all of that stuff UP into the "application layer", which I currently don't really have. My service layer is a bit of a hodgepodge of responsibilities... something to be refactored soon.
@Ben, handler layer == controller layer in Coldbox.
@Ben, handler layer == controller layer in Coldbox.
@Ben, Henry ...
I might suggest taking a look at implementing the Front-Controller MVC design pattern. ColdBox has a mature and feature rich architecture that supports the delegation features your looking for in CF ...
I like webmanwalking's notion that business logic implements business rules, and business rules are basically requirements. At implementation time you then get application logic and domain logic, and the business rules could be implemented in either or both depending on the degree of generality desired.
To me domain logic is all about generality. What *is* a thread? What are it's properties, and what can it do? Come up with a definition that you're happy to run with across all the applications of this kind that you might want to write, and that's domain stuff. This is why really rich domain models are rare - because most domains have very few truly general rules - and complicated - because a lot of the rules have be parameterized to make them general.
So if all discussion threads in the universe of applications you might want to write have to be less than three days old to be renamed - that's domain logic. If only this particular application cares about thread age and renaming - that's application logic. If thread age has a bearing on renaming in all applications, but different applications might allow different ages - that's a mix. The "care about thread age when renaming" is domain logic, and "make the threshold three days" is application logic.
@Ben ... 'Hodgepodge of Responsibilities' ...
You may want to research 'ISP' or 'Interface Segregation Principles' - The 'I' in a S.O.L.I.D. application design ...
@Edward,
On the "framework" side of things, I feel mostly comfortable. I have not, traditionally, been a "framework" person; and, getting requests to responses has been a matter of converting URLs to actions, to content, to rendering. It's not always pretty, but that part of the web-development world has been one of the kinder aspects. Though, I have stressed over rendering complex layouts and how that's done properly; but, I get something working.
The part of this whole process that comes back to bite me is often the gathering of data for display - the point where the controller needs to prepare the view-model (or what ever you want to call it). That's the part, for me, that gets unwieldy over time.
As far as Bob Martin, I definitely gobble up all the articles and presentations and interviews of his that I can find :)
@Jaime,
I think what makes that mindset so difficult, at least for me, is that I rarely build two applications that are a like. In my job at Epicenter Consulting (~last 4 years), I never built two sites that were similar. Ok, maybe a few e-commerce sites; but other than that, we build line-of-business web-apps for all kinds of different types of businesses.
Now, at InVision, we build a single product.
As such, the thought of using a component in a non-application-specific way seems incredibly foreign. Since I am so heavily influenced by the current project and all of its constraints, it's hard to think about the aspects of it that could exist in other apps. I fear it would leave me with just a set of vanilla data-structures.
@Ben "The part of this whole process that comes back to bite me is often the gathering of data for display "
I feel your pain ... Systems architecture is complex. In my bootstrap description ... model layer 'data-structures' are transitive and dynamic by nature - handling attributes and behaviors responsible for their effective transport is 'The Rub'
I think we can only hope to make good progress in this area ... as perfection is quite illusive ...
Back again ...
Sorry for all the responses ... Got my attention here ... I'd say @Rick and @WMW's view are accurate ...
In this case ... attempting to define both coarse and fine-grained logic and maintaining a separations of concerns is where JPA / Hibernate really shines By designing interfaces that work with data mappers and repositories ... we can define abstract DTO interfaces for both the UI layer and the DA layer without most of the negative issues associated with coupling and design scale.
I'm just getting my feet wet with full-scale application architecture but the benefits of designing model and views through JPA are huge.
@Edward,
Hopefully, I'm getting better at it. My understanding is much better than it was even a few months ago, thanks to the current project (letting me experiment and learn and feel pain).
One of the biggest mental hurdles left is understanding / figuring out how to deal with collections and aggregates. For example, going back to the forum type example, imagine that I had to get a list of discussion threads along with the count of new comments available for the currently authenticated user. In SQL, this is a moderately easy query with GROUP'ing or some sort of intermediary table.
BUT, what happens when I have a number of those kinds of queries required by many, slightly different User Interfaces? How do I build that kind variety, with good performance, on top of a domain model.
I've been reading up on CQRS - Command Query Responsibility Separation. From what I've read, this consists of a different database for reading / writing; however, even with a single database, I definitely see very different needs in an application for reading vs. maintaining data integrity. The question is, how to organize those kinds of queries in the set of components in the application.
... still trying to think that one through.
The Spring Data JPA is probably something you'd get some value from too ...
@Ben ...
I've slapped together a spring data jpa demo app that I modified from ...
Examples are a lot clearer than discussion sometimes ... :-). The controller has to mediate between the two."
Business Logic:
Do new users need to click an activation link to validate their email?
Application Logic:
When you click on an activation link unlock the user and allow logins.
Business Logic 2:
When a user logs in x times incorrectly, lock their account.
Application Logic 2:
Call business logic on failed login. If it returns 'L' then lock the account.
Provide unlocking mechanism.
Business Logic would then be that part of the App which can be customized/overwritten and will (somehow) survive an upgrade.
I often take the approach of business logic typically being objects that are unaware of their surroundings.
Example, I create an object, set some properties for it, and call the doYourThing() method and check for output.
It wouldn't know anything about the UI, or how the data itself is gathered, nor what to do with the data, how to store, etc. It just processes the information according to the business rules requirements.
This way, I can manually test the object however I wished using things like test cases and such to verify the business rules are operating correctly.
Afterwards, I start wrapping/extending the object with application and storage specific code, maybe a layer of validation before the data goes in to the core and as it comes out.
This is all decoupled from the core logic and is theoretically interchangeable.
In coldfusion, I typically do this with a cfc, and then create cfc wrappers that instantiate (or directly call from persistent scope) the object. These wrappers would handle remote webservice calls or ExtJS Direct invocations. They take care of validating the webservice call, validating the incoming xml against schemas before the data makes it to the core, building success and error responses, parsing and creating json responses, etc.
Most often with coldfusion code, I leave DB specific code inside the core as I know what system I'm writing for, otherwise, this is where the ORM stuff would come into play inside the core.
I typically have something like:
/Components/Something/widget.cfc
/Webservices/Something/widget.cfc
The latter processes remote calls, validates against messaging schema, build error response if bad input, calls the former, builds response, validates response against messaging schema, returns response.
A little bit different with my ExtJS Direct stack, but similar idea.
For business logic specific to UI, it can be similar.
Your click button press event wouldn't perform much. I like to have them create pointers to the elements I need to check and pass those in to an object. This way, the dom locations or names can change, but the core business logic doesn't need to.
onChange=doThing();
doThing(){
var in1 = document.getElementById('text1');
var in2 = document.getElementById('text2');
var v = new Validator(in1, in2);
v.validate();
if(!v.success)
{
alert(v.errorMessage);
}
}
@Edward,
At first glance, it looks very interesting. I'll have to carve out some more time to go through it and really try to understand it. One thing that I do have a particular interest in is how you organize files. I see in you Java folder, you are making good use of namespaces. This is something that I don't have very much experience with... especially when using Dependency Injection that seems to be powered by component names (without name spaces).
I really appreciate you putting that together! You rock!
@Marc,
I think my current understanding of Business Logic is a little bit of the opposite - it's the stuff that *wouldn't* need to be changed from application to application? Not saying I'm right - that's just the way I've been leaning lately.
@Jim,
What you're describing sounds a bit like the "Onion Architecture" that I have been reading up on:
It has the "domain core" in the middle; and, then a set of layers that wrap around it. Actually, the Onion Architecture is, in big part, how I finally got to writing this post - the Onion Architecture makes use of "Application Services" and "Domain Services", which sounded good. BUT, I had no idea how to define the type of information that when in each... hence, what the heck is Business Logic :D
I think I'm getting closer.
I tried to codify some more of my thoughts on software application layers and their respective responsibilities:
Hopefully, I'm getting closer to something that makes sense :D
Im not sure if you are still interested, but I hope this
can explain some. A few years back I was trying to become a better programmer too, right around the same time I was asking myself the same kinds of questions.
Cheers
@Sean,
I found your comment to be very concise and has cleared up some confusion on my own projects. Just this morning I asked myself; is my business logic in the correct place, then I asked myself; what is business logic?
According to your comment ive got all the pieces in the places they should be.
My 2 cents.
Application Logic consumable logic. Change aspects, behavior, input, etc.
In a console application, the application logic is the input params and the output response. In a schedule task, it's the same. The trigger that make the application start and the output, both are Application Logic.
Please note, Consumer does NOT have to be a User.
In a webapi, Application Logic refers to request, response, INPUT validation.
Side note: Validation can and happens at multiple levels of an Application. Some at Application Logic and other not!
So now, what is business logic ? Business Logic is the process that happen under the scene, without notifying a consumer, but the application logic and without getting input from the consumer but the application logic.
That's why business logic can have be shared in multiple applications, and applications shared with multiple consumers. business logic cannot be shared by consumers, because are not consumables.
So, WHERE should business logic be ? That's sounds as a good question. and the answer as I see it is very simple: Anywhere that makes sense.
Spa application can have heavy business logic on the client 'layer' while standard web apps have less.
If you want to do heavy business logic on your client side, you can have SQL-like queries in your Javascript. (see breeze.js for example).
In an application like Entity Framework ORM, the lambda expression like .Where() .Select(), etc are all EF application logic. The actual implementation on how that translates that to a query is EF business logic, because the only consumer is the Application Logic while the Application Logic can have many consumers.
Last words:
If a consumer interacts with an application logic, the application logic *may* call the business logic and interpret the response (if any) from the business logic and then the application logic interacts with the consumer again. It doesn't matter if that 'business logic' is a DLL behind 213432 layers, the same in page Javascript or a store procedure in a DB.
TL;DR;
Business Logic is code that has no consumer but Application Logic.
Application Logic is code that has n consumer(s).
Together with my coleages I had this frustration too. A few years ago we were working on a language (XML) that would be able to describe a domain fully and completely to be able to but all business logic into the domain model.
The idea was to generate UI automatically from the domain model and to reduce the code for the controller as much as possible. Martin F"owler's Patterns of Enterprise Architecture" ans Eric Evan's "Domain Driven Design" were our most important inspirations. I also recommend Vaughn Vernon's "Implementing Domain Driven Design" very highly.
Today we are able to do just that. Have a look at and if you have any questions I am happy to share our ideas!
all the best,
Roland
There is no spoon. I think this question could be paralleled with similar ideological dualistic conundrums such as where do I end and you begin? Everything bleeds into everything. I don't think there is a finite line to be drawn in the sand that will be universally agreed upon that separates the two in a quantifiable way. The useful function of programming paradigms is what is most important in my opinion. Adopting it should help you not frustrate you.
In this case for me it is useful to think about the data sets I will be working with and how they tie into the real world as business logic. For instance a fulfillment center needs to track orders among many things.
There are many operations on orders but when an order changes there are finite things that occur if its line items change in quantity then the corresponding inventory of its product will decrease. There is no application in the fulfillment industry that would say otherwise.
The result of this business logic is useful to different people in different ways. A customer service representative will be most interested in being able to quickly access order details to answer a clients questions. The owner will want to see profit and loss based on inventory and sales. So that to me is application logic. People can say I am wrong but if it helps me code better than that was the purpose of the contemplation of the ideology from the get go. But is someone had a more useful understanding then it would be worth looking back into it.
My main point is how useful is your definition not how authoritative is its speaker in their tone. That and there is no spoon or right answer. I very much appreciate the conversation your humble and honest tone brought. It is especially impressive coming from a CTO. | https://www.bennadel.com/blog/2436-what-the-heck-is-business-logic-anyway.htm | CC-MAIN-2022-27 | refinedweb | 7,516 | 61.87 |
i want to write a a program that will accept student name and grades and output it.use an array data structure in the implementation this program and implement the following
write method that will traverses the array and allow the user to perform the following processes
a) search for a particular student and his or her marks
b)find the average of all the student in the class
c)find all student with a mark below 50 and output them.
i started off with this codes in Java .But the thing is if i can do it in java i can do it in C and C++
import java.util.Scanner;
//import java.lang.String;
public class Main {
public static int n;
//public static String names;
//private static String[] nameS;
//private static String[] nameS;
/**
* @param args the command line arguments
*/
public static void main(String[] args/*,String[] nameS*/) {
Scanner in=new Scanner(System.in);
int Da=0;
int num []=new int[n];
//int x=0;
System.out.printf("%s\n","Enter the Number of student taking This Couse");
n=in.nextInt();
String name[]=new String [n];
System.out.printf("%s %s \n", "index","value");
for (; Da < name.length; Da++ )/*Da 4 Display array*/ {
System.out.printf( "%5d%8d\n", Da, name[Da] );
}
System.out.println("Enter the names of the student");
String names;
names=in.nextLine();
name[n] = new String(names);
for (; Da < name.length; Da++ ){
System.out.printf( "%5d%8d\n", Da, name[Da] );
}
}
}
i can not input the names into the array( name) i created
pls help me | https://www.daniweb.com/programming/software-development/threads/329217/how-to-input-into-array-from-keyboard | CC-MAIN-2018-43 | refinedweb | 261 | 66.33 |
Fast Gradient Boosting with CatBoost
In this piece, we’ll take a closer look at a gradient boosting library called CatBoost.
In gradient boosting, predictions are made from an ensemble of weak learners. Unlike a random forest that creates a decision tree for each sample, in gradient boosting, trees are created one after the other. Previous trees in the model are not altered. Results from the previous tree are used to improve the next one. In this piece, we’ll take a closer look at a gradient boosting library called CatBoost.
CatBoost is a depth-wise gradient boosting library developed by Yandex. It uses oblivious decision trees to grow a balanced tree. The same features are used to make left and right splits for each level of the tree.
As compared to classic trees, the oblivious trees are more efficient to implement on CPU and are simple to fit.
Dealing with Categorical Features
The common ways of handling categorical in machine learning are one-hot encoding and label encoding. CatBoost allows you to use categorical features without the need to pre-process them.
When using CatBoost, we shouldn’t use one-hot encoding, as this will affect the training speed, as well as the quality of predictions. Instead, we simply specify the categorical features using the
cat_features parameter.
Advantages of using CatBoost
Here are a few reasons to consider using CatBoost:
- CatBoost allows for training of data on several GPUs.
- It provides great results with default parameters, hence reducing the time needed for parameter tuning.
- Offers improved accuracy due to reduced overfitting.
- Use of CatBoost’s model applier for fast prediction.
- Trained CatBoost models can be exported to Core ML for on-device inference (iOS).
- Can handle missing values internally.
- Can be used for regression and classification problems.
Training Parameters
Let’s look at the common parameters in CatBoost:
loss_functionalias as
objective— Metric used for training. These are regression metrics such as root mean squared error for regression and logloss for classification.
eval_metric— Metric used for detecting overfitting.
iterations— The maximum number of trees to be built, defaults to 1000. It aliases are
num_boost_round,
n_estimators, and
num_trees.
learning_ratealias
eta— The learning rate that determines how fast or slow the model will learn. The default is usually 0.03.
random_seedalias
random_state— The random seed used for training.
l2_leaf_regaliasis the default. In
SymmetricTree, the tree is built level-by-level until the depth is attained. In every step, leaves from the previous tree are split with the same condition. When
Depthwisealias
min_child_samples— This is the minimum number of training samples in a leaf. This parameter is only used with the
Lossguideand
Depthwisegrowing policies.
max_leavesalias
num_leaves— This parameter is used only with the
Lossguidepolicy and determines the number of leaves in the tree.
ignored_features— Indicates the features that should be ignored in the training process.
nan_mode— The method for dealing with missing values. The options are
Forbidden,
Min, and
Max. The default is
Min. When
Forbiddeniterations are used. Regression problems using quantile or MAE loss use one
Exactiteration. Multi classification uses one
Netwoniteration.
leaf_estimation_backtracking— The type of backtracking to be used during gradient descent. The default is
AnyImprovement.
AnyImprovementdecreases the descent step, up to where the loss function value is smaller than it was in the last iteration.
Armijoreduces the descent step until the Armijo condition is met.
boosting_type— The boosting scheme. It can be
plainfor the classic gradient boosting scheme, or
ordered, which offers better quality on smaller datasets.
score_function— The score type used to select the next split during tree construction.
Cosineis the default option. The other available options are
L2,
NewtonL2, and
NewtonCosine.
early_stopping_rounds— When
True, sets the overfitting detector type to
Iter.
Regression Example
CatBoost uses the scikit-learn standard in its implementation. Let’s see how we can use it for regression.
The first step — as always — is to import the regressor and instantiate it.
from catboost import CatBoostRegressor cat = CatBoostRegressor()
When fitting the model, CatBoost also enables use to visualize it by setting
plot=true:
cat.fit(X_train,y_train,verbose=False, plot=True)
It also allows you to perform cross-validation and visualize the process:
Similarly, you can also perform grid search and visualize it:
We can also use CatBoost to plot a tree. Here’s the plot is for the first tree. As you can see from the tree, the leaves on every level are being split on the same condition—e.g 297, value >0.5.
cat.plot_tree(tree_idx=0)
CatBoost also gives us a dictionary with all the model parameters. We can print them by iterating through the dictionary.
for key,value in cat.get_all_params().items(): print(‘{}, {}’.format(key,value))
Final Thoughts
In this piece, we’ve explored the benefits and limitations of CatBoost, along with its primary training parameters. Then, we worked through a simple regression implementation with scikit-learn. Hopefully this gives you enough information on the library so that you can explore it further.
CatBoost - state-of-the-art open-source gradient boosting library with categorical features support
CatBoost is an algorithm for gradient boosting on decision trees. It is developed by Yandex researchers and engineers...
The Data Science Bootcamp in Python
Learn Python for Data Science,NumPy,Pandas,Matplotlib,Seaborn,Scikit-learn, Dask,LightGBM,XGBoost,CatBoost and much...
Bio: Derrick Mwiti is a data analyst, a writer, and a mentor. He is driven by delivering great results in every task, and is a mentor at Lapid Leaders Africa.
Original. Reposted with permission.
Related:
- LightGBM: A Highly-Efficient Gradient Boosting Decision Tree
- Understanding Gradient Boosting Machines
- Mastering Fast Gradient Boosting on Google Colaboratory with free GPU | https://www.kdnuggets.com/2020/10/fast-gradient-boosting-catboost.html | CC-MAIN-2021-04 | refinedweb | 935 | 50.73 |
Is there a way to implement an Indexer on a class member and not the class itself?
This is strictly for code readability because I would like the idea of having an Indexer property of a variable within a class.
An Example would be
Then lets say I instantiate a MyClass objectThen lets say I instantiate a MyClass objectCode:public class MyClass { private List<PlayerClass> player = new List<PlayerClass>(); public PlayerClass Player[int index] { get { return player[index]; } set { player.Add(value); } } }
MyClass blah = new MyClass();
I would be able to access the player list like so...
blah.Player[1]
without making the player list public. I would like to keep this member private so that I can use the properties to validate the input (even though that isn't shown in this example). I know I can do this with a method and keep my list private, I was just hoping i could use the indexer notation []. Any ideas? | http://cboard.cprogramming.com/csharp-programming/124701-indexer-question.html | CC-MAIN-2014-35 | refinedweb | 160 | 58.21 |
This section is the place to post your general code offerings -- everything from one-liners to full-blown frameworks and apps.
Greetings
Update : This can be used to make interprocess communication transparent : with the appropriate setup it should allow communication between process that might be on different machines as if they were on the samenext thing up, change the way the summoner works so he can return file handles to his callers, also make it so he can have any number of callers and treat their requests one after anotherTo do that I was thinking about having a "call me back" file handle inside the parameter hash passed to him so he can send a reply with the needed file handle
After much nagging, harassing this community with questions regarding IPC I finally have some code to show you.
Even better, This time it's code that works!
Please keep in mind that I have not yet gotten rid of my eye-gouging coding style (I made some effort on that one to provide with a coherent synopsis, description and a better documentation
so, here is the archidaemon, sitting upon his throne of undelivered messages, I give you Messaging!
now the class he uses to summon his little slaves, the messenger daemons (each summoned has his TrueName-ie his pid) in the archi daemon Great Book Of Names (ie his %children hash)so he can be sent back whence he came if need arises
And now, ladies and gentlemen, have a look at this beast,
this entity summoned from the deepest pits of madness as it goes about jumping through those poorly cobbled together testing hoops and does (hopefully) not crash and burn with an otherwordly Croak of despair!*Cracks his whip
Those slaves will happily pass around simple text messages, but what about more complicated serialized data with newline characters? I am still looking for advice on how to handle those cases, thank you for reading this far :)
Greetings,
I'm not sure if this is a real cool use, but with this class you can specify any regex for a standard parser tool as well as any callback in string form (pretty useful if you want to do all of that in a configuration file under version management) I have some serious doubts about the way I used eval in this code so I would welcome feedback on how to do it better. I looked over the forum for ways to handle the storing of substitution regex and back references but what I found I felt I did not understand enough to re use properly so if you feel like engraving it into my forehead so I can get it feel free to do so (I'm refering to this node and that one
now here is the code :
And, as usual, the tests, iirc its almost 100% cover
The Following code provides a class to create Markov chain based automata which role is to tell you, after reading a dictionary, whether words you give them are likely to be part of the language they studied. I wrote it so I can use it to comb through dns queries logs to find anything that looks like an algorithmicaly generated domain name. have fun :D
And here is the test file : 100% testcover :)
This program creates a recursive diff between two directory trees. The directory trees can be local or reachable by ssh. The diff lists added and removed files and for changed files, it lists the differences in diff style. This makes it convenient to review the differences between two machines that should be identical, or to find the steps that are needed to bring one directory tree to another.
After a hint by salva that Net::SSH2 comes included with Strawberry Perl, I was motivated to rip out some system-specific
ties to plink.exe and post this. Unfortunately, Net::SSH::Any doesn't seem to have a way to talk to the ssh agent for quick authentification, so this relies on Net::SSH2 instead of Net::SSH::Any.
#!perl -w
use strict;
use Algorithm::Diff;
use Getopt::Long;
use File::Find;
use File::stat;
use Net::SSH2;
=head1 NAME
diff-servers.pl
=head1 ABSTRACT
Generate a diff between two directory trees. The directory trees must
+be local or reachable
via ssh. Only the ssh2 protocol is supported.
=head1 SYNOPSIS
perl -w diff-servers.pl corion@production:/opt/mychat corion@staging
+:/tmp/deploy-0.025 --ignore .bak --ignore .gpg --ignore .pgp --ignore
+ random_seed
Quick diff, showing only added/missing files without comparing their c
+ontent
perl -w diff-servers.pl c:\mychat\old-versions\0.025 corion@staging:
+/tmp/deploy-0.025 -q
=head1 OPTIONS
=over 4
=item B<--ignore>
Regexp of directory entries to ignore
=item B<--no-mode>
Don't compare the file mode.
=item B<--no-owner>
Don't compare the file owner.
=item B<--quick>
Don't compare file contents
=item B<--verbose>
Be somewhat more verbose
=back
=head1 PREREQUISITES
Currently, the script expects C<find> and C<perl> to be available on t
+he remote
side. The dependency on C<find> could be eliminated by implementing th
+e functionality
in Perl. The dependency on C<perl> on the remote side could be elimina
+ted by using
the SFTP protocol for retrieving the directory tree, at an added compl
+exity.
=cut
GetOptions(
'verbose|v' => \my $verbose,
'ignore|i:s' => \my @ignore,
'no-owner|o' => \my $ignore_owner,
'no-mode|m' => \my $ignore_mode,
'quick|q' => \my $skip_contents,
);
use vars qw(%connections);
sub run_remote {
my( $server, $command )= @_;
my $user;
if( $server =~ /(.*)\@(.*)/ ) {
$user = $1;
$server = $2;
};
if( ! $connections{ $server }) {
my $ssh2 = Net::SSH2->new();
$ssh2->connect($server) or die "Couldn't connect to '$server':
+ $!";
if ($ssh2->auth( username => $user, interact => 1 )) {
$connections{ $server } = $ssh2;
} else {
die "No auth to $server.";
};
};
my $fh = $connections{ $server }->channel;
warn "[$command]" if $verbose;
$fh->exec($command) or die;
my @lines = map {s/\s+$//; $_ } <$fh>;
#warn "$server:[$_]" for @lines;
return @lines
}
sub get_local {
my( $file )= @_;
open my $fh, '<', $file
or warn "Couldn't read '$file': $!";
binmode $fh;
my @lines = map {s/\s+$//; $_ } <$fh>;
return @lines
}
sub split_serverpath {
my( $serverpath ) = @_;
if( $serverpath =~ /((?:\w+\@)[\w.]+):(.*)/ ) {
return ("$1","$2");
} else {
# Must be local
return (undef, $serverpath);
}
};
use Data::Dumper;
sub filelist {
my( $serverpath ) = @_;
my( $host, $dir ) = split_serverpath( $serverpath );
if( $host ) {
# Outputs a line per file
# mode user group type filename
my $uid_gid_file = q!perl -Mstrict -MFile::stat -nle 'next if
+/^\s*$/;my $s=stat($_);my($p,$u,$g,$t)=(0,q(-),q(-),q(f)); if($s and
+not -l) {$p=$s->mode;$u=(getpwuid($s->uid))[0];$g=(getgrgid($s->gid))
+[0] } else { $t=q(l)}; print sprintf qq(%08o %s %s %s %s), $p, $u,$g,
+$t,$_'!;
# Read all directory entries
my @remote_entries = map { my( $mode,$u,$g,$t,$name ) = split
+/ +/, $_, 6 ;
$name =~ s!^\Q$dir!!;
{ user => $u, group => $g, type =>
+$t, name => $name, mode => $mode };
} run_remote( $host, qq{find '$dir' -
+type f -o -type l| $uid_gid_file } );
return @remote_entries;
} else{
my @files;
find({ wanted => sub {
return if -d $_;
my $s = stat($_)
or warn "Couldn't stat [$_]: $!", return;
my $name = $_;
my $u='-';
my $g='-';
my $t='f';
my $mode = $s->mode;
$name =~ s!^\Q$dir!!;
push @files, { user => $u, group => $g, type => $t, name =
+> $name, mode => $mode };
}, no_chdir => 1 },
$dir );
#warn "local: $_" for @files;
return @files;
};
}
sub wanted_file {
my( $fileinfo )= @_;
my $file = $fileinfo->{name};
if( my @why = grep { $file =~ /\Q$_/ } @ignore ) {
#warn "Ignoring $file (@why)";
} else {
#warn "Allowing [$file] ...";
}
! grep { $file =~ /\Q$_/ } @ignore;
}
sub diff {
my( $name, $server1, $server2 )= @_;
my($host1, $path1) = split_serverpath( $server1 );
my($host2, $path2) = split_serverpath( $server2 );
my @left = $host1 ? run_remote( $host1, qq{cat '$path1$name'} ) :
+ get_local( "$server1$name" );
my @right = $host2 ? run_remote( $host2, qq{cat '$path2$name'} ) :
+ get_local( "$server2$name" );
my $diff = Algorithm::Diff->new( \@left, \@right );
$diff->Base( 1 ); # Return line numbers, not indices
my $has_diff;
while( $diff->Next() ) {
next if $diff->Same();
if( ! $has_diff ) {
$has_diff = 1;
print "$name\n";
}; "< $_\n" for $diff->Items(1);
print $sep;
print "> $_\n" for $diff->Items(2);
}
$has_diff
};
my( $server1, $server2 )= @ARGV;
#warn "Old: $server1";
#warn "New: $server2";
my %left_info = map { $_->{name} => $_ } grep { wanted_file($_) } file
+list( $server1 );
my %right_info = map { $_->{name} => $_ } grep { wanted_file($_) } fil
+elist( $server2 );
my @left_names = sort keys %left_info;
my @right_names = sort keys %right_info;
my $filediff = Algorithm::Diff->new( \@left_names, \@right_names );
my @samelist;
$filediff->Base( 1 ); # Return line numbers, not indices
while( $filediff->Next() ) {
if( $filediff->Same() ) {
# entry exists in both trees
push @samelist, $filediff->Items(1);
} else {
# Entries only on tree 2, but no symlink
my @new_items = grep { ! $right_info{ $_ }->{type} ne 'l' } $f
+ilediff->Items(2);
print "new: $_\n" for @new_items;
# Entries only on tree 1, but no symlink
my @old_items = grep { ! $left_info{ $_ }->{type} ne 'l' } $fi
+lediff->Items(1);
print "del: $_\n" for @old_items;
};
}
for my $same (@samelist) {
my $linfo = $left_info{ $same };
my $rinfo = $right_info{ $same };
#warn "File: $same";
#warn Dumper $linfo;
#warn Dumper $rinfo;
if( $linfo->{type} ne $rinfo->{type} ) {
print "$same: Link vs. file: $linfo->{type} => $rinfo->{type}\
+n";
};
next if $linfo->{type} eq 'l' or $rinfo->{type} eq 'l';
if( ! $ignore_owner ) {
if( $left_info{ $same }->{user} ne $right_info{ $same }->{
+user}
or $left_info{ $same }->{group} ne $right_info{ $same }->{
+group}
) {
print "$same: Ownership different: $left_info{ $same }->{use
+r}:$left_info{$same}->{group} ne $right_info{ $same }->{user}:$right_
+info{$same}->{group}\n";
};
};
if( ! $ignore_mode ) {
if( $left_info{ $same }->{mode} ne $right_info{ $same }->{m
+ode}
) {
print "$same: Mode different: $left_info{ $same }->{mode} $r
+ight_info{$same}->{mode}\n";
};
};
if( ! $skip_contents ) {
diff( $same, $server1, $server2 );
};
};
[download]
Monks and monkettes! I recently found myself wondering, what's the longest words in the dictionary (/usr/share/dict, anyway)?
This is easily found out, but it's natural to be interested not just in the longest word but (say) the top ten. And when your dictionary contains (say) eight words of length fifteen and six words of length fourteen, it's also natural to not want to arbitrarily select two of the latter, but list them all.
I quickly decided I needed a type of list that would have a concept of the fitness of an item (not necessarily the length of a word), and try not to exceed a maximum size if possible (while retaining some flexibility). My CPAN search-fu is non-existent, but since it sounded like fun, I just rolled my own. Here's the first stab at what is right now called List::LimitedSize::Fitness (if anyone's got a better idea for a name, please let me know):
This features both "flexible" and "strict" policies. With the former, fitness classes are guaranteed to never lose items, but the list as a whole might grow beyond the specified maximum size. With the latter, the list is guaranteed to never grow beyond the specified maximum size, but fitness classes might lose items. (Obviously you cannot have it both ways, not in general.)
Here's an example of the whole thing in action:
This might output (depending on your dictionary):
$ perl longestwords.pl wordsEn.txt
..........
length 21
antienvironmentalists
antiinstitutionalists
counterclassification
electroencephalograms
electroencephalograph
electrotheraputically
gastroenterologically
internationalizations
mechanotheraputically
microminiaturizations
microradiographically
length 22
counterclassifications
counterrevolutionaries
electroencephalographs
electroencephalography
length 23
disestablismentarianism
electroencephalographic
length 25
antidisestablishmentarian
length 28
antidisestablishmentarianism
19 words total (10 requested).
$
[download]
If you've got any thoughts, tips, comments, rotten tomatoes etc., send them my way! (...actually, forget about the rotten tomatoes.)
Also, does anyone think this module would be useful to have on CPAN, in principle if not in its current state?
The | http://www.perlmonks.org/index.pl?showspoiler=1029871-1;node_id=1044 | CC-MAIN-2015-35 | refinedweb | 1,927 | 53.34 |
__author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Spring 2019"
Thus far, all of the information in our word vectors has come solely from co-occurrences patterns in text. This information is often very easy to obtain – though one does need a lot of text – and it is striking how rich the resulting representations can be.
Nonetheless, it seems clear that there is important information that we will miss this way – relationships that just aren't encoded at all in co-occurrences or that get distorted by such patterns.
For example, it is probably straightforward to learn representations that will support the inference that all puppies are dogs (puppy entails dog), but it might be difficult to learn that dog entails mammal because of the unusual way that very broad taxonomic terms like mammal are used in text.
The question then arises: how can we bring structured information – labels – into our representations? If we can do that, then we might get the best of both worlds: the ease of using co-occurrence data and the refinement that comes from using labeled data.
In this notebook, we look at one powerful method for doing this: the retrofitting model of Faruqui et al. 2016. In this model, one learns (or just downloads) distributed representations for nodes in a knowledge graph and then updates those representations to bring connected nodes closer to each other.
This is an incredibly fertile idea; the final section of the notebook reviews some recent extensions, and new ones are likely appearing all the time.
%matplotlib inline from collections import defaultdict from nltk.corpus import wordnet as wn import numpy as np import os import pandas as pd import retrofitting from retrofitting import Retrofitter import utils
data_home = 'data'
For an an existing VSM $\widehat{Q}$ of dimension $m \times n$, and a set of edges $E$ (pairs of indices into rows in $\widehat{Q}$), the retrofitting objective is to obtain a new VSM $Q$ (also dimension $m \times n$) according to the following objective:$$\sum_{i=1}^{m} \left[ \alpha_{i}\|q_{i} - \widehat{q}_{i}\|_{2}^{2} + \sum_{j : (i,j) \in E}\beta_{ij}\|q_{i} - q_{j}\|_{2}^{2} \right]$$
The left term encodes a pressure to stay like the original vector. The right term encodes a pressure to be more like one's neighbors. In minimizing this objective, we should be able to strike a balance between old and new, VSM and graph.
Definitions:
$\|u - v\|_{2}^{2}$ gives the squared euclidean distance from $u$ to $v$.
$\alpha$ and $\beta$ are weights we set by hand, controlling the relative strength of the two pressures. In the paper, they use $\alpha=1$ and $\beta = \frac{1}{\{j : (i, j) \in E\}}$.
Q_hat = pd.DataFrame( [[0.0, 0.0], [0.0, 0.5], [0.5, 0.0]], columns=['x', 'y']) Q_hat
edges_0 = {0: {1, 2}, 1: set(), 2: set()} _ = retrofitting.plot_retro_path(Q_hat, edges_0)
edges_all = {0: {1, 2}, 1: {0, 2}, 2: {0, 1}} _ = retrofitting.plot_retro_path(Q_hat, edges_all)
edges_isolated = {0: {1, 2}, 1: {0, 2}, 2: set()} _ = retrofitting.plot_retro_path(Q_hat, edges_isolated)
_ = retrofitting.plot_retro_path( Q_hat, edges_all, retrofitter=Retrofitter(alpha=lambda x: 0))
Faruqui et al. conduct experiments on three knowledge graphs: WordNet, FrameNet, and the Penn Paraphrase Database (PPDB). The repository for their paper includes the graphs that they derived for their experiments.
Here, we'll reproduce just one of the two WordNet experiments they report, in which the graph is formed based on synonymy.
WordNet is an incredible, hand-built lexical resource capturing a wealth of information about English words and their inter-relationships. (Here is a collection of WordNets in other languages.) For a detailed overview using NLTK, see this tutorial.
The core concepts:
A lemma is something like our usual notion of word. Lemmas are highly sense-disambiguated. For instance, there are six lemmas that are consistent with the string
crane: the bird, the machine, the poets, ...
A synset is a collection of lemmas that are synonymous in the WordNet sense (which is WordNet-specific; words with intuitively different meanings might still be grouped together into synsets.).
WordNet is a graph of relations between lemmas and between synsets, capturing things like hypernymy, antonymy, and many others. For the most part, the relations are defined between nouns; the graph is sparser for other areas of the lexicon.
lems = wn.lemmas('crane', pos=None) for lem in lems: ss = lem.synset() print("="*70) print("Lemma name: {}".format(lem.name())) print("Lemma Synset: {}".format(ss)) print("Synset definition: {}".format(ss.definition()))
====================================================================== Lemma name: Crane Lemma Synset: Synset('crane.n.01') Synset definition: United States writer (1871-1900) ====================================================================== Lemma name: Crane Lemma Synset: Synset('crane.n.02') Synset definition: United States poet (1899-1932) ====================================================================== Lemma name: Crane Lemma Synset: Synset('grus.n.01') Synset definition: a small constellation in the southern hemisphere near Phoenix ====================================================================== Lemma name: crane Lemma Synset: Synset('crane.n.04') Synset definition: lifts and moves heavy objects; lifting tackle is suspended from a pivoted boom that rotates around a vertical axis ====================================================================== Lemma name: crane Lemma Synset: Synset('crane.n.05') Synset definition: large long-necked wading bird of marshes and plains in many parts of the world ====================================================================== Lemma name: crane Lemma Synset: Synset('crane.v.01') Synset definition: stretch (the neck) so as to see better
A central challenge of working with WordNet is that one doesn't usually encounter lemmas or synsets in the wild. One probably gets just strings, or maybe strings with part-of-speech tags. Mapping these objects to lemmas is incredibly difficult.
For our experiments with VSMs, we simply collapse together all the senses that a given string can have. This is expedient, of course. It might also be a good choice linguistically: senses are flexible and thus hard to individuate, and we might hope that our vectors can model multiple senses at the same time.
(That said, there is excellent work on creating sense-vectors; see Reisinger and Mooney 2010; Huang et al 2012.)
The following code uses the NLTK WordNet API to create the edge dictionary we need for using the
Retrofitter class:
def get_wordnet_edges(): edges = defaultdict(set) for ss in wn.all_synsets(): lem_names = {lem.name() for lem in ss.lemmas()} for lem in lem_names: edges[lem] |= lem_names return edges
wn_edges = get_wordnet_edges()
For our VSM, let's use the 300d file included in this distribution from the GloVe team, as it is close to or identical to the one used in the paper:
If you download this archive, place it in
vsmdata, and unpack it, then the following will load the file into a dictionary for you:
glove_dict = utils.glove2dict( os.path.join(data_home, 'glove.6B', 'glove.6B.300d.txt'))
This is the initial embedding space $\widehat{Q}$:
X_glove = pd.DataFrame(glove_dict).T
X_glove.T.shape
(300, 400000)
Now we just need to replace all of the strings in
edges with indices into
X_glove:
def convert_edges_to_indices(edges, Q): lookup = dict(zip(Q.index, range(Q.shape[0]))) index_edges = defaultdict(set) for start, finish_nodes in edges.items(): s = lookup.get(start) if s: f = {lookup[n] for n in finish_nodes if n in lookup} if f: index_edges[s] = f return index_edges
wn_index_edges = convert_edges_to_indices(wn_edges, X_glove)
And now we can retrofit:
wn_retro = Retrofitter(verbose=True)
X_retro = wn_retro.fit(X_glove, wn_index_edges)
Converged at iteration 10; change was 0.0043
# Optionally write `X_retro` to disk for use elsewhere: # # X_retro.to_csv( # os.path.join(data_home, 'glove6B300d-retrofit-wn.csv.gz'), compression='gzip')
Here are the results I obtained, using the same metrics as in Table 2 of Faruqui et al. 2016:
The retrofitting idea is very close to graph embedding, in which one learns distributed representations of nodes based on their position in the graph. See Hamilton et al. 2017 for an overview of these methods. There are numerous parallels with the material we've reviewed here.
If you think of the input VSM as a "warm start" for graph embedding algorithms, then you're essentially retrofitting. This connection opens up a number of new opportunities to go beyond the similarity-based semantics that underlies Faruqui et al.'s model. See Lengerich et al. 2017, section 3.2, for more on these connections.
Mrkšić et al. 2016 address the limitation of Faruqui et al's model that it assumes connected nodes in the graph are similar. In a graph with complex, varied edge semantics, this is likely to be false. They address the case of antonymy in particular.
Lengerich et al. 2017 present a functional retrofitting framework in which the edge meanings are explicitly modeled, and they evaluate instantiations of the framework with linear and neural edge penalty functions. (The Faruqui et al. model emerges as a specific instantiation of this framework.) | https://nbviewer.jupyter.org/github/cgpotts/cs224u/blob/master/vsm_03_retrofitting.ipynb | CC-MAIN-2019-43 | refinedweb | 1,453 | 63.19 |
developers,
as Yaron pointed out to me, there are quite some people now developing code=
on=20
top of SMW whom we ought to give much more details on the changes in SMW1.0=
=2E=20
Yes, we will increase our support for developers.
I will sum up the main internal changes (skip what you find uninteresting):
=3D=3D Storage =3D=3D
SMW now has a completely new storage access implementation. No more=20
SQL-queries, just calls to some specific storage class. In this way, SMW is=
=20
becoming completely detached from the DB layout (and in fact from the whole=
=20
DB technology). For instance, there were some complaints that SMW's tables=
=20
use too much disk space due to extensive indexing. In order to change the D=
B=20
layout and index structures, one now would merely have to rewrite a single=
=20
(albeit long) file, while the rest of the code remains untouched. This woul=
d=20
also allow RDF-stores to be connected to SMW in a clean way.
The store has many methods for accessing data, and more will be added. The=
=20
file includes/store/SMW_Store.php gives an overview.
=3D=3D Properties =3D=3D
There no longer is a distinction between attributes and relations. Basicall=
y,=20
all code now looks like the former attribute-code, i.e. relations now are a=
=20
special type of attribute (i.e. property). Usually this simplifies things a=
=20
lot since half of all code is obsolete.
=3D=3D Datavalues =3D=3D
Values of properties in SMW are now internally represented by their own pro=
per=20
containers. There has been SMWDataValue before, but it was now completely=20
rewritten and extended in functionality. The old typehandler code will=20
disappear, and implementing new datatypes will become easier (basically, yo=
u=20
just make a subclass of SMWDataValue).
Since relations now are a kind of property, there is also a datatype=20
for "relations", called Type:Page. It also has a special datavalue=20
implementation, called SMWWikiPageValue, which is used instead of the Title=
=20
objects that were representing values of relations in SMW0.7. Often this is=
=20
faster, and in any case it unifies the treatment.
Datavalues now also may hold a "caption", i.e. an alternative label to be u=
sed=20
for printouts. In annotations, this would be as follows:
[[property::value|caption]]
=46ew will need to know this, but you may see parameters called "caption" i=
n the=20
code.
=3D=3D=3D How do I check the type of some datavalue? =3D=3D=3D
You can check the type of a datavalue by the method getTypeID(). All built-=
in=20
types have fixed, internal IDs that you can check for. For instance, '_wpg'=
=20
is for Wikipage and '_str' is for String. The wikipage type has some=20
nonstandard methods that emulate methods of former Title objects. If you=20
still need a title object, you can get one via SMWWikiPageValue::getTitle()=
=2E=20
This should make code updates easier.
User-defined types use the DBKey of their Type-Pages as ID, so you would ge=
t=20
something like 'Geographic_length' there. But normally you do not want to=20
check for this within the code anyway.
In case of "composite types" (nary properties), you just get '__nry' as a t=
ype=20
id (the double "_" indicates that this is an internal type that has no=20
translation into user speak). To find out the exact structure of such an na=
ry=20
datavalue container, you can call getType(). It returns to you a special ki=
nd=20
of value: the value used for the property "has type". So the value describe=
s=20
an SMW datatype as specified by a user.=20
The file SMW_DV_Types.php contains the implementation of this datavalue. Th=
e=20
*type* of this container is '__typ', and the *value* of this container=20
describes a (unary or nary) type. Bascically, it holds just an array of one=
=20
or more types. You can use the method getTypeLabels() to get an array of th=
e=20
user labels of all those types, or you can use getTypeValues() to get an=20
array of typevalues representing those types. You can check whether a=20
typevalue represents a unary type by using the method isUnary(). The ID of =
a=20
unary typevalue can be obtained with the method getXSDValue(), but for nary=
=20
values this is a string that represents all IDs, separated by ';'. Thus, fo=
r=20
nary typevalues, you should first call getTypeValues() and then getXSDValue=
=20
for each entry. There is currently no way of directly getting an array of I=
Ds=20
from a typevalue. If this is handy to you, I will add it.
=3D=3D=3D How can I create new datavalue objects? =3D=3D=3D
Creating new datavalues is really easy. There is a static class=20
SMWDataValueFactory that has all kinds of convenient methods for making new=
=20
datatypes:
If you have the ID (e.g. '_wpg' or '_int') of a type, you can use the metho=
d=20
newTypeIDValue(), optionally with initial value and caption.
If you have a typevalue object for a type, you can use the method=20
newTypeObjectValue(), optionally with initial value and caption.
If you want a value for a certain property, you can use newPropertyObjectVa=
lue=20
(if you have the property's Title object) or newPropertyValue (if you just=
=20
have the name of the property). Wit newSpecialValue you can make a suitable=
=20
value for a special property.
The factory also does caching for faster response, and provides some=20
convenience methods to check the type of some property without making an=20
empty datavalue object for it.
=3D=3D Tooltips =3D=3D
We now have a universal tooltipping facility. You just insert some HTML=20
anywhere and our JavaScript will make a pretty tooltip for you. There are t=
wo=20
kinds of tooltips:
* Nonessential, inline tooltips. These will not be visible if JavaScript is=
=20
disabled and they will go away when the mouse is moved. Do not use these fo=
r=20
long or important texts. To create such a tooltip, write something like:
<span class=3D"smwttinline">Anchor Text<span=20
class=3D"smwttcontent">Some<br/>Tooltip</span></span>
* Important, persistent tooltips. The conten of those will be visible if=20
JavaScript is turned off, and they are clicked and explicitly closed. They=
=20
can hold much content, since you can scroll down if needed (but do not over=
do=20
it). To create such a tooltip, write something like:
<span class=3D"smwttpersist">Anchor Text<span=20
class=3D"smwttcontent">Some<br />Tooltip</span></span>
Instead of textual anchors, you can also use icons provided by SMW, e.g. as=
=20
follows:
<span class=3D"smwttpersist"><span class=3D"smwtticon">warning.png</span><s=
pan=20
class=3D"smwttcontent">Some<br />Tooltip</span></span>
NOTE: although these tooltips can be used everywhere, we do not provide=20
support for their direct use in wikipages. You can insert these texts in an=
y=20
page when editing, but it is likely that in the near future the required=20
JavaScript can only be requested programmatically, so that user-created=20
tooltips would fail.
=3D=3D Queries =3D=3D
There is now a whole internal API for queries. You can issue a query as bef=
ore=20
by giving a query string, but you can also construct a query from PHP=20
objects. These object-based query representations are found in the file=20
SMW_Description.php and SMW_Query.php.=20
The static methods of SMW_QueryPorcessor.php can convert a query string int=
o=20
an object-based query, and it would be possible to work on those queries wi=
th=20
your own code (e.g. to add conditions or to optimise something). The=20
Ask-Special shows how to go from query string to printout now.
Simlilarly, results are not directly printed from SQL but have an intermedi=
ate=20
result representation that is accessed by query printers. All query printer=
s=20
were rewritten to use this structure. Usually things get easier, but printi=
ng=20
queries still requires three nested loops (that's the results structure ...=
)=20
and so code tends to get messy.
Yet we think that the new internal interfaces are more convenient for issui=
ng=20
queries from your own code, for instance since you do not need=20
language-specific strings as for the earlier query strings. Of course its=20
also more efficient if you do not need a query string to be parsed.
=3D=3D What else? =3D=3D
I think this addresses most relevant changes. Feel free to ask questions on=
=20
how to port your code to SMW1.0. Yaron also asked me why the devel list is=
=20
not used for making design decisions. The reason is that SMW was developed=
=20
within the Halo project in the past months, and design decisions had to be=
=20
made during real world meetings. Also, the core developers at the moment ar=
e=20
only Denny and I, so we just talk during lunch breaks instead of starting=20
Hi all,
Denny and I have been hard to communicate with recently, mostly due to our=
=20
high workloads. Please bear with us. I will now take some time to shed some=
=20
light on the upcoming SMW 1.0 release.
[In all feature description below, the keyword "will" is used to describe=20
features that are not implemented in SVN yet, but that are planned for 1.0.]
=3D=3D Main visible changes =3D=3D
(1) "Relations" and "Attributes" are joined and become "Properties"
* The "default type" of a (untyped or nonexisting) property is "Page", i.e.=
=20
such properties just behave like relations in SMW 0.7
* You can continue to use "::" and ":=3D", but there is no difference. We=20
suggest "::", since it can be used in template parameters where "=3D" is=20
problematic.
* The former syntactic hint that "::" is a link while ":=3D" is not has thu=
s=20
been given up, but this distinction got heavily diluted recently by more=20
elaborate datatypes anyway. Also, many users had problems of distinguishing=
=20
the two things.
* The Special pages are simplified -- basically half of them is gone.
NOTE: the word "property" is the nicest thing we could come up with for=20
English (its a technical term anyway, but better ideas could be taken into=
=20
account). It also resembles common Semantic Web speak. Other languages do n=
ot=20
have this bias and can seek better terms if they like. For example, I think=
=20
that German SMW will use "Attribut" since "Eigenschaft" ("Property" in=20
German) sounds queerer.
(2) Novel, more versatile tooltips
* Tooltips now can be inserted much easier into many places, and SMW makes =
use=20
of this possibility a lot.
* Error messages in the factbox now become tooltips, and there will be the=
=20
option of displaying these error messages even inline in little tooltips=20
(useful if you disable the Factbox).
* Various hints are shown in tooltips. For instance, queries now use toolti=
ps=20
for showing problems (e.g. if you typed some query that SMW did not=20
understand properly, SMW will give a small warning instead of just showing=
=20
unexpected results).
(3) Significant speed-up
* SMW 0.7 was slow -- not because of heavy querying but because of the shee=
r=20
amounts of code being loaded all the time (shame on us).
* 1.0 loads significantly faster, yielding a noticable speedup in normal=20
operation
* Loading of JavaScripts will be controlled more carefully to prevent too m=
uch=20
single loading requests to the server per page view.
* Queries, when restricted to the query power of SMW0.7, should be faster.
(4) More powerful querying, more semantic expressivity
* Queries now are really *parsed* and *preprocessed* before being executed.=
=20
This enables much cleaner handling and new features.
* Queries support disjunctions everywhere.
* Queries support value inequality ("search for all pages with a population=
=20
that is unequal to '50000'" -- useless example, but you get the point). Not=
e=20
that this has nothing to do with negation.
* Subproperty statements are supported, and are taken into account for=20
querying.
* Redirects work like equality even on subqueries.
* Queries report all errors and problems that occurred from parsing over=20
preprocessing to execution. For example, if you use a query that is bigger=
=20
than the configuration of the site allows, you will see a warning (this was=
a=20
source for much confusion before).
(5) Improved display of datatypes
* Data values used for semantic annotation now have more control over their=
=20
display. In particular, HTML and Wiki versions of a datavalue are separated=
=2E=20
This will enable things like linked URLs to work properly (you will not=20
see "[http://... ]" in query results anymore).
(6) N-ary datatypes
* There has been discussion about this already, and I will write an extra m=
ail=20
on this. For now just note that (a) naries do not support all features and=
=20
datatypes yet, (b) naries are distinct from "subpages" (groups of annotatio=
ns=20
that are, well, grouped), (c) the availability of naries *now* does not=20
preclude the addition of grouped annotations *later*, and both things have=
=20
different uses.
(7) Ontology import revived
* Well, some people wanted it, here it is. We still do not really recommend=
=20
it, since it cannot create meaningful page contents but just empty pages wi=
th=20
annotations.
* But it is smart enough not to duplicate existing annotations.
(8) Nl language translation (thanks to Siebrand Mazeland)
(9) A completely new set of bugs (many old bugs gone, many new introduced).
=46inally, we were rightly asked to provide a parser function for <ask>=20
(something like {{#ask|...}}). This would yield full template compatibility=
=2E=20
The new "::" syntax is one step towards this, the better datavalue formatti=
ng=20
is another one. What is really missing is the conversion of HTML-query=20
outputs to wiki text. We still consider whether this is realistic for SMW=20
1.0 ... I will discuss this on the devel list.
=3D=3D Main invisible changes =3D=3D
* Basically, almost everything was rewritten more or less completely, or wi=
ll=20
be rewritten before the release. I will send details to the devel list soon=
=2E=20
Anyway, many changes should be convenient to developers of SMW-extensions,=
=20
but we are aware that more documentation is needed.
=3D=3D When? When is the release? When can I safely use SVN? =3D=3D
We *want* to release SMW 1.0 around the first week of October. At least som=
e=20
release candidate should be out by that time. Main open issues are:
* Upgrade path: the merger of Relations and Attributes requires you to merg=
e=20
two namespaces. Basically, the Attribute namespace is automatically renamed=
=20
to "Property" but the pages from "Relation:" must be moved over. You can do=
=20
this manually or (with some care) on the database, but we would like to=20
provide you with some automated way of doing this. This is the main=20
show-stopper for SMW1.0.
* Bugs: there are some medium-sized issues that we definitely want to fix.
* Documentation: the docu is not complete yet.
* Internal changes: there are still a number of "old" files that ought to b=
e=20
replaced by new implementations in SMW1.0 (though most of them already have=
).=20
This is a prerequisite for some bugfixes/improvements.
So should you upgrade to SVN? Well, you could, but note that there is no wa=
y=20
back to SMW 0.7 (especially the DB-layout changed). At least ontoworld and=
=20
various other wikis use the current alpha version and are working reasonabl=
y=20
well. You can use MediaWiki 1.10. To upgrade, you need to first go to=20
Special:SMWAdmin as usual, and press the button. If you have a large wiki,=
=20
this may take some time, and you should better use our new maintenance scri=
pt=20
SMW_setup.php. Next you should run the maintenance script=20
SMW_refreshData.php, maybe twice (on large wikis, run it only for propertie=
s=20
first, see docu in the script file). Finally you can bother how to get your=
=20
Relation-pages ("Relation:" still exists) into "Property:". This is not=20
critical for the wiki to work, but you get a lot of red links in the Factbo=
x.
Also, if your wiki is large, you may want to restrict the new query=20
expressivity. See the parameters in SMW_Settings.php (copy your own setting=
s=20
to LocalSettings.php). Especially equality (redirects) and subproperty=20
queries in combination tend to puzzle MySQL, possibly leading to long query=
=20
times. We look out for further optimisation before releasing.
=3D=3D What is it with this Halo-Project? =3D=3D
As some of you may know, we are employing and extending SMW within a projec=
t=20
called "Halo", together with the company ontoprise. Our work on many=20
SMW-features have been funded by this project, and these parts are just=20
included into SMW1.0.=20
Other features are more application-specific (Halo is targetting=20
knowledge-engineering in certain application domains in the natural=20
sciences), or tailored towards smaller wikis or specific tasks (e.g. the ta=
sk=20
of adding inline annotations to otherwise finished pages). These parts of=20
Halo will be released as an extension package to SMW1.0, that can be=20
installed, enabled, and disabled at your liking. I assume that there will=20
also be a public demonstration wiki at some time. It is not clear at the=20
moment how and if these Halo extensions are going to be maintained beyond=20
SMW1.0, but they are all in the open source so that alignment with future S=
MW=20
releases should be possible. The targetted release date for the Halo=20
extensions is around Oct 15.
OK, you are now up-to-date concerning general SMW ongoings. I will answer=20
further specific questions in separate emails, especially on the devel list. | https://sourceforge.net/p/semediawiki/mailman/semediawiki-devel/?viewmonth=200709&viewday=21 | CC-MAIN-2017-39 | refinedweb | 3,082 | 63.9 |
Changing Base Type Of A Razor View
Within a Razor view, you have access to a base set of properties (such
as
Html,
Url,
Ajax, etc.) each of which provides methods you can
use within the view.
For example, in the following view, we use the
Html property to access
the
TextBox method.
@Html.TextBox("SomeProperty")
Html is a property of type
HtmlHelper and there are a large number
of useful extension methods that hang off this type, such as
TextBox.
But where did the
Html property come from? It’s a property of
System.Web.Mvc.WebViewPage, the default base type for all razor views.
If that last phrase doesn’t make sense to you, let me explain.
Unlike many templating engines or interpreted view engines, Razor views
are dynamically compiled at runtime into a class and then executed. The
class that they’re compiled into derives from
WebViewPage. For long
time ASP.NET users, this shouldn’t come as a surprise because this is
how ASP.NET pages work as well.
Customizing the Base Class
HTML 5 (or is it simply “HTML” now) is a big topic these days. It’d be
nice to write a set of HTML 5 specific helpers extension methods, but
you’d probably like to avoid adding even more extension methods to the
HtmlHelper class because it’s already getting a little crowded in
there.
Well perhaps what we need is a new property we can access from within Razor. Well how do we do that?
What we need to do is change the base type for all Razor views to something we control. Fortunately, that’s pretty easy. When you create a new ASP.NET MVC 3 project, you might have noticed that the Views directory contains a Web.config file.
Look inside that file and you’ll notice the following snippet of XML.
>
The thing to notice is the
<pages> element which has the
pageBaseType attribute. The value of that attribute specifies the base
page type for all Razor views in your application. But you can change
that value by simply replacing that value with your custom class. While
it’s not strictly required, it’s pretty easy to simply write a class
that derives from
WebViewPage.
Let’s look at a simple example of this.
public abstract class CustomWebViewPage : WebViewPage { public Html5Helper Html5 { get; set; } public override void InitHelpers() { base.InitHelpers(); Html5 = new Html5Helper<object>(base.ViewContext, this); } }
Note that our custom class derives from
WebViewPage, but adds a new
Html5 property of type Html5Helper. I’ll show the code for that helper
here. In this case, it pretty much follows the pattern that
HtmlHelper
does. I’ve left out some properties for brevity, but at this point, you
can add whatever you want to this class.
public class Html5Helper { public Html5Helper(ViewContext viewContext, IViewDataContainer viewDataContainer) : this(viewContext, viewDataContainer, RouteTable.Routes) { } public Html5Helper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection) { ViewContext = viewContext; ViewData = new ViewDataDictionary(viewDataContainer.ViewData); } public ViewDataDictionary ViewData { get; private set; } public ViewContext ViewContext { get; private set; } }
Let’s write a simple extension method that takes advantage of this new property first, so we can get the benefits of all this work.
public static class Html5Extensions { public static IHtmlString EmailInput(this Html5Helper html, string name, string value) { var tagBuilder = new TagBuilder("input"); tagBuilder.Attributes.Add("type", "email"); tagBuilder.Attributes.Add("value", value); return new HtmlString(tagBuilder.ToString()); } }
Now, if we change the
pageBaseType to
CustomWebViewPage, we can
recompile the application and start using the new property within our
Razor views.
Nice! We can now start using our new helpers. Note that if you try this and don’t see your new property in Intellisense right away, try closing and re-opening Visual Studio.
What about Strongly Typed Views
What if I have a Razor view that specifies a strongly typed model like so:
```csharp @model Product @{ ViewBag.Title = “Home Page”; }
@Model.Name
The base class we wrote wasn’t a generic class so how’s this going to work? Not to worry. This is the part of Razor that’s pretty cool. We can simply write a generic version of our class and Razor will inject the model type into that class when it compiles the razor code. In this case, we’ll need a generic version of both our `CustomWebViewPage` and our `Html5Helper` classes. I’ll follow a similar pattern implemented by `HtmlHelper<T>` and `WebViewPage<T>`.
public abstract class CustomWebViewPage
public override void InitHelpers() {
base.InitHelpers();
Html5 = new Html5Helper
public class Html5Helper
public Html5Helper(ViewContext viewContext, IViewDataContainer container,
RouteCollection routeCollection) : base(viewContext, container,
routeCollection) {
ViewData = new ViewDataDictionary
public new ViewDataDictionary
Now you can write extension methods of
Html5Helper<TModel> which will
have access to the model type much like
HtmlHelper<TModel> does.
As usual, if there’s a change you want to make, there’s probably an extensibility point in ASP.NET MVC that’ll let you make it. The tricky part of course, in some cases, is finding the correct point. | http://haacked.com/archive/2011/02/20/changing-base-type-of-a-razor-view.aspx/ | CC-MAIN-2013-48 | refinedweb | 835 | 57.27 |
- Knowledge needed: Basic PHP, basic responsive web design
- Requires: PHP, Twitter Bootstrap, Modernizr, Swipe.js, WURFL
- Project Time: 2-4 hours 'hybrid' solution before.. The technique presented in this tutorial is a simple RESS solution that is meant to get you started in a short amount of time. We are going to build a single responsive page that includes some basic elements that are surprisingly complex to use on responsive sites: images, ads and social media widgets.
01. Responsive web design
Responsive web design needs no introduction, but you have probably noticed that most responsive techniques are only using client side code. And for a good reason. The code is based on web standards and if a new device or browser relates to these standards, our website will still work as intended. And this also means that we have one code base for all devices. And this part is both fantastic and a bit scary at the same time.
It works really well in many cases, but we also see some cases where the least capable browsers (often mobile) suffers from too much logic and content, poor usability and an overall slow experience.
02. Client, meet server
This is where the server can help out. The traditional way of building solutions for mobile or for a specific platform is to build either a separate mobile site or an app. Both methods are tailored for the specific device and it is also why they work so well for mobile (at least from an end users perspective). Both solutions also have drawbacks, as I am sure you are aware of, but they have a few things that many responsive websites don't have: optimisation for the device and speed.
It's not uncommon for a responsive website to be 2, 3 and even 4 megabytes and have hundreds of HTTP requests, and I can tell you right now that that is too much. The main idea about responsive web design is to not tailor for a specific device, but in some cases, it actually makes sense to do some opimisation on the server.
03. The setup
We'll create a simple PHP page (that looks a lot like a magazine frontpage ...). The site will have an image carousel, some advertising and some social media plug-ins. We will focus on making the site easy to set up and will use Twitter Bootstrap as a responsive framework. We'll use both feature and device detection. We'll also use Modernizer to help with feature detection and WURFL for device detection. We are going to detect the screen size of the device both server side and client side and are going to use this to make decisions about which images, ads and content we're going to serve to the user.
04. Feature detection and device detection
With this setup we have two sources of information about the browser. Modernizr is a feature detection framework that makes it easy to detect browser features. It simply runs a test in the browser to get a boolean answer as output: "does X work?" and the answer is mostly "true" or "false". The beauty of this is that it works on all browsers, also those that are not released yet. But it does not have much granularity, and the capabilities that are available is limited to what is possible to feature test. Examples of features that are possible to test include boxshadow, csstransitions, touch, rgba, geolocations and so on.
Device detection on the other hand, is something different. It all happens on the server and it's a framework that analyses the HTTP header of the device. It then looks up in a database of known devices and return a set of capabilities for that device. The beauty of this is that it's a database of information that is collected and maintained by humans and it can hold incredibly detailed information about capabilities that is currently impossible to feature test. Examples include device type (desktop, TV, mobile, tablet), device marketing name, video codec support and so on.
The downside is that User Agent analysis can go wrong some times and many devices tend to have a non unique UA string or to fake the UA string, but using a framework will minimise the rist of false detection. Device detection and feature detection cannot really be set up against each other as they are not two sides of the same coin.
05. The demo site
Let's start coding! I will show you how you can use RESS to solve three common problems: ads, images and social media plug-ins. The demo site we'll build is at andmag.se/ress/ and all the code is available in a Github repo.
We'll start by downloading and setting up the tools we are going to use. We won't focus too much on the responsive code in this tutorial and we'll use Twitter Bootstrap to help us out there.
You need to download the Bootstrap files and unzip the package. Bootstrap contains a JS, CSS and IMG folder and we will put this in a "bootstrap" folder in our empty project.
Next, we need to get the device detection up and going. We will use the ScientiaMobile WURFL Cloud offering for this. WURFL stands for Wireless Universal Resource File and WURFL is one of the most used device detection systems out there. You need to sign up with ScientiaMobile to get an API key and then you can download the cloud client. There are different versions depending on site traffic and the number of capabilities that you want. I'm using the standard version, but there's also a free version that you can use. After you have signed up, go to your account settings and download the PHP client code and put the code in a folder called "WURFL".
When that is done, we are ready to start adding code. We will focus on keeping things simple and will create a simple file structure. We'll also create our own CSS, JavaScript and image folders. We will only create a frontpage in this example and all the code goes in index.php. We'll use PHP's "include" method to include other files to avoid having all the code in the same file. index.php includes header.php and footer.php along with the fragments of the page. header.php also includes WURFL.php and RESS.php. Soon we'll see what these files will do.
06. WURFL.php
WURFL.php includes the code to initialise the WURFL client and will store the capabilities that you have access to in an PHP array.
<?php
// Include the WURFL Cloud Client
require_once 'WURFL/Client/Client.php';
// Create a configuration object
$config = new WurflCloud_Client_Config();
// Set your WURFL Cloud API Key - Change this to your own key
$config->api_key = '12345:abcDEFabcDEFabcDEFabcDEF';
// Create the WURFL Cloud Client
$client = new WurflCloud_Client_Client($config);
// Detect your device
$client->detectDevice();
?>
After the client is initialised, we can start getting information about the device that is currently using the site anywhere in the code:
<?php
$client->getDeviceCapability('brand_name');
?>
07. RESS
We're now going to build a way to combine client and server detection. We'll use a cookie to share information from the client to the server. The most important capability for this test is the screen width, so we create a RESS.php file with some JavaScript that detects the screen size for us. We also create a RESS namespace and a writeCookie() helper method. We can then get the width and write the cookie to the client:
<script type="text/javascript">
RESS = {};
RESS.writeCookie = function (name, value) { //cookie code }
//Store width in a cookie
RESS.storeSizes = function () {
//Get screen width
var width = window.innerWidth;
// Set a cookie with the client side capabilities.
RESS.writeCookie("RESS", "width." + width);
}
RESS.storeSizes();
</script>
We also register an onresize event, so that we can write the cookie when the window has changed size or the device has changed orientation, not only on a new page load. The onresize event tends to be very trigger happy so we wait one second before we write the new value.
RESS.isResizeActive = false;
window.onresize = function (event) {
if (!RESS.isResizeActive) {
RESS.isResizeActive = true;
//make sure we do not do this too often, wait 1 second...
window.setTimeout(function () {
RESS.storeSizes();
RESS.isResizeActive = false;
}, 1000);
}
}
Next, we need some PHP code to read the cookie, so that we can make the screen width available client side as well.
$RESSCookie = $_COOKIE['RESS'];
if ($RESSCookie) {
$RESSValues = explode('|', $RESSCookie);
$featureCapabilities;
foreach ($RESSValues as $RESSValue) {
$capability = explode('.', $RESSValue);
$featureCapabilities[$capability[0]] = $capability[1];
}
}
We will also get the server side width as a fallback. This is important as it will be used when we don't have access to the cookie on the first page load or if cookies or JavaScript is disabled.
$WURFLWidth = $client->getDeviceCapability('max_image_width');
if ($client->getDeviceCapability('ux_full_desktop')) {
$WURFLWidth = 1440;
}
WURFL's default screen width for "desktop" is 600 so we make sure we default to a large size and let the responsive code handle the screen size if it is smaller. And based on this we can now get the screen width server side and with a fallback to the WURFL width:
$defaultWidth = ($featureCapabilities["width"] ? $featureCapabilities["width"] : $WURFLWidth);
08. Images
Tired of hearing "responsive images" yet? Thought so. The discussion about how to handle images for different screen resolutions has been going on for some time now. Mat Marquis sums it all up nicely in his article The state of responsive images.
We're going to use our RESS screen width in order to serve different images to different screen sizes. We're using Flickr images for our carousel and we choose three of their default sizes: 320, 500, 640 and we create a new size: 770, which is the max of our carousel. There are some differences in how wide the carousel is going to be in different breakpoints and we try to consider that in the algorithm. Also note that we are going to serve an image that is slightly larger than what we are going to use. This is because we want the image to work well in landscape mode as well. If we have a 320 pixel screen width, the height or portrait width is 480 so the 500 image is the best match for such a device (based on the Flickr formats). There is room for optimisation here and you are welcome to change the code and serve smaller images if you would like that. Here is the code:
//select correct image version
if ($defaultWidth < 320) {
//small screens get 320 image
$imageVersion = "320";
} else if ($defaultWidth < 500) {
//320-499 screens get 500
$imageVersion = "500";
} else if ($defaultWidth <= 1024) {
//screens between 500 and 1024 get 640
$imageVersion = "640";
} else {
//anything >= 1024 get 770
$imageVersion = "770";
}
We will now expose our calculations in a global RESS variable:
global $RESS;
$RESS = array(
"width" => $defaultWidth,
"imageVersion" => $imageVersion);
And we can now easily get the values server side and use this in our code.
<?php echo $RESS["width"] ?>
<?php echo $RESS["imageVersion"] ?>
09. The carousel
Ok, we have everything set up now and are ready to start using it. In order to put a carousel up on the site we will use swipe.js and we also need Modernizr to know if we should enable CSS transitions or not. Also, we will try and pick the correct image version for the device. We use the four image version we decided upon and store them in our img folder:
img1_320.jpg
img1_500.jpg
img1_640.jpg
img1_770.jpg
Based on this, we can now use our RESS variable to pick the correct version:
<img src="img/img1_<?php echo $RESS["imageVersion"]?>.jpg" alt="First Image">
After applying some styles, we now have a working carousel with variable image size! You can also have a different crop of the image for different screen sizes if you wish that. See full code for the carousel here.
10. Ads
One of the problems with ad networks is that most of them only provide fixed sized ads. We're going to include those fixed sized ads on our responsive site, but we use RESS to include different sizes depending on the screen size we are dealing with. We're going to use Google AdSense and we will place an ad in the header of the page next to the logo. We use the same technique as when we served different image versions. We will have a 320px ad above the logo on small screens, a larger 468px ad on the right side of the logo on medium screens and finally a large 728px ad on the right side of the logo for large screens. Here is the code:
<?php
if ($RESS["width"] >= 320 && $RESS["width"] <= 640) {
?>
<div class="mobile-ad max-320">
<?php include "fragments/ads/320.php"?>
</div>
<?php
}?>
<div id="site-logo">
<a href="/ress/">RESS</a>
</div>
<div class="ad">
<?php
if ($RESS["width"] >= 980) {
?>
<div class="max-980">
<?php include "fragments/ads/728.php"?>
</div>
<?php
} else if ($RESS["width"] >= 768) {
?>
<div class="max-768">
<?php include "fragments/ads/468.php"?>
</div>
<?php
}
?>
</div>
Note that we have a media query that will hide the ad if the ad gets below the specified width. The ad is visible by default and we hide it for screen sizes that are less than 980px, in other words, max 979 pixels. The ad is hidden if the device width decrease without a reload, but if you reload the page you will get a different ad size.
@media screen and (max-width: 979px) {
.max-980 {
display: none !important;
}
}
Hiding content with display none is normally a big "no-no", but remember that it's only hidden if the screen size changes dramatically and it's only responsive web design developers that change their browser window on every website they see anyway ...
11. Conditional content inclusion
As you start to understand by now, we can easily write conditional code on the server and we can do a lot of dirty things ... One thing is to remove content for smaller screens. Some types of content are simply not worth the cost on mobile, such as social media widgets in this case. We can debate on removing them all together from our site (we probably should). Here are the code for the right column of our page:
<?php include "fragments/archive.php"?>
<?php if ($RESS["width"] >= 768) { ?>
<div class="max-768">
<h2>Social</h2>
<?php include "fragments/twitter-search.php"?>
<?php include "fragments/facebook.php"?>
</div>
<?php}?>
So we only include these fragments if the screen is 768 pixels or greater. Having the logic set on such a rule means that we take a step out of the fully responsive world in order to acheive a performance gain on mobile. Devices such as the Kindle Fire that has a 600x1024px screen won't load the Twitter and Facebook fragments in portrait, but it will load them in landscape. Odd things like this will happen, but that is the price we have to pay. Luckily there is a solution and it's called progressive enhancement. It should be easy to load the missing content once the screen is made wider again. Again, you should think twice about this stuff as it will probably confuse your user, but read on and have a look at the performance gain of this technique.
We are currently using screen width for all our decisions, but we could just as well be using other capabilities such as the new Network Information API.
12. Performance
So how does our approach affect the performance of the site? Here are some tests from three different breakpoints let's call them, Large, Medium and Small. (Note that the code on the demo site is not minified to make it easier to read and debug):
- Large: 84 requests, 696KB transferred | 2-6s (onload: 1-3s, DOMContentLoaded: 600ms-3s).
- Medium: 84 requests, 685KB transferred | 2-6s (onload: 1-3s, DOMContentLoaded: 600ms-3s).
- Small: 25 requests, 221KB transferred | 560ms (onload: 580ms, DOMContentLoaded: 320ms).
So the large site is three times the size of the small site, both in size and in number of requests! The difference in image size from the three 500px image to the larger 770px image is 60KB. So it's the social widgets that are actually making the site big, not the images. But size itself is not the only issue here, the amount of connections is also troublesome and they come only from the social widgets. The images are also heavily optimised from the original version by using Photoshop and ImageOptim.
13.Conclusion
We now have a basic RESS setup and it should be easy to include this in your current site or even in a PHP CMS such as Wordpress or Drupal. The technique may go against some of the things you have learned in your RWD class, but in many cases it is much more efficient (both for you and for the browser) to put the logic on the server. I've also found that this gives an increased flexibility since you can add or remove content for specific devices and you can use third party solutions that are not mobile friendly by serving alternative solutions on small screens.
Progressive Enhancement is a central part of responsive web design and can also be used together with RESS and a natuaral extension to our content inclusion demo is to include content with JavaScript when the screen size increases. You also need to be aware that we are now serving slightly different content on the same URL and that this can affect your cache. There are solutons for how to address this issue but that is out of scope for this tutorial.
14. Further reading
You also might want to check out other work on RESS: Detector by Dave Olssen and the presentation Adaptation: Why responsive design actually begins on the server by Yiibu as well as the original RESS article by Luke Wroblewski.
Anders M Andersen - andmag.se - lives, works and plays in Stockholm, Sweden. He has been doing mobile development since WML and is currently trying to get that "responsive thing" to work better for mobile devices. Catch up with Anders on Twitter as @andmag.
Liked this? Read these!
- Brilliant Wordpress tutorial selection
- Our favourite web fonts - and they don't cost a penny
- Discover what's next for Augmented Reality | https://www.creativebloq.com/responsive-web-design/getting-started-ress-5122956 | CC-MAIN-2019-47 | refinedweb | 3,095 | 70.84 |
We are still stalled with no permanent namespace to advertise effectively. I guess I will update the advogato Wikiversity project sheet with a useful link instead of the current dud ... en.wikiversity.org (de.wikiversity.org works but I have no idea whether the German language project is progressing well) and start adding alternate links to other sites that might be of interest for free educational materials.
Maybe we can just pretend the ineffective tab location at is an interactive insider joke or something (Wikiversity is Not a University or Wikibooks ... WiNUKs ...maybe the Canadians will like it ... Starts with WiN, rhymes with smucks ...hmm ... WiNuWs ... rhymes with Great Gazoo ... ).
this article on some guy's dot.corg theory has an interesting discussion and analysis of incestuous dot.org and dot.com relationships. Late in the lengthy article the author makes several points that the dot.org must be perceived as trustworthy and accomplishing its values based mission before branching out to working with commercial organizations to create revenue streams (which are split somehow between the value oriented dot.org and the profit motivated dot.com) to reinvest in their respective missions.
Maybe it is time for an anonymous email to MIT asking their open courseware initiative managers to consider a parallel free project where the public could use wiki style software to modify and republish their stuff. Maybe tie in some constraints such as MIT CS grad students can spend DOD funding counting sentences and testing theories of semantics webs or inserting Turing Test Bots or something. Developing and testing ways to track and hide information from various agents with access to the internet. It would seem like something useful could be done to justify a few million dollars worth of bandwidth and computers. Of course MIT is a private institution .... maybe better to ask some tax supported institutions what they are doing to justify their tax bases and research money to the public at large.
Maybe point out to Homeland Security that a good multi-lingual Wikiversity would be ideal learning environment for future covert operatives and intelligence analysts regarding foreign languages, cultures, thinking patterns, and typical views or biases. American Free University Online ... other countries could either compete or ally with the effort. Start it off with a big bang announcement of how many effort hours the U.S.G. intended to allocate for its trainees to create free training materials for any or all to modify and use under an FDL. Tie it into President Bush's grand plan (3rd time's the charm) for getting to Mars on a shoe string by allowing NASA specialists to leverage off of available free grunt work to keep those space technology development projects coming in under budget and ontime. Some Pentagon spectacular photo-ops could show military parents collaborating with their kids on their homework the day before a combat patrol or after debriefing. Could not possibly be less cost effective than press announcements regarding Madison Avenue based propaganda ... could it?
Really go all out and ask the American people to make a supreme sacrifice for the war effort. Instead of just encouraging your alleged literate to earn college tuition or a decent retirement in the U.S. military dodging IEDs or raiding neighborhoods in a foreign land .... gun ho civilians could encourage their students still at home to key their graded homework and term papers into a world accessible database and discuss it with their peers worldwide .... have to set up some form of mediation I suppose when the inevitable grading scandals rock the nation.
In other exciting news, I plugged a replacement CDROM into my linux server and redid the incomplete installation of Fedora Core left when I broke the previous CD. (It was jamming and refusing to open, managed to "assist" it twice before breaking it one CD short of installation competion ... argh!) Everything appears to be working fine again except, as usual, internet access. I am not looking forward to setting up Linux to the DSL with Verizon again ... so far I am one for three. Verizon kluuge and poor installation instructions, no tech support at fault ... not Fedora Core) I know it can be done with the equipment I have (unless Verizon has changed their stripes) but I am still not certain what exactly worked previously, why and in what sequence to duplicate it reliably.
I played with Kig a bit. I really liked it when it worked but I seemed to hang it up periodically. I intend to check out the code but I have an ugly feeling it is in C++ whereas I am supposed to be studying Java. Still the potential for using it to plot orbits for space related games/papers/lesson plans/sci fi plots/etc. is tempting ... not to mention its solid possiblities for high school and college level geometry and trig for wikiversity ... I forgot to check the file export capability. No rush. Nothing interesting happening with math at Wikiversity prototype, no need for cool math analysis tools with good interfaces.
Still. Nothing ventured nothing gained. I will add a link to Kig in appropriate engineering, math, and space related department files and possibly a few courses. There is some activity in some of the computer language and programming courses ... maybe they would be interested in debugging tools useful to getting the engineering or other departments of passing interest to themselves going?
Good grief! K edutainment It looks like a motherlode! I guess I have enough to keep me out of trouble for a few weeks looking this stuff over and liberally sprinkling links around the wikiversity prototype/test/stall site to provide a little apparent progress for other participants waiting breathlessly for stacked Board approval to proceed. | http://www.advogato.org/person/mirwin/diary/210.html | CC-MAIN-2014-42 | refinedweb | 962 | 53.51 |
Hello all!
Please allow me to introduce myself, my name is Tony Bernard and I am a Senior Program Manager on the BizTalk Server team. I am taking over for Suren Machiraju who, as relayed in his final post, has moved on to new and exciting opportunities elsewhere within Microsoft.
I want to take this opportunity to thank Suren for his many years of dedication and leadership on the B2B team!
In this posting I thought I would share a little trick for implementing trading partner and document security on inbound transmissions. By default, the EDI implementation in BizTalk 2006 R2 (which I will simply refer to as R2 for the remainder of this posting) will accept and validate all inbound interchanges as long as the proper schema is deployed and there is a receive location with either the EdiReceive or AS2EdiReceive pipeline specified. I'll call this approach an 'implicit accept' approach since all transmissions are by default processed assuming the appropriate artifacts are deployed.
So what do you do if you want to take an 'implicit deny' approach to processing interchanges? And how would you do that at both a trading partner level (i.e. only allow interchanges from specific partners) and at a document level (i.e. only allow certain documents from approved trading partners)?
Receive Port Authentication
One way to implement partner level security is to leverage the Authentication settings on the Receive Port. In R2 the EDI receive pipeline will compare security and authorization fields in the incoming interchange envelope with those specified in the party. If valid, the interchange will be accepted and processed. If not, the interchange will be handled according to the settings in the Authentication section on the General page of the Receive Port properties.
Partner Level Security
But what if you aren't using the security or authentication settings specified in your EDI standard (which many, arguably most, don't) or for some other reason don't want to turn on Receive Port Authentication? Well that's where our little trick comes in. There is a property on the EDIFACT and X12 Interchange Processing Properties pages of the EDI Global Properties called Target namespace. The primary intent of the property is to facilitate the 'implicit accept' behavior mentioned above by ensuring that all inbound interchanges would get assigned a valid schema namespace. However, the same field can be used to implement 'implicit deny' behavior as well. By setting this field to a dummy or 'dead letter' namespace (i.e. one in which there are no schemas) by default all inbound interchanges will be assigned that namespace unless they are successfully associated with a specific party agreement by the EDI receive pipeline. They will then be suspended by BizTalk due to a missing or invalid schema. Therefore, the only documents that will make it through will be ones which have a party agreement implemented.
Document Level Security
Now that we have discussed partner level security, let's talk about how to implement document level security. The scenario here is that you've implemented a partner for certain document types (say purchase orders), but don't want to accept other documents (say advanced ship notices or invoices) that may still be in testing. The approach is very similar to that for partner level security in that it leverages namespaces. However, for this trick we will work within the party-specific settings for that trading partner. As in the EDI Global Properties, there is a property where a default namespace for the party can be specified. This property is labeled Default Target namespace and can be found on the EDIFACT and X12 Interchange Processing Properties pages of the EDI Properties for a given party. Again, the primary intent of this setting is to ensure that all documents for this party get assigned a valid namespace. However, by leverage this property in conjunction with the Enable custom transaction set definitions grid just below it you can implement the same behavior with individual document types as you did with partners as described above. Simply set the Default Target namespace to a dummy or 'dead letter' namespace and then create entries in the grid below for the documents that you want to allow to be processed. This is analogous to creating a 'white list' for spam filtering. Documents that don't match the ones on that list will be assigned the default (i.e. dummy) namespace and will be suspended.
So there you have it. Two techniques to enhance the security of your R2-based EDI solution. That's all for now, but as always, feel free to keep the questions, comments and suggestions coming.
Cheers,
Tony | http://blogs.msdn.com/b/biztalkb2b/archive/2007/01/12/inbound-trading-partner-and-document-security.aspx | CC-MAIN-2015-40 | refinedweb | 781 | 51.07 |
On 09/07/2007 03:03 PM, Jim Jagielski wrote:
>
> On Sep 7, 2007, at 6:29 AM, jean-frederic clere wrote:
>
>>
>> I think I have patched it. Could you try it?
>>
>
> Ahh... this is much nicer that my idea of breaking out
> the data struct defs from the rest of mod_proxy.h
I do not share this view and think that we should do this
differently (haven't worked out a patch so far).
1. IMHO we change the public API with jean-frederic's patch
(we remove ap_proxy_lb_workers from mod_proxy.h so a major
bump would be due IMHO).
2. I do not like the very close coupling of scoreboard.h and mod_proxy via
the inclusion of mod_proxy.h.
By having ap_proxy_lb_workers as an optional function we decoupled both
as far as possible. The only reasons I see why we define a more or less
useful type for lb_score is that
1. We need the size of the struct for the calculation of the scoreboard
size.
2. We need the size of the struct in ap_get_scoreboard_lb to get
the correct worker slot.
Why don't we do this with another optional function that just delivers
the size of proxy_worker_stat and use an incomplete type for lb_score
that hides all the details like we do in APR?
Then we could do something like
typedef struct proxy_worker_stat lb_score
in scoreboard.h.
and do something like
return (lb_score *) (&((char *) (ap_scoreboard_image->balancers))[lb_size * lb_num]);
in ap_get_scoreboard_lb
where lb_size is the size of the struct (saved in a static var like we do with
lb_limit) or we do something like
typedef char lb_score
in scoreboard.h.
and do something like
return &ap_scoreboard_image->balancers[lb_size * lb_num];
Regards
Rüdiger | http://mail-archives.apache.org/mod_mbox/httpd-dev/200709.mbox/%3C46E1CE97.8020400@apache.org%3E | CC-MAIN-2016-18 | refinedweb | 284 | 71.55 |
Bugzilla – Bug 472
[cbackend] Static globals are prototyped as 'extern'
Last modified: 2004-12-03 11:20:26
You need to
before you can comment on or make changes to this bug.
The C writer currently generates invalid C code (static followed by extern which
will be an error in gcc-4.0, see also ).
For example:
static char msg[] = "hello";
char *foo(void) { return msg; }
gets translated into:
/* Global Variable Declarations */
extern signed char l1__2E_msg_1[6];
/* Global Variable Definitions and Initialization */
static signed char l1__2E_msg_1[6] = "hello";
/* Function Bodies */
signed char *foo(void) {
return (&(l1__2E_msg_1[0]));
}
A fix would be to emit a static forward declaration instead of extern. And even
better - though this might not be easy - the static forward declaration should
only be emitted if it is actually needed as they are invalid in C++.
Mine.
Fixed. Testcase here:
Patch here:
Thanks a lot for noticing this!
-Chris | http://llvm.cs.uiuc.edu/PR472 | crawl-001 | refinedweb | 151 | 56.29 |
02 June 2008 10:19 [Source: ICIS news]
LONDON (ICIS news)--Croda has completed the sale of its US oleochemicals business in Chicago to HIG Capital, LLC, the specialty chemicals company said on Monday.
?xml:namespace>
The UK company announced in May the sale of the business for £46.7m ($93.4m/€59.1m) to the private equity firm as part of its restructuring programme.
“All employees of the business will transfer to the acquiring entity as a result of this transaction. Croda will continue to source some products from the business under normal third party commercial terms,” it had said.
($1=€0.64/$1=$0 | http://www.icis.com/Articles/2008/06/02/9128569/croda-completes-sale-of-chicago-oleochemicals.html | CC-MAIN-2013-48 | refinedweb | 106 | 60.65 |
I am able to have buttons in a flash file trigger a Javascript function that in turn sends a event tracking message to Google Analytics.
My button sends the main playhead to a particular frame where it stops.
The AS is placed on that frame (not the button) and looks like this:
stop();
import flash.external.ExternalInterface;
vid_rec.onRelease=function(){
ExternalInterface.call("fv4");
}
(vid_rec is the instance name of the button.)
The Javascript:
function fp4(){
The JS function looks like this:
_gaq.push(['_trackEvent','Category','Action','Label',]);
}
This works nicely and Google Analytics is readily showing my category, the Action and the Label.
I am using this to track how many people listen to a sound recording.
Another one is tracking a different button that leads to a Captivate file.
Here is my problem:
I need to monitor Video visits as well.
My video is placed in a movie clip that is dropped on the main scene in a particular frame.
I have a short shape animation right before the movie starts. Let us say the animation starts in frame 10 and goes to frame 16 where there is a stop action. On that frame the movie clip with the video is placed.
I have tried to have the External interface code in both the frame where the movie clip lives and the first frame of the animation, but it does not work either way. Seems to me that I have tried to have the code inside the movieclip on the frame where the movie runs as well. And that it also did not produce a hit.
Since it works well to have the code in the main time line in the other cases, I do not understand what is different about the video, other than that it lives in a movie clip.
Do you have any other suggestions where to place the code?
Thanks on beforehand.
ggaarde
I don't see why it wouldn't work the same either since it does not appear to be timeline related as far as the code goes. Have you mixed a trace in with the code to confirm that the code is executing?
What you might try just to see is to place the function in the main timeline and try calling it from within the movieclip using a _root reference to target it.
Hi Ned.
Good idea with the trace code. It executes on the ones that are going to GA but not on the videos.
I tried to move the video to the main time line, but that did not make a difference.
Also tried to just take the playhead to an empty frame and move the code there, and that did not trigger the trace either.
Now I am even more mystified...
If i was going to try your approach of placing the function on the main time line where should it go? and what would the actual syntax be for both the function and ther movie clip calling it?
Thank you on beforehand.
ggaarde
If the code is not executing, that's a better mystery to try to solve.
For putting the function in the main timeline just place the function in a layer that extends as far as it needs to be accessible. If you name the function aFunction, then the code to call it from within the movieclip could be _root.aFunction();
But if you don't solve why the code is not executing, chances are you will find yourself in the same situation where the function call never gets made. | https://forums.adobe.com/thread/1170033 | CC-MAIN-2018-39 | refinedweb | 595 | 79.6 |
Introducing Real-Time Linux
If you wanted to control a camera or a robot or a scientific instrument from a PC, it would be natural to think of using Linux so you could take advantage of the development environment, the X Window System, and all the networking support. However, Linux cannot reliably run these kinds of hard real-time applications. A simple experiment, are more important than average performance. For example, if a camera fills a buffer every millisecond, a momentary delay in the process reading that buffer can cause data loss. If a stepper motor in a lithography machine must be turned on and off at precise intervals in order to minimize vibration and to move a wafer into position at the correct time, a momentary delay may cause an unrecoverable failure. Consider what might happen if the task that causes an emergency shutdown of a chemistry experiment must wait to run until Netscape redraws the window.
It turns we slipped a small, simple, real-time operating system underneath Linux. Linux becomes a task run only when there is no real-time task to run, and we pre-empt Linux whenever a real-time task needs the processor. The changes needed in Linux itself are minimal. Linux is mostly unaware of the real-time operating system as it goes about its business of running processes, catching interrupts, and controlling devices. Real-time tasks can run at quite a high level of precision. In our test P120 system, we can schedule tasks to run within a precision of about 20 microseconds.
Real-time Linux is a research project with two goals. First, we want a practical, non-proprietary tool we can use to control scientific instruments and robots. Our other goal is to use RT-Linux for research in real and non-real-time OS design. We'd like to be able to learn something about how to make operating systems efficient and reliable. For example, even a non-real-time operating system should be able to determine whether it can guarantee timing needed for its I/O devices. We're also interested in what types of scheduling disciplines actually turn out to be the most useful for real-time applications. Following this dual purpose, in this paper we discuss both how to use RT-Linux and how it works.
Let us consider an example. Suppose we want to write an application that polls a device for data in real-time and stores this data in a file. The main design philosophy behind RT-Linux is the following:
Real-time programs should be split into small, simple parts, with hard real-time constraints, and larger parts that do more sophisticated processing.
Following this principle, we split our application into two parts. The hard-real-time part will execute as a real-time task and copy data from the device into a special I/O interface called real-time fifo. The main part of the program will execute as an ordinary Linux process. This part will read data from the other end of the real-time fifo and display and store the data in a file.
The real-time component will be written as a kernel module. Linux allows us to compile and load kernel modules without rebooting the system. Code for a module always starts with a define of MODULE and an include of the module.h file. After that, we include the real-time header files rt_sched.h and rt_fifo.h and declare an RT_TASK structure.
#define MODULE #include <linux/module.h< /* always needed for real-time tasks */ #include <linux/rt_sched.h> #include <linux/rt_fifo.h> RT_TASK mytask;
The real-time task structure will contain pointers to code, data, and scheduling information for this task. The task structure is defined in the first include file. Currently, RT-Linux has only one fairly simple scheduler. In the future, the schedulers will also be loadable modules. Currently, the only way for real-time tasks to communicate with Linux processes is through special queues called real-time fifos. Real-time fifos have been designed so that the real-time task will never be blocked when it reads or writes data. Figure 1 illustrates real-time fifos.
Figure 1. Real-time fifos
The example program will simply loop, reading data from the device, writing the data to an RT-fifo, and waiting for a fixed amount of time.
/* this is the main program */ void mainloop(int fifodesc) { int data; /* in this loop we obtain data from */ /* the device and put it into the */ /* fifo number 1 */ while (1) { data = get_data(); rt_fifo_put(fifodesc, (char *) &data, sizeof(data)); /* give up the CPU till the */ /* next period */ rt_task_wait(); } }
All modules must contain an initialization routine. The initialization routine for the example real-time task will:
record the current time,
initialize the real-time task structure,
and put the task on the periodic schedule.
The rt_task_init routine initializes the task structure and arranges for an argument to be passed to the task. In this case, the argument is a fixed descriptor for a real-time fifo. The rt_make_periodic routine puts the new task on the periodic scheduling queue. Periodic scheduling means the task is scheduled to run at certain intervals in time units. The alternative is to make the task run only when an interrupt causes it to become active.
This function is needed in any module. It */ /* will be invoked when the module is loaded. */ int init_module(void) { #define RTfifoDESC 1 /* get the current time */ RTIME now = rt_get_time(); /* `rt_task_init' associates a function */ /* with the RT_TASK structure and sets */ /* several execution parameters: */ /* priority level = 4, */ /* stack size = 3000 bytes, */ /* pass 1 to `mainloop' as an argument */ rt_task_init(&mytask, mainloop, RTfifoDESC, 3000, 4); /* Mark `mytask' as periodic. */ /* It could be interrupt-driven as well */ /* mytask will have period of 25000 */ /* time units. The first run is in */ /* 1000 time units from now */ rt_task_make_periodic(&mytask, now + 1000, 25000); return 0; }`
Linux also requires that every module have a cleanup routine. For a real-time task, we want to make sure a dead task is no longer scheduled.
/* cleanup routine. It is invoked when the */ /* module is unloaded. */ void cleanup_module(void) { /* kill the realxi--time task */ rt_task_delete(&mytask); }
That's the end of the module. We also need a program which runs as an ordinary Linux process. In this example, the process will just read data from the fifo and write (copy) the data to stdout.
#include <rt_fifo.h> #include <stdio.h> #define RTfifoDESC 1 #define BUFSIZE 10 int buf[BUFSIZE]; int main() { int i; int n; /* create fifo number 1 with size of */ /* 1000 bytes */ rt_fifo_create(1, 1000); for (n=0; n < 100; n++) { /* read the data from the fifo */ /* and print it */ rt_fifo_read(1, (char *) buf, BUFSIZE * sizeof(int)); for (i = 0; i < BUFSIZE; i++) { printf("%d ", buf[i]); } printf("\n"); } /* destroy fifo number 1 */ rt_fifo_destroy(1); return 0; }
The main program could also display data on the screen, send it over the network, etc. All these activities are assumed to be non-real-time. The fifo size must be big enough to avoid overflows. Overflows can be detected, and another fifo can be used to inform the main program about | http://www.linuxjournal.com/article/232?quicktabs_1=0 | CC-MAIN-2015-32 | refinedweb | 1,203 | 53.92 |
Oct 11, 2012 05:22 PM|armendderguti|LINK
Hi to all
I am going to develop a GPS tracking system which basically receives data from GPS device via GPRS store them in database show them for the real time monitoring and generate the reports.
What I need now is some advice in:
1. The data are transmited via GPRS connection over TCP. There are over 1000 units that sends data once per second. What is the best way to handle those data (receive, phrase, store in SQL, and show them in real time)? (really need clear advice here!)
2. Can this system be done with Web Forms, Ajax, and SQL 2008 R2? If not what is proposed?
Thank you in advance
Armend
Oct 11, 2012 06:59 PM|N_EvilScott|LINK
The best thing you can do since its just regular packets coming over TCP is use as little overhead as possible. A Windows Service lends itself completely to this, and you can use the TcpListener object in the System.Net.Sockets namespace to capture all the incoming data.
The windows service will be able to handle anything you want extremely fast.
After your backend is completed with that, you can create your front end with whatever tech you want.
1) Best way is to use the TcpListener and capture the data using a Windows Service
2) Capturing cannot be done via Ajax or Web Forms, but you can use the Windows Service to store information into SQL Server or some type of intermediate respository for viewing. You can VIEW the data with any standard web tech you want, but capturing will require some low level code like Sockets and the TcpListener in order to get the quality you want.
Oct 12, 2012 04:18 PM|armendderguti|LINK
Oct 12, 2012 04:27 PM|N_EvilScott|LINK
Having the windows service communicate directly with the viewing mechanism generally isn't supported and you would need to use some type of interop in order to make it work anyway. Not only is it harder to do, but it can also hinder the service performance. Much easier to just let the service collect info and dump it into a database or some other medium.
In my experience an sql database works perfect for this. That way you have the service operating normally and just inserting data to the database, and the database is taking all the pain of having to read and write at the same time from the View and from the Service.
The most simple way to display the data that refreshes every second is going to be using AJAX. It's very light and requires little effort.
There are essentially two common ways to set that up:
1) Use an <asp:Timer> ajax control and have it Tick every second and query the data and return it to the controls inside of an update panel.
2) Another idea that is probably a bit lighter, and more client friendly is to create a regular asp.net web service that queries the database or other medium you are storing the data into. Then use the <asp:ScriptManager> and regular javascript functions to query the data every second. Javascripts SetInterval(1000) works best for this as a super light timer, instead of using SetTimeout(1000) and resetting the timeout later.
Oct 13, 2012 11:40 AM|armendderguti|LINK
Oct 15, 2012 04:03 PM|N_EvilScott|LINK
I don't know of any videos but you can search youtube. Here is a quick link though that shows how to assign a web service in the ScriptManager, and then you can call it using javascript.
5 replies
Last post Oct 15, 2012 04:03 PM by N_EvilScott | https://forums.asp.net/t/1850622.aspx?GPS+Tracking+System+Advice+needed | CC-MAIN-2018-13 | refinedweb | 621 | 68.4 |
On my daily journey down the Youtube rabbit hole at 2 a.m, I stumbled upon a series of videos with 2005esque TV news channel graphics and computer generated text-to-speech voiceovers. I linked the video but it really isn’t worth watching. I have no way to refund your 3 minutes if you did click on that link. In summary, the content is poorly produced and is probably just a text to speech program being run on a news article with stock graphics as a background. The video I stumbled upon didn’t really have too many views (goes to show how deep down the rabbit hole I really went) but that doesn’t mean this isn’t a big deal. These bots can churn out hundreds of videos per day. The quality of content isn’t even the biggest issue because we really can’t expect every Youtube channel to spend hours in production. Quality is meant to be a choice of the Youtube channel. The main issue is that these videos are very obviously plagiarizing content from other news websites. You can find hundreds of other bot driven channels that cover the exact same news content with slightly different backdrops. I also managed to find variations of TTS generated content such as this r/AskReddit based Youtube channel (I’m a bit conflicted on this one because some variations appear weirdly human but churn out enough content per day for me to suspect them).
The financial incentive
Apparently, NYTimes.com publishes on average 150 articles per day. In order to maximize Youtube ad revenue, the video would have to be around 10 minutes long. By a wordcounter.net estimation, a standard speaking pace would require around 1600 words for a 10-minute long speech. I’m not sure how many of the 150 articles are actually this long. Let’s assume that only the around 65 blog posts per day are usable content for the bot-generated videos. If you’ve ever uploaded a video to Youtube, you’d know that even a 10-second clip from a CCTV camera of a fly sitting on a wall would get around 4-6 views in the first 24 hours. Most of these views come from bots. These views don’t appear to be useful in terms of watch time analytics or ad revenue generation. The real money comes from real people (usually). According to most ad revenue calculators, assuming around 5 real human views per video and a pretty low engagement level of around 1%, your revenue would be around $3-5 per month. This is pretty paltry compared to what you could earn if you actually created useful content and encouraged engagement with your audience. However, these bots recognize their power in numbers. Large numbers.
If this bot were to run for a month,
- Day 1: 65 videos, 5 views per video, 325 views for the day = $0.10 in ad revenue for the day
- Day 2: 65 + 65 videos from the previous day, 5 views per video, 650 views for the day = $0.18 in ad revenue for the day
- And so on
Obviously, the revenue won’t just scale up linearly. Videos will tend to gain fewer viewers over time. However, if everything went according to plan, these channels could be earning around $50 per month according to my napkin math. You might be thinking, $50 isn’t a whole lot of money for a month of plagiarizing.
The cost?
It costs literally nothing. It’s 50 free dollars for the first month and an increasing passive income for as long as Youtube decides to keep your video up. Your videos could earn even more if a couple of them went viral which is very possible if the news article happened to be controversial. $50 in your first month could easily turn into $500 over subsequent months. Also, there is nothing stopping these bots from being run on multiple channels and plagiarizing from more than 65 articles per day. $50 per month is as low as my estimate could get.
So I tried building my own bot…
My intention was never to plagiarize 65 articles per day and earn a passive income for myself. I just wanted to try writing a script to show how easy it is to generate content for Youtube. This isn’t particularly good content and it won’t earn any money because thankfully, Youtube has guidelines to prevent newly created channels from earning ad revenue. Also, I’m hesitant to call it a bot because I no longer run it on the cloud and it’s really just a Python script.
The first step of writing generating Youtube content is to find a source to plagiarize from. I found that Listverse has content that is formatted pretty much the same way in every article. “Top 10” videos also tend to be pretty popular so this might just end up being my new retirement plan.
BeautifulSoup is an awesome Python library for scraping the web! First, we need to open the URL of the blog post using the requests library and perform a GET request. We use headers to give us permission to perform the request since the website denies access from any non-user requests.
from bs4 import BeautifulSoup import requests url = "url" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} page = requests.get(url, headers=headers)
I decided that the video would be formatted in the form of slides, just like any low-quality powerpoint presentation video. Each slide has a default duration of 3 seconds, an index, a title, and its content. Grouping chunks of content into slides made it easy to manipulate each group by calling functions on each object.
#slide class class Slide: duration = 3 def __init__(self, index, title, content): self.index = index self.title = title self.content = content
Next step is getting the relevant content from the page. I can’t show you the code for this because this implementation will vary based on which site you are scraping. But the idea is just to save all the useful details into Slide objects using the default constructor.
#creating slides slides = [] #creating intro slide intro_slide = Slide(0, title, preview) #creating outro slide outro_slide = Slide(11, "Thank you for watching!", "Please Like & Subscribe!") slides.append(intro_slide) for i in range(1, 11): slide = Slide(i, item_titles[i-1], item_contents[i-1]) slides.append(slide) slides.append(outro_slide)
These Slides are only abstract representations of what we need to put the video together. We need to generate images for each slide to have a visual representation of our content. I used PIL to generate images with text overlays for each slide. This was a little complicated as I needed to figure out how to scale each title and place it in the center of each image according to the total number of characters in the text. The textwrap library helps separate each block of text into multiple segments based on how many characters you want per line. Each image is saved in a directory called “video_name/images”. All the images are saved in this directory to later be accessed by an FFMPEG script and be concatenated into a video.
from PIL import Image, ImageDraw, ImageFont import textwrap #creating images for slides font = ImageFont.truetype("arial.ttf", 60) i = 0 for slide in slides: i = i+1 if i == 1 or i == 12: img = Image.new('RGB', (632, 420), 'white') else: img = Image.new('RGB', (632, 420), (222,222,200)) lines = textwrap.wrap(slide.title, width=20) #multi line title y_text = 80 draw = ImageDraw.Draw(img) for line in lines: w, h = font.getsize(line) draw.text(((632 - w) / 2, y_text), line, font=font, fill="black") y_text += h img.save("E:/youtube-generator/"+video_name+"/images/" + str(i) + ".jpg")
We’re almost done! We just need to generate speech using our text. I used the Google TTS library for Python. Since we’re generating audio files now, it is also convenient to update the duration of each slide from their default values. The duration of the slide is just the duration of the TTS audio file. I used mutagen to find the length of the MP3 file generated. All the audio files are stored in an audio subdirectory for easy use with FFMPEG.
from gtts import gTTS #text to speech from mutagen.mp3 import MP3 #get audio durations #generating audio files and durations i = 0 for slide in slides: i = i + 1 tts = gTTS(text=slide.content, lang='en') tts.save("E:/youtube-generator/"+video_name+"/audio/" + str(i) + ".mp3") #get durations here audio = MP3("E:/youtube-generator/"+video_name+"/audio/" + str(i) + ".mp3") slide.duration = audio.info.length
FFMPEG is our best option for programmatically generating videos. It is primarily used on the command line but you can also write C programs using the FFMPEG libraries. I decided to use a Batch script since I really didn’t want to mess with C. FFMPEG has an option to take a “blueprint” text file with references to the video clip names and concatenate them together. It has a similar option to concatenate audio files. Once we have the full-length video file and full-length audio file, we need to put these two together to generate the final video file. I generated the blueprint files in the Python script.
text_file = open(""+video_name+"/input.txt", "w") audio_list = open(""+video_name+"/audio.txt", "w") i = 0 for slide in slides: i = i + 1 #write audio clips audio_list.write("file " + "'audio/" + str(i) + ".mp3'") audio_list.write("\n") #write video clips text_file.write("file " + "'images/" + str(i) + ".jpg'") text_file.write("\n") text_file.write("duration " + str(slide.duration)) text_file.write("\n") text_file.write("file " + "'images/" + str(12) + ".jpg'") text_file.close()
The blueprint needs to be formatted sort of like this:
file 'images/1.jpg' duration 18.192 file 'images/2.jpg' duration 75.768 file 'images/3.jpg' duration 73.248 file 'images/4.jpg' duration 81.432 file 'images/5.jpg' duration 61.32 .... file 'images/11.jpg' duration 68.592 file 'images/12.jpg' duration 1.824 file 'images/12.jpg'
…and similarly for the audio files. Here are the three commands that make the magic happen!
ffmpeg -f concat -i input.txt -vsync vfr -pix_fmt yuv420p output.mp4 //concat images ffmpeg -f concat -i audio.txt -c copy output.wav //concat audio ffmpeg -i output.mp4 -i output.wav -c:v copy -c:a aac -strict experimental final.mp4 //put em together
The lesson to be learned
Here’s the stupid video I ended up generating.
Writing scripts to generate content isn’t a particularly new concept and it was never really difficult. I guess the whole point of this experiment was really just to show that there’s a lot of goofy things you can do with a little bit of free time and some Python. Don’t try this at home. Don’t steal content. There’s probably some legal way to use this script and earn money on Youtube. Perhaps you could use it to generate videos to supplement the growth of your Youtube channel while running a blog. The possibilities are endless (?)! | https://abhinavpola.com/blog/ | CC-MAIN-2020-05 | refinedweb | 1,891 | 66.94 |
ACL_COPY_EXT(3) BSD Library Functions Manual ACL_COPY_EXT(3)
acl_copy_ext — copy an ACL from internal to external representation
Linux Access Control Lists library (libacl, -lacl).
#include <sys/types.h> #include <sys/acl.h> ssize_t acl_copy_ext(void *buf_p, acl_t acl, ssize_t size);
The acl_copy_ext() function copies the ACL pointed to by acl from sys‐ tem unspeci‐ fied. It is the responsibility of the invoker to allocate an area large enough to hold the copied ACL. The size of the exportable, con‐ tiguous,.
Upon success, this function returns the number of bytes placed in the buffer pointed to by buf_p. On error, a value of (ssize_t)-1 is returned and errno is set appropriately..
IEEE Std 1003.1e draft 17 (“POSIX.1e”, abandoned)
acl_copy_int(3), acl | http://man7.org/linux/man-pages/man3/acl_copy_ext.3.html | CC-MAIN-2017-22 | refinedweb | 123 | 60.11 |
In this article, we will learn what a heap is in python and its implementation. We will understand max heap and min heap concepts with their python program implementation and the difference between max-heap and min-heap. Lastly, we will learn the time complexity and applications of heap data structure. So, let's get started!
What is Heap?
Heap is a data structure that follows a complete binary tree's property and satisfies the heap property. Therefore, it is also known as a binary heap. As we all know, the complete binary tree is a tree with every level filled and all the nodes are as far left as possible. In the binary tree, it is possible that the last level is empty and not filled. Now, you must be wondering what is the heap property? In the heap data structure, we assign key-value or weight to every node of the tree. Now, the root node key value is compared with the children’s nodes and then the tree is arranged accordingly into two categories i.e., max-heap and min-heap. Heap data structure is basically used as a heapsort algorithm to sort the elements in an array or a list. Heapsort algorithms can be used in priority queues, order statistics, Prim's algorithm or Dijkstra's algorithm, etc. In short, the heap data structure is used when it is important to repeatedly remove the objects with the highest or the lowest priority.
As learned earlier, there are two categories of heap data structure i.e. max-heap and min-heap. Let us understand them below but before that, we will study the heapify property to understand max-heap and min-heap.
What is Heapify?
Before moving forward with any concept, we need to learn what is heapify. So, the process of creating a heap data structure using the binary tree is called Heapify. The heapify process is used to create the Max-Heap or the Min-Heap. Let us study the Heapify using an example below:
Consider the input array as shown in the figure below:
Using this array, we will create the complete binary tree
We will start the process of heapify from the first index of the non-leaf node as shown below:
Now we will set the current element “k” as “largest” and as we know the index of a left child is given by “2k + 1” and the right child is given by “2k + 2”.
Therefore, if the left child is larger than the current element i.e. kth index we will set the “largest” with the left child’s index and if the right child is larger than the current element i.e., kth index then we will set the “largest” with right child’s index.
Lastly, we will swap the “largest” element with the current element(kth element).
We’ll repeat the above steps 3-6 until the tree is heaped.
Algorithm for Max-Heapify
maxHeapify(array, size, k) set k as largest leftChild = 2k + 1 rightChild = 2k + 2 if leftChild > array[largest] set leftChildIndex as largest if rightChild > array[largest] set rightChildIndex as largest swap array[k] and array[largest]
Algorithm for Min-Heapify
minHeapify(array, size, k) set k as smallest leftChild = 2k + 1 rightChild = 2k + 2 if leftChild < array[smallest] set leftChildIndex as smallest if rightChild < array[smallest] set rightChildIndex as smallest swap array[k] and array[smallest]
What is Max Heap?
When the value of each internal node is larger than or equal to the value of its children node then it is called the Max-Heap Property. Also, in a max-heap, the value of the root node is largest among all the other nodes of the tree. Therefore, if “a” has a child node “b” then
Key(a) >= key(b)
represents the Max Max Heap
MaxHeap(array, size) loop from the first index down to zero call maxHeapify
Algorithm for Insertion in Max Heap
If there is no node, create a new Node. else (a node is already present) insert the new Node at the end maxHeapify the array
Algorithm for Deletion in Max Heap
If nodeDeleted is the leaf Node remove the node Else swap nodeDeleted with the lastNode remove nodeDeleted maxHeapify the array
Python Code for Max Heap Data Structure
def max_heapify(A,k): l = left(k) r = right(k) if l < len(A) and A[l] > A[k]: largest = l else: largest = k if r < len(A) and A[r] > A[largest]: largest = r if largest != k: A[k], A[largest] = A[largest], A[k] max_heapify(A, largest) def left(k): return 2 * k + 1 def right(i): return 2 * k + 2 def build_max_heap(A): n = int((len(A)//2)-1) for k in range(n, -1, -1): max_heapify(A,k) A = [3,9,2,1,4,5] build_max_heap(A) print(A)
Output
[9, 4, 5, 1, 3, 2]
What is Min Heap?
When the value of each internal node is smaller than the value of its children node then it is called the Min-Heap Property. Also, in the min-heap, the value of the root node is the smallest among all the other nodes of the tree. Therefore, if “a” has a child node “b” then
Key(a) < key(b)
represents the Min Min Heap
MinHeap(array, size) loop from the first index down to zero call minHeapify
Algorithm for Insertion in Min Heap
If there is no node, create a new Node. else (a node is already present) insert the new Node at the end minHeapify the array
Algorithm for Deletion in Min Heap
If nodeDeleted is the leaf Node remove the node Else swap nodeDeleted with the lastNode remove nodeDeleted minHeapify the array
Python Code for Min Heap Data Structure
def min_heapify(A,k): l = left(k) r = right(k) if l < len(A) and A[l] < A[k]: smallest = l else: smallest = k if r < len(A) and A[r] < A[smallest]: smallest = r if smallest != k: A[k], A[smallest] = A[smallest], A[k] min_heapify(A, smallest) def left(k): return 2 * k + 1 def right(k): return 2 * k + 2 def build_min_heap(A): n = int((len(A)//2)-1) for k in range(n, -1, -1): min_heapify(A,k) A = [3,9,2,1,4,5] build_min_heap(A) print(A)
Output
[1, 3, 2, 9, 4, 5]
Min Heap vs Max Heap
Time complexity
The running time complexity of the building heap is O(n log(n)) where each call for heapify costs O(log(n)) and the cost of building heap is O(n). Therefore, the overall time complexity will be O(n log(n)).
Applications of Heap
- Heap is used while implementing priority queue
- Heap is used in Heap sort
- Heap data structure is used while working with Dijkstra's algorithm
- We can use max-heap and min-heap in the operating system for the job scheduling algorithm
- It is used in the selection algorithm
- Heap data structure is used in graph algorithms like prim’s algorithm
- It is used in order statistics
- Heap data structure is used in k-way merge
Conclusion
Heap data structure is a very useful data structure when it comes to working with graphs or trees. Heap data structure helps us improve the efficiency of various programs and problem statements. We can use min-heap and max-heap as they are efficient when processing data sets. As you get a good command of heap data structure, you are great to work with graphs and trees at the advanced level. | https://favtutor.com/blogs/heap-in-python | CC-MAIN-2022-05 | refinedweb | 1,262 | 62.82 |
Eclipse:
Katalon: ?
If it’s possible, then HOW? If it’s not possible, then WHY?
Thanks!
Eclipse:
Katalon: ?
If it’s possible, then HOW? If it’s not possible, then WHY?
Thanks!
No, it is not possible. Not supported.
I don’t know. Ask Katalon Team.
I personally never feel I need it.
I would rather ask you why you need it?
A Katalon Studio project is a folder with a composite of Groovy source codes (*.groovy) + XML files + *.properties files. All of them are text files. You can open a Katalon Studio project folder with your favourite Editor and do “Text Search” and “Text Replace” as much as you like. When necessary, I would do so using Emacs or Visual Studio Code. Be sure you don’t break the Katalon’s project structure when you do so.
For your information.
When I open a Groovy source file in the Keyword folder, I can right click a method name of a class, select
Reference > Project; then Eclipse Search feature shows the references made by other Groovy source codes in the project.
As you can see, the Eclipse Search feature is in action behind Katalon Studio.
But I do not find a “Search” feature for Test Cases. Though I would not need it.
Hi kazurayam,
It would be great to have it for the same reason Eclipse has it - to make developers lives easier and more productive. For example, if you remember some function name or a part of it, but don’t remember the locations where it’s defined or used, that would definitely help. Or you need to work on the project developed by someone else and trying to understand it. Etc., etc, etc. Katalon is not very helpful in this regards to put it mildly. Yes, it’s possible to use some editors to search, but that’s not the same as being able to do it in Katalon itself and then just click on the search result to get to the exact location in Katalon itself (w/o even being able to “break the Katalon’s project structure when you do so.”)) and being able to edit it right away.
As for your second reply, even that shows how unfriendly Katalon is to their users because it looks like, for example, in my Util.groovy
@Keyword def static clickElementJS(TestObject to) { // STATIC usable and searchable in the Keywords by selecting 'clickElementJS' when called like this // (i.e. w/o CustomKeywords.'web.Util.clickElementJS') : // "web.Util.clickElementJS(findTestObject(''))" // // searchable in the Scripts, Tests by using Util.groovy (Show References) when called like this // (i.e. with CustomKeywords.'web.Util.clickElementJS') : // CustomKeywords.'web.Util.clickElementJS'(findTestObject('')) // // not searchable in the Scripts, Tests when called like this: // // (i.e. w/o CustomKeywords.'web.Util.clickElementJS') : // web.Util.clickElementJS(findTestObject(''))
kazurayam, I just put my observations about searching in my code and commented it out. In my previous comment, I just copied it directly from my code to give some context helping to understand what my comments are about. Still it looks better after you use the Markdown code formatting. Thanks.
Which reminds me about another Katalon’s “feature”. If I right-click -> Source -> Add Block Comment, it distorts my code. right-click -> Source -> Toggle Comment works though. That’s all my comments are now //
The funny thing is that, as a result of my observations about searching, I’m only using something like this to use my keywords in my tests
CustomKeywords.‘web.Util.clickElementJS’(findTestObject(’’))
just because it’s easier to search and not for any other reasons )
Are you aware that you don’t have to call your Keyword classes indirectly via
CustomeKeywords?
Your test case and your groovy classes can call your Keyword class.method() directly just as a usual Groovy class.method() like this:
import web.Util Util.clickElementJS(findTestObject('...'))
If you write your code in this simpler way, the Eclipse built-in “Reference > Project” feature in the Script mode editor will work for you.
If you write your code in
CustomKeywords."..."(...) format, unfortunately, the “Reference” feature loses its power.
CustomKeywords is a magic spell that functions only in the Manual mode of Test Case editor. If you do not use the Manual mode and use the Script mode only, you can forget
CustomKeywords and
@Keyword annotation at all. | https://forum.katalon.com/t/is-it-possible-to-search-in-katalon-as-in-eclipse/56484 | CC-MAIN-2022-27 | refinedweb | 723 | 65.52 |
Ankit Patel | Software engineer, Content Acquisition and Media Platform
With the growing need for machine learning signals from Pinterest’s huge visual dataset, we decided to take a closer look at our infrastructure that produces and serves these signals. A few parameters we were particularly interested in were signal availability, infra complexity and cost optimization, tech integration, developer velocity, and monitoring. In this post, we will describe our journey from a Lambda architecture to the new real-time signals infrastructure inspired by Kappa architecture.
In order to understand the existing visual signals infrastructure, we need to understand some of the basic content processing systems at Pinterest. Pinterest’s Content Acquisition and Media Platform, formerly known as Video and Image Platform (VIP), is responsible for ingesting, processing, and serving all of Pinterest’s content on every surface of the application. We ingest media at a massive scale every single day. This post will not go into details about the ingestion and serving part, and it will mostly focus on the processing part, as that is where most of the magic happens.
Media is ingested through 50 different pipelines. Pipelines are namespaces in VIP systems, e.g. Pinner uploaded content, crawled images, shopping images, video keyframes, user profile images, etc. Each pipeline maps to custom media processing configurations tailored for the use case it serves.
When we started building our visual signals processing infrastructure, we utilized this existing namespace philosophy and also partitioned our visual signals around pipelines. Pinterest’s homegrown signal processing and serving tech stack is called Galaxy. Namespaces keyed by different entity IDs in Galaxy are called Joins or Galaxies. Each VIP pipeline is mapped to their equivalent Galaxy. Sometimes we combine multiple similar pipelines into a single galaxy, as they are closely related.
Until recently, we used the Lambda architecture illustrated below to compute visual signals from our media content.
As you can see in the diagram above, there are 2 modes to this architecture: online and offline. Let’s discuss the offline architecture first.
- A nightly workflow (Hadoop based map-reduce job) is scheduled to run. We calculate the delta unique image signatures from that particular day and create a new partition.
- We then create batches of image signatures and enqueue PinLater jobs for processing these batches.
- We spin up a GPU cluster with the ML models needed for the signal computation and then start processing the PinLater Jobs. This is an expensive cluster.
- We download the image from Amazon S3, run the model inference on them, and then store the output in S3. We would then spin down the GPU cluster to optimize EC2 spend.
- The signal is generated in a delimited bytes format with Protobuf encoded values.
- We kickoff a Workflow which transforms this output into equivalent Apache Thrift encoding because Pinterest heavily uses Thrift as its wire format and storage for data.
- Thrift output is stored in a Parquet columnar Hive table. Downstream batch clients consume this output.
- In order to support real time RPC clients, we have a final workflow that uploads the Hive partition to a Rockstore key value pair database.
- Galaxy Signal Service provides an RPC API to look up these signals from Rockstore for our online clients.
As you can see, there are a lot of moving pieces in the above design. Even though these processes matured over time and became more stable, VIP team engineers faced frequent issues while on call. Some of the biggest concerns were:
- Workflows depending on other workflow
- Consumers have to wait 24 hours for the signals to be available
- Application logic issues are extremely hard to debug
- Granular retries don’t exist, it’s all or nothing
- Delays due to the nature of these systems
As we continued to build additional features that are powered by these machine learning signals, the need for producing these signals faster became a priority across the company. That is where the online mode comes into picture:
- We create a PinLater job for each image signature in real time.
- In this Job, we call a GPU cluster running the machine learning model inference service to calculate a signal and directly store its result into the key value pair based Rockstore database. GSS (Galaxy Signal Service) would then serve this signal.
- We then publish an event through Kafka to notify the downstream consumers about the signal availability.
- Downstream clients consume this event and fetch the signal from GSS in real time.
VIP wasn’t the only team in Pinterest that was getting attracted to this new paradigm of signal processing. Other teams became excited about the idea of having their signals calculated in real time. It provided more visibility into the signal generation compared to the black box that is hadoop based workflows. This approach came with multiple benefits like:
- Better developer experience
- Easier to debug, test, and deploy changes
- Granular retries
- Low latency signals
However, it came with its share of cons as well. The main ones being:
- Complex operations, like group bys and signal joins, are not possible with a simple event-driven processing framework like Pinlater. We needed a robust stream processing framework like Apache Flink.
- The extra cost of running a duplicate GPU cluster that processes the same pins as the batch pipeline on a continuous basis.
- There was no shared infrastructure to address common needs.
Finally, the Signal Platform team at Pinterest saw an opportunity to address this concern for all signal developers and build the next version of signal development infrastructure called “Near-real-time Galaxy,” or simply NRTG. The technologies of choice were Apache Kafka and Apache Flink. Flink seemed like it was specifically designed to address the concerns mentioned above. Given that the Signal Platform team already had a framework in place to build signals on a batch technology using Galaxy Dataflow APIs, extending it to also work on a stream technology was arguably the best way forward without causing massive amounts of refactoring, rewriting, or just reinventing.
The VIP team decided to be among the early adopters of this initiative as our media signals are some of the most upstream in the whole tree of signals at Pinterest, so it would naturally be the easiest to onboard a platform while it is still being built. We scoped out the signals we wanted to experiment with and got started on this mission.
The gist of it is very simple: you would write a simple flink job that computes the signal in streaming (on Apache Flink). NRTG would make this process easy and quick by leveraging standard design patterns and annotations.
Based on the annotations, the NRTG framework mentioned above does most of the heavy lifting away hidden from the signal developers. The configs and the mapping to underlying native Flink is managed by this middleware layer. This makes signal development extremely fast because the developers do not need to learn Flink in detail as they are already familiar with these annotations. Xenon (Flink) platform team at Pinterest provides the infrastructure capabilities to deploy and maintain Flink applications.
Once we onboarded to NRTG, we wanted to turn down our existing batch workflows setup. There are a number of consumers who consume these signals in batch. We had to provide a solution that would work for them from our streaming pipelines. In order to simulate a daily Hive table for our signals, we wrote a simplified workflow that takes a daily dump of our KVStore and transforms it into existing Hive output. No GPU computations were required to recompute the signal values — the data was simply computed in streaming, moved to S3 via a daily dump, and filtered to the correct format. This not only allowed us to save on the GPU cost but also trim down chained complex workflows design into a simple data transformation job. With the FlinkSQL being in active development, we will be able to completely migrate the offline portion from Spark/Hadoop to Flink.
Migration to this new fast-signals infrastructure is the beginning of a great future for Pinterest in signal generation. It allows the signal developers to quickly build signals with a lot less learning curve. Underlying Flink capabilities also support advanced signals design. Even though batch backfill support is a work in progress in NRTG and the signal producers need to adapt outputs to avoid disruption to their consumers, the benefits still outweigh the costs of duplication in the existing lambda infrastructure. NRTG team already has this in the roadmap to offer end to end support by providing Hive integration as part of the framework. Bringing the end to end lifecycle of a signal under one platform would massively benefit the innovation and productizing ideas across different teams at Pinterest. It has reduced the infra complexity, and we are able to leverage cost optimization on GPU and other compute resources. We expect other teams at Pinterest to follow in the same footsteps and boost their developer velocity by moving to a more simple and robust architecture as outlined in this blog.
This project is a joint effort across multiple teams at Pinterest: Video & Image Platform (VIP), Near-real time Galaxy (NRTG), Xenon, Hermes, Rockstore, and Visual Search. | https://engineeringjobs4u.co.uk/pinterest-visual-signals-infrastructure-evolution-from-lambda-to-kappa-architecture-by-pinterest-engineering-pinterest-engineering-blog-nov-2020 | CC-MAIN-2021-25 | refinedweb | 1,531 | 51.28 |
On Sun, 29 Mar 2009 18:45:36 +0200Corrado Zoccolo <czoccolo@gmail.com> wrote:> On Sun, Mar 29, 2009 at 5:51 PM, Arjan van de Ven> <arjan@infradead.org> wrote:> > On Sun, 29 Mar 2009 17:40:10 +0200> > Corrado Zoccolo <czoccolo@gmail.com> wrote:> >> >> Hi,> >> I'm seeing around 2 s "lost" during kernel boot, that are not> >> accounted for any init call (excerpt of dmesg with initcall_debug> >> follows, kernel is 2.6.29).> >> What's the suggested way to investigate such problems?> >> > I take it you don't have an initrd ?> > You guessed right.> > >> > If so I know what you are hitting; I have a patch to solve it but> > it's a bit convoluted and not ready for mainline.... let me know if> > you want to try it, I suspect it'll solve your issue ;)> >> > Sure. I'd like to test it.> attached...-- Arjan van de Ven Intel Open Source Technology CentreFor development, discussion and tips for power savings, visit: [PATCH] fastboot: remove "wait for all devices before mounting root" delayIn the non-initrd case, we wait for all devices to finish theirprobing before we try to mount the rootfs.In practice, this means that we end up waiting 2 extra seconds forthe PS/2 mouse probing even though the root holding device has beenready since a long time.The previous two patches in this series made the RAID autodetect codedo it's own "wait for probing to be done" code, and added"wait and retry" functionality in case the root device isn't actuallyavailable.These two changes should make it safe to remove the delay itself,and this patch does this. On my test laptop, this reduces the boot timeby 2 seconds (kernel time goes from 3.9 to 1.9 seconds).Signed-off-by: Arjan van de Ven <arjan@linux.intel.com>------ a/init/do_mounts.c 2009-01-07 18:42:10.000000000 -0800+++ b/init/do_mounts.c 2009-01-07 18:43:02.000000000 -0800@@ -370,14 +370,17 @@ void __init prepare_namespace(void) ssleep(root_delay); } +#if 0 /* * wait for the known devices to complete their probing * * Note: this is a potential source of long boot delays. * For example, it is not atypical to wait 5 seconds here * for the touchpad of a laptop to initialize. */ wait_for_device_probe();+#endif+ async_synchronize_full(); md_run_setup(); Subject: [PATCH] fastboot: retry mounting the root fs if we can't find initcurrently we wait until all device init is done before trying to mountthe root fs, and to consequently execute init.In preparation for relaxing the first delay, this patch adds a retryattempt in case /sbin/init is not found. Before retrying, the codewill wait for all device init to complete.While this patch by itself doesn't gain boot time yet (it needs follow onpatches), the alternative already is to panic()...Signed-off-by: Arjan van de Ven <arjan@linux.intel.com>------ a/init/main.c 2009-01-07 18:29:11.000000000 -0800+++ b/init/main.c 2009-01-07 18:32:08.000000000 -0800@@ -837,6 +837,7 @@ static void run_init_process(char *init_ */ static noinline int init_post(void) {+ int retry_count = 1; /* need to finish all async __init code before freeing the memory */ async_synchronize_full(); free_initmem();@@ -859,6 +860,8 @@ static noinline int init_post(void) ramdisk_execute_command); } +retry:+ /* * We try each of these until one succeeds. *@@ -871,6 +874,23 @@ static noinline int init_post(void) "defaults...\n", execute_command); } run_init_process("/sbin/init");++ if (retry_count > 0) {+ retry_count--;+ /* + * We haven't found init yet... potentially because the device+ * is still being probed. We need to+ * - flush keventd and friends+ * - wait for the known devices to complete their probing+ * - try to mount the root fs again+ */+ flush_scheduled_work();+ while (driver_probe_done() != 0)+ msleep(100);+ prepare_namespace();+ goto retry;+ }+ run_init_process("/etc/init"); run_init_process("/bin/init"); run_init_process("/bin/sh"); | http://lkml.org/lkml/2009/3/29/180 | CC-MAIN-2017-22 | refinedweb | 628 | 65.22 |
Summary editslebetman: This implements what I'd call C-like syntax for numbers in Tcl. Basically, this means that not only can you use infix assignment like x = $y * 2 but you also need to declare the variables before using them. There are other implementations of this available somewhere in this wiki, mostly by Richard Suchenwirth. Prompted by GWM, I thought I'd dig up my very simple implementation which have been floating around usenet (google "syntax expressiveness"). Anyway, here's the code:
proc cleanupVar {name1 name2 op} { if {![uplevel 1 [list info exists $name1]]} { rename $name1 {} } } proc var {name {= =} args} { upvar 1 $name x if {[llength $args]} { set x [expr $args] } else { set x {} } proc $name args [subst -nocommands { upvar 1 $name $name if {[llength \$args]} { set $name [expr [lrange \$args 1 end]] } else { return $$name } }] uplevel 1 [list trace add variable $name unset cleanupVar] }The following is an example of how to use var:
proc test {} { var x var y = 10 x = $y*2 return $x } puts [test]Another feature is that the variables actually exists in local scope even though their associated commands exists in global scope. This means that the variables can be used recursively:
proc recursiveTest {x} { var y = $x - 1 if {$y > 0} { recursiveTest $y } puts $y } recursiveTest 10should output the numbers 0 to 9. Another test:
proc test2 {} { var x = 10 puts "this x belongs to test2 = $x" } proc test3 {} { var x = 100 test2 x = $x + 1 puts "this x belongs to test3 = $x" } test3output:
this x belongs to test2 = 10 this x belongs to test3 = 101Larry Smith: All of this would be so much tidier if it were possible to declare local procs.escargo 2007-02-04 - Might it make more sense for the default value of a declare var to be 0 (or, since these are supposed to be reals, 0.0)?slebetman: I prefer a default value that is not a number. If you want to initialise it to 0 then declare it as:
var x = 0Besides, these aren't supposed to be reals. They're regular Tcl variables with expr built-in. It's important to remember that because:
var x = 1 / 2is not 0.5 but 0.NEM: A few comments. Firstly, the advice to always brace your expr-essions applies here too:
% var x = "foo" eq "bar" invalid bareword "foo" in expression "foo eq bar"; should be "$foo" or "{foo}" or "foo(...)" or ...The other performance and precision benefits also apply, so you should really write:
var x = {"foo" eq "bar"}However, this doesn't actually work as "args" applies more quoting, resulting in x being assigned the literal string {"foo" eq "bar"}. It will also go wrong with any variable references. We can fix this with an [uplevel], and we can also simplify the var proc considerably using interp aliases and setting the trace through the upvar alias:
proc var {name {= =} args} { upvar 1 $name x if {[llength $args]} { set x [uplevel 1 [linsert $args 0 expr]] } interp alias {} $name {} ::var $name trace add variable x unset cleanupVar return $x }slebetman: notes that performance and precision benefits can also be achieved by using it like:
x = \$x + \$ybut may be considered by some (myself included) as ugly.Lars H: It's probably unnecessary to recreate the alias every time the variable is set, but indeed this is the kind of command that should be an alias. I think both variants are buggy with respect to recursion however, as it wants to remove the command every time a variable by that name is unset. Try changing test3 to
proc test3 {} { var x = 100 uplevel {test2} x = $x + 1 puts "this x belongs to test3 = $x" }to see the problem:
this x belongs to test2 = 10 Error: invalid command name "x"Checking for another variable by the same name in the current context simply isn't good enough. Another implementation of var which adresses this bug (by only attaching an unset trace to the variable for which the command had to be created) is
proc var_set {name {= =} args} { uplevel 1 [list ::set $name [uplevel 1 [linsert $args 0 ::expr]]] } proc var {name {= =} args} { upvar 1 $name x if {[llength $args]} { set x [uplevel 1 [linsert $args 0 ::expr]] } set cmd [uplevel 1 {::namespace current}]::$name if {![llength [interp alias {} $cmd]]} then { interp alias {} $cmd {} ::var_set $name trace add variable x unset "[list ::interp alias {} $cmd {}];#" } return $x }It is possible to break it by [uplevel]ing an [unset] for the outer variable, but as long as unsetting happens because procedures return it should be OK.slebetman: Note that unsetting the "local" should be OK. Just don't unset the variable of the same name at uplevel 1. | http://wiki.tcl.tk/17648 | CC-MAIN-2017-17 | refinedweb | 789 | 58.66 |
Content-type: text/html
abort - Generates a software signal to end the current process
Standard C Library (libc.so, libc.a)
#include <stdlib.h>
void abort ( void );
Interfaces documented on this reference page conform to industry standards as follows:
abort(): ISO C, POSIX.1, XPG4, XPG4-UNIX
Refer to the standards(5) reference page for more information about industry standards and associated tags.
The abort() function sends a SIGABRT signal to the current process. This signal terminates the process unless both of the following conditions are true: (1) signal SIGABRT is being caught, and (2) the signal handler does not do a normal return, for example, if it does a longjmp.
If abort() causes the process to terminate abnormally and the current directory is writable, the system creates a core file in the current working directory.
If the call to the abort() function terminates the process, each open stream and message catalog descriptor is affected as if the fclose() function was called. The abort() function then terminates the process with the same result as the _exit() function, with the exception of the status value made available to the wait() or waitpid() function. These functions receive the status value of the process terminated by the SIGABRT signal. The abort() function overrides blocking or ignoring of the SIGABRT signal.
The abort() function is supported for multi-threaded applications.
Functions: exit(2), kill(2), sigaction(2)
Standards: standards(5) delim off | http://backdrift.org/man/tru64/man3/abort.3.html | CC-MAIN-2017-09 | refinedweb | 238 | 53.92 |
b64.xsl:
b64.ffd.xsl:
b64.xq:
b64.jsoniq:
b64.js:
Hermann <myBlog/> <myTweets/> | <GraphvizFiddle/> | <xqib/> | <myCE/> <myFrameless/> |/>/>
A month ago blog posting coproc2gatewayscript provided a preview on new GatewayScript (Javascript on DataPower) available with version 7.0.0.0 of DataPower firmware later this month.
I never worked with modules and seeing a question on how to do AES encoding/decoding in GatewayScript I thought this is a great sample for learning about modules and easily make use of libraries found on the internet.
With the first release (7.0.0.0) GatewayScript will be available there will be no crypto library support.
(This is similar to XQuery/JSONiq new with version 6.0.0.0 having no access to dp:variables and HTTP header, that came with 6.0.1.0 firmware)
A word of caution here:
It is always better to use Encrypt/Decrypt/Sig/Verify actions instead of DataPower crypto extension functions in XSLT.
Reason is that the actions are hardened against Oracle Padding attacks -- using crypto extension functions YOU are responsible.
Anyway, since 7.0.0.0 GatewayScript does not ship any crypto funcitons, using self written or found libraries is your only current option.
I googled and found this nice, self-contained and interactive AES JavaScript demo:
Doing "View Page Source" I saw that these 4 code parts were included into the page:
utf8.js / base64.js / aes.js / aes-ctr.js
You get them unmodified if you do "Save Page as" as "complete webpage".
{"EDIT":"11-10_2014 - files on website did change, two are missing now. Attaching June 2 version of the files here for the purpose of easily trying out aes-demo with GatewayScript. Your further (real) work should based on latest version JavaScript from above website."}
So I decided to make 4 modules out of them, store under "local:" on DataPower and just require("aes-ctr") in order to use it. To make functionality available from the module the last line "module.exports = ...;" had to be appended to each file. And in order to use functionality eg. from module "utf8" var Utf8 = require("utf8"); had to be added at the top of the modules.
Only one more change had to be done in addition to make everything work on GatewayScript, these are all diffs:
Here you can see demonstration GatewayScript aes.demo.js in action:
$ coproc2 aes.demo.js ../ab.json
Password: L0ck it up saf3
Plaintext: pssst ... đon’t tell anyøne!
Encrypted ...: GQK5heUZjVNxqjSRRj0HzMJwPrW+OMWOaL5RXzzvfklqdViJraQ8tQ==
...
$
$ coproc2 aes.demo.js ../ab.json
Password: L0ck it up saf3
Plaintext: pssst ... đon’t tell anyøne!
Encrypted ...: RQFLXOcZjVNuGspYI20khzUJKbmeb6WOFBSL/cQPfX+1pnr+pmQP+Q==
...
$
The output for the three test vectors from Appendix C of NIST AES spec should be
Now we have seen that aes.demo.js works fine, here is it completely:
The little helper function "_()" at the bottom of aes.demo.js was only intended to be a nice oneline implementation of "byte array to hex string" conversion. To my total surprise it seems to outperform other implementations by orders(!) of magnitude!?!?!
I verified that on jsperf.com, try it out yourself (I hope the test result is "real"):
(at least it produces the needed hexadecimal output for the NIST test vectors above)
<EDIT>
Vyacheslav Egorov pointed out that the measurements were flawed:
</EDIT>
$
$ od -tcx1 te0t
0000000 t e \0 t
74 65 00 74
0000004
$
$ java coproc2 boot.xsl te0t
dGUAdA==
$
$ java coproc2 boot.xsl te0t | base64 -d | od -tcx1
0000000 t e \0 t
74 65 00 74
0000004
$
:
$ java coproc2 xpath++.xsl store-identity.xsl "*/namespace::*"-------------------------------------------------------------------------------xmlns:dpconfig=""-------------------------------------------------------------------------------xmlns:dp=""-------------------------------------------------------------------------------xmlns:xsl=""-------------------------------------------------------------------------------xmlns:xml=""$
$ coproc2 ampify.xsl 412.xml | coproc2 body2Extract.xsl - | https://www.ibm.com/developerworks/mydeveloperworks/blogs/HermannSW/tags/coproc2?lang=ko | CC-MAIN-2015-22 | refinedweb | 613 | 56.76 |
...
CodingForums.com
>
:: Client side development
>
JavaScript programming
> How to pass the event object when dynamically attaching an event handler in NS6
PDA
How to pass the event object when dynamically attaching an event handler in NS6
WA
08-03-2002, 02:10 AM
Hi;
I have a question regarding passing the event object in NS6 hopefully someone can clarify. I have a function that has a few parameters, one of which is the event object. I wish to dynamically assign this function to an event handler, which itself is attached to a HTML element using script. My question is, how do I pass the event object into this function in this case? The below should work, but it doesn't:
Below code doesn't work in NS6
<form name="test">
<input type="text" name="test2">
</form>
<script>
function dothis(width,height,e){
alert(e)
}
document.test.test2.onkeypress=function(e){ dothis(5, 10, event); }
</script>
The above returns an "event" not defined error. I have no problem getting things to work if I simply defined the event handler using HTML. For example, the below works:
<input type="text" name="test2" onkeypress="dothis(5,10,event)">
Why is that?
Spookster
08-03-2002, 03:12 AM
function(e){
A function with no name? :confused:
joh6nn
08-03-2002, 04:04 AM
anonymous functions are valid as of JavaScript 1.2. i use them all the time for event handlers. but generally not with the event object.
George, the new event handling system still doesn't make sense to me, but from what i get out of the Guide you may have to do that this way:
document.test.test2.onkeypress = function(e) { dothis(5, 10, e); }
might also try it this way:
document.test.test2.onkeypress=function() { dothis(5, 10, event); }
jkd
08-03-2002, 04:07 AM
George, read the tutorial I submitted to your very own site. :p
An object named "event" is passed as an argument to whatever function you assign the event to:
Say when mousedown is fire on node "myNode", it does this:
myNode.mousedown(event);
(Essentially, though not really...)
Which means:
myNode.onmousedown = function(anynameyouwantfortheeventobject) {
alert(thesamenameasbefore)
}
Or you can forget about naming it, and just call arguments[0].
WA
08-03-2002, 04:46 AM
Thanks guys for the responses.I eventually got to where John is, which works in NS6:
document.test.test2.onkeypress = function(e) { dothis(5, 10, e); }
What still throws me off is why when you attach event handlers using HTML, you need to pass in "event", and not a name holder like e or "ewhateveryouwant", but in the above case, "e' instead in NS6. Specifically, I'm talking about "e" as it occurs here:
dothis(5, 10, e);
I guess my question really boils down to how parameters in anonymous functions operate.
In IE4+, all this is much simplier, as there's simply "event" to deal with.
jkd
08-03-2002, 06:22 AM
Every time an event fires, the event object is a unique object. It makes more sense to me to pass this as an argument to the event listener every time, rather than pollute the global namespace with variables which really are better implemented elsewhere.
BTW, this lets you create your own event objects and dispath them programatically without fear of altering the global event object via document.createEvent() and the various initEventType() methods.
EZ Archive Ads Plugin for
vBulletin
Computer Help Forum
vBulletin® v3.8.2, Copyright ©2000-2013, Jelsoft Enterprises Ltd. | http://www.codingforums.com/archive/index.php/t-3238.html | CC-MAIN-2013-20 | refinedweb | 587 | 62.48 |
Updated 31 May, 2019
*Originally published at blog.mphomphego.co.za on May 26, 2019.
We use and love Slack for team messaging, throughout the day. I needed to integrate slack with some of my IoT devices in the office and at home primarily because of its simplistic API as compared to WhatsApp and Telegram (that I never use).
The reason is pretty straight forward, I wanted my devices to SlackMe messages. For example, I have soil moisture sensor(s) planted in my flowers pot at the office as well as in my vegetable garden at home, and I wanted my plants to SlackMe should they need me to water them.
Note, this is an ongoing side project if you have interest on it go here, I will make a detailed blog post soon.
My solution was to have a simple Python script that sends me a message in the appropriate Slack channel at specific/random times or when
xValue goes beyond a certain
threshold.
Slack provides
Incoming-Webhooks and they have a well documented Incoming-Webhooks guide. However, the guide only tells you what they expect you to do, but it doesn’t really explain what you actually need to do.
The first thing I needed to do was to find out from Slack the correct URL it will use to post the messages.
- Go to and sign in then follow the instructions here
- Choose the channel to which you want to send messages and then Add Incoming WebHooks Integration.
- Note that you can find the
Display Nameand change what will appear in the channel. Slack gives you the URL to which you’ll be posting your messages. Similar to this:
Posting to a Slack channel
From the URL Slack gave you, extract the
app_id,
secret_id and
token which are denoted as
/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX on the URL Slack gave you. Below is the simplified Python code snippet
import requests class SlackBot: def __init__(self, app_id, secret_id, token): """ Get an "incoming-webhook" URL from your slack account. @see eg:<app_id>/<secret_id>/<token> """ self._url = "" % ( app_id, secret_id, token, ) def slack_it(self, msg): """ Send a message to a predefined slack channel.""" headers = {"content-type": "application/json"} data = '{"text":"%s"}' % msg resp = requests.post(self._url, data=data, headers=headers) return "Message Sent" if resp.status_code == 200 else "Failed to send message" slack = SlackBot(app_id, secret_id, token) slack.slack_it("Hello")
Wrapping Up
Now you've got a simplified Slack message bot which can be expanded and used in various ways.
If you would like to dig even further, there's a 'bloated' Python package called
slackclient which is a developer kit for interfacing with the Slack Web API and Real Time Messaging (RTM) API on Python 3.6 and above.
Top comments (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/mmphego/send-slack-messages-with-python-17pc | CC-MAIN-2022-40 | refinedweb | 461 | 62.58 |
Jdh
A Json implementation for Haskell, with JavaScript Values and Encoding/Decoding
This package is not currently in any snapshots. If you're interested in using it, we recommend adding it to Stackage Nightly. Doing so will make builds more reliable, and allow stackage.org to host generated Haddocks.
JSON-for-Haskell
A JSON implementation for haskell
module Main( main ) where import Data.Jdh.Json main :: IO () main = do print $ fromArray [fromInt 3, fromInt 5, fromStr "Haha"] putStrLn $ encode True $ fromProps ["field1" =: fromInt 5, "field2" =: fromReal 3.5] putStrLn $ encode False $ fromProps ["condensed JSON data" =: fromBool True] print $ decode "{\"hello\": [\"world\"], \"nested\": {\"nested\": true}}" return () | https://www.stackage.org/package/Jdh | CC-MAIN-2017-43 | refinedweb | 105 | 57.37 |
Automate social media posts via Ayrshare's API for your company or users. Post to Instagram, Twitter, Facebook, YouTube, LinkedIn, Google My Business, Pinterest, Telegram, and Reddit.
Project description
Social Media Posting and Scheduling APIs
Social Post API is a wrapper SDK for Ayrshare's APIs.
Ayrshare is a powerful set of APIs that enable you to send social media posts, get analytics, and add comments to Twitter, Instagram, Facebook, LinkedIn, YouTube, Google My Business, Pinterest, Reddit, and Telegram on behalf of your users.
The Ayrshare API handles all the setup and maintenance for the social media networks. One API to rule them all (yeah, went there). See the full list of full list of features.
Get started with a free plan, or if you have a platform or manage multiple users check out the Business Plan.
For more information on setup, see our installation video or our Quick Start Guide.
Installation
pip install social-post-api
Setup
1. Create a free Ayrshare account.
2. Enable your social media accounts such as Twitter, Facebook, LinkedIn, Reddit, Instagram, or Telegram in the Ayrshare dashboard.
3. Copy your API Key from the Ayrshare dashboard. Used for authentication.
Getting Started
Initialize Social Post API
Create a new Social Post object with your API Key.
from ayrshare import SocialPost social = SocialPost('8jKj782Aw8910dCN') # get an API Key at ayrshare.com
History, Post, Delete Example
This simple example shows how to post, get history, and delete the post. This example assumes you have a free API key from Ayrshare and have enabled Twitter, Facebook, and LinkedIn. Note, Instagram, Telegram and Reddit also available.
from ayrshare import SocialPost social = SocialPost('8jKj782Aw8910dCN') # get an API Key at ayrshare.com # Post to Platforms Twitter, Facebook, and LinkedIn postResult = social.post({'post': 'Nice Posting 2', 'platforms': ['twitter', 'facebook', 'linkedin']}) print(postResult) # Delete deleteResult = social.delete({'id': postResult['id']}) print(deleteResult) # History print(social.history())
API
Published a new post to the specified social networks either immediately or at scheduled future date. Returns a promise that resolves to an object containing the post ID and post status (success, error).
postResponse = social.post({ # Required 'post': 'Best post ever!', # Required: Social media platforms to post. # Accepts an array of strings with values: "facebook", "twitter", "linkedin", "pinterest", "reddit", or "telegram". 'platforms': ['twitter', 'facebook', 'linkedin', 'pinterest', 'telegram', 'reddit'], # Optional: URLs of images to include in the post or for Instagram 'media_urls': [''], # Optional: Datetime to schedule a future post. # Accepts an ISO-8601 UTC date time in format "YYYY-MM-DDThh:mm:ssZ". Example: 2021-07-08T12:30:00Z 'scheduleDate': '2020-08-07T15:17:00Z', # Required if platform includes "reddit." Title of Reddit post. 'title': 'My Reddit Post', # Required if platform includes "reddit." Subreddit to post. 'subreddit': 'test', # Optional: Shorten links in the post for all platforms similar to bit.ly. # Only URLS starting with http or https will be shortened. Default value: true. 'shorten_links': true })
Delete a post with a given post ID, obtained from the "post" response. Returns a promise with the delete status. Also, can bulk delete multiple IDs at once using the "bulk" key.
deleteResponse = social.delete({ # Required 'id': 'POST ID', # optional, but required if "bulk" not present 'bulk': ['Post ID 1', 'Post ID 2', ...] # optional, but required if "id" not present })
History
Get a history of all posts and their current status in descending order. Returns a promise that resolves to an array of post objects.
historyResponse = social.history({ 'lastRecords': 10, # optional: returns the last X number of history records 'lastDays': 30, # optional: returns the last X number of days of history records. Defaults to 30 if not present. })
Upload Media
Upload and store a new image. Returns a URL referencing the image. Can be used in "image_url" in "post".
uploadResponse = social.upload({ # Required: The image as a Base64 encoded string. Example encoding: 'file': ', # Optional 'fileName': 'test.png', # Optional 'description': 'best image' })
Get Media
Get all media URLS. Returns a promise that resolves to an array of URL objects.
mediaResponse = social.media()
User
Get data about the logged in user, such as post quota, used quota, active social networks, and created date.
user = social.user()
Shorten URL
Shorten a URL and return the shortened URL.
shortenResponse = social.shorten({ # Required: URL to shorten 'url': '', })
Analytics
Get analytics on shortened links, share, likes, and impressions.
analytics = social.analyticsLinks({ # Optional range 1-7, default 1 day. 'lastDays': 3 })
analytics = social.analyticsPost({ 'id': 'Post ID', 'platforms': ['twitter', 'linkedin'] })
Add an RSS or Substack Feed
Add a new RSS or Substack feed to auto post all new articles. Returns a promise that resolved to an object containing the feed ID. See How to Automate Your Blog or Newsletter for more info.
feedResponse = social.feedAdd({ # Required: URL to shorten 'url': '', # Optional: Value: "rss" or "substack". # If not set, defaults to "rss" 'type': 'RSS', })
Delete an RSS or Substack Feed
Delete an RSS feed for a given ID.
feedResponse = social.feedDelete({ # Required: ID of the feed 'id': 'Feed ID', })
Get Commnets
Get Comments for a Post
getCommentsResponse = social.getComments({ # Required: ID of the Post 'id': 'Post Id', })
Add a comment to a Post
postCommentResponse = social.postComment({ # Required: ID of the Post 'id': 'Post Id', 'platforms': ['facebook', 'instagram'], 'comment': 'The best comment ever!', })
Business Plan Functions for Multiple Clients - Business Plan Required
See here for more information
Create Profile
Create a new account profile under the primary account
createProfileResponse = social.createProfile({ # Required: title 'title': 'New Profile Title', })
Delete Profile
Delete a profile owned by the primary account
deleteProfileResponse = social.deleteProfile({ # Required: profileKey - the API Key of the profile to delete 'profileKey': 'JI9s-kJII-9283-OMKM', })
Generate JWT URL for SSO
Generate an SSO link. Please see integration guide provided with the Business Plan.
generateJWTResponse = social.generateJWT({ 'domain': 'mydomin', 'privateKey': 'private key data...', 'profileKey': 'JI9s-kJII-9283-OMKM', })
Additional Calls
- registerWebhook
- unregisterWebhook
- listWebhook
- setAutoSchedule
- deleteAutoSchedule
- listAutoSchedule
Information and Support
Additional examples, responses, etc. can be found at:
RESTful API Endpoint Docs
Please contact us with your questions, or just to give us shout-out 📢!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/social-post-api/ | CC-MAIN-2022-05 | refinedweb | 1,023 | 58.18 |
SELRECORD(9) MidnightBSD Kernel Developer’s Manual SELRECORD(9)
NAME
selrecord, selwakeup — record and wakeup select requests
SYNOPSIS
#include <sys/param.h>
#include <sys/selinfo.h>
void
selrecord(struct thread *td, struct selinfo *sip);
void
selwakeup(struct selinfo *sip);
DESCRIPTION
selrecord() and selwakeup() are the two central functions used by select(2), poll(2) and the objects that are being selected on. They handle the task of recording which threads are waiting on which objects and the waking of the proper threads when an event of interest occurs on an object.
selrecord() records that the calling thread is interested in events related to a given object. If another thread is already waiting on the object a collision will be flagged in sip which will be later dealt with by selwakeup().
selrecord() acquires and releases sellock.
selwakeup() is called by the underlying object handling code in order to notify any waiting threads that an event of interest has occurred. If a collision has occurred, selwakeup() will increment nselcoll, and broadcast on the global cv in order to wake all waiting threads so that they can handle it. If the thread waiting on the object is not currently sleeping or the wait channel is not selwait, selwakeup() will clear the TDF_SELECT flag which should be noted by select(2) and poll(2) when they wake up.
The contents of *sip must be zeroed, such as by softc initialization, before any call to selrecord() or selwakeup(), otherwise a panic may occur. selwakeup() acquires and releases sellock and may acquire and release sched_lock.
SEE ALSO
poll(2), select(2)
AUTHORS
This manual page was written by Chad David 〈davidc@FreeBSD.org〉 and Alfred Perlstein 〈alfred@FreeBSD.org〉.
MidnightBSD 0.3 June 13, 2007 MidnightBSD 0.3 | http://www.midnightbsd.org/documentation/man/selrecord.9.html | CC-MAIN-2015-22 | refinedweb | 292 | 53.1 |
Linked by Thom Holwerda on Fri 29th Oct 2010 20:48 UTC
Thread beginning with comment 447728
To view parent comment, click here.
To read all comments associated with this story, please click here.
To view parent comment, click here.
To read all comments associated with this story, please click here.
RE[4]: Good news for HTML5 ...
by vivainio on Sat 30th Oct 2010 08:38 in reply to "RE[3]: Good news for HTML5 ...".
RE[5]: Good news for HTML5 ...
by ephracis on Sat 30th Oct 2010 14:36 in reply to "RE[4]: Good news for HTML5 ..."
Member since:
2007-09-23
It's pretty easy. Most of my design I do in XAML which is very efficient. But sometimes I need to handle the controls in code which works just as you would expect if you are used to WinForms. You can actually access WinForms from within WPF application _exactly_ as you do in your normal WinForms app. Just be careful what namespaces you include so you don't confuse your compiler.
One thing I love is the ease of modifying controls. You can put a style on it, or completely remake a control just by using templates. This is how I made those playback buttons which were supposed to look somewhat like the buttons in Windows Explorer (in fact I have tried to mimic Explorer pretty much). However, when it's easy to style your app, some people/corporations will abuse that ability and create computer-vomit, but that's life.
I used Glade before when doing GTK+ apps, which I enjoyed, so WPF with XAML felt natural for me.
However, I love the Qt toolkit and how easy and powerful it is. When I port my app to Linux I hope to be able to do a Qt and a GTK+ version (because integration is extremely important IMO), so I hope that WPF can give me that separation that I need as well.
Oops! This seems to have gotten out of hand. I should've stayed on topic... *flees*
Edited 2010-10-30 04:39 UTC | http://www.osnews.com/thread?447728 | CC-MAIN-2015-18 | refinedweb | 351 | 73.78 |
In the previous article the first article: which owns it. You’ll see this below.
- An itemRenderer can use anything in the data record. You might, for example, have an item in a record that’s not for direct display but which influences how an itemRenderer behaves.
Dynamically Changing the itemRenderer
Here is the MXML itemRenderer from the previous article used for a TileList. We) which lets the user give a range of prices; all items which fall outside of the range should fade out (the itemRenderers’ alpha value should change). You need to tell each itemRenderer:
- Part of the list itself. That is, your list (List, DataGrid, TileList, etc) could be a class that extends a list control and which has this criteria as a public member.
- Part of the application as global data..
listData, it is the MyTileList – my extension of TileList – which is the owner. Casting the owner field to MyTileList allows the criteria to be fetched.
IDropInListItemRenderer
Access to listData is available when the itemRenderer class implements the IDropInListItemRenderer interface. Unfortunately, UI container components do not implement the interface which gives access to the listData. Control component such as Button and Label do, but for containers you have to implement the interface yourself.
Implementing this interface is straightforward and found in the Flex documentation. Here’s what you have to do for our BookItemRenderer class:
- Have the class implement the interface.
<mx:HBox xmlns:
- Add the set and get functions.
invalidateList():
- The itemRenderer looks into its list owner for the criteria to use to help it determine how to render the data.
- The list owner class,).
Events visual – the TileList. The bubbling approach doesn’t assoicate the event (bookBuy) with the list control (Tile.
First, you have to add metadata to the CatalogList control to let the compiler know the control dispatches the event:
import events.BuyBookEvent; import mx.controls.TileList; [Event(name="buyBook",type="events.BuyBookEvent")] public class CatalogList extends TileList {
Second, add a function to CatalogList to dispatch the event. This function will be called by the itemRenderer instances:
public function dispatchBuyEvent( item:Object ) : void { var event:BuyBookEvent = new BuyBookEvent(); event.bookData = item; dispatchEvent( event ); } }
Third, change the Buy button code in the itemRenderer to invoke the function:
fo.
Summary. | http://blogs.adobe.com/peterent/author/pent/page/3/ | CC-MAIN-2013-48 | refinedweb | 376 | 57.47 |
When i run the command rpmbuild -bb mypackage.spec, on centos, i get an
error
error: Package already exists: %package debuginfo
following is part of the spec file:
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}BuildRequires: gcc = 4.1.2BuildRequires: make >= 3.81BuildRequires: postgresql84-devel = 8.4.9%descrip
company xyz created a package
com.xyz.utils.
There are two classes declared in two separate files.
They have some variables as package private. so that a variable X in class
A can be used in class B of the same package.
package
com.xyz.utils;public class A{int a=10;}package
com.xyz.utils;public class B{int b
Im trying to build a deployment package out of VS2010 against a web
project and want to include all IIS settings as configured in IIS Manager.
However when i enable this i get the following error message
Object of type 'manifest' and path
'K:SandboxWeb.Crm.FrameworkobjDebugPackageWeb.Crm.Framework.SourceManifest.xml'
cannot be created.One or more entries in the manifest 's
I would like to play .flv or mp4 videos in servlet . this servelt will
be called from webView of android. i would like to play the video just like
you tube does. Please provide the code example so that i can test.
This is with Flexbuilder 3.2, Eclipse 3.3.2.
I am moving my
development environment to a new machine. Actionscript classes that
compiled in the old environment now get a compile error:
A
file found in a source-path must have an externally visible definition. If
a definition in the file is meant to be externally visible, please put the
definition in a package.
I am using Spring 3.In my application context xml file I would
like to use component-scan and start in my root package com.mysite and not
explicitly add every package:
would like to do
<context:component-scan
not:
<context:component-scan<context:
I have a wxPython application with the various GUI classes in their own
modules in a package called gui. With this setup, importing
the main window would be done as follows:
gui
from
gui.mainwindow import MainWindow
This looked messy to
me so I changed the __init__.py file for the
gui package to import the class
__init__.py
I have a version of a package installed in my project but during testing
I have found a problem with it. I tried the obvious thing
Update-Package -Id Foo.Bar -Version 1.0.0 -Force but the
Update-Package cmdlet doesn't have a -Force parameter, and it doesn't allow
updates to an earlier version. How do I downgrade my package dependencies
(without taking advantage of source control!)<
Update-Package -Id Foo.Bar -Version 1.0.0 -Force
I have a set of python scripts organized like so:
PythonScripts/ TypeAScripts/
TypeASet1Scripts/ example.py
TypeASet2Scripts/ TypeBScripts/ TypeBSet1Scripts/ TypeBSet2Scripts/ TypeCScripts/
TypeCSet1Scripts/ TypeCSet2Scripts/
CommonFunctions/
Python
Intra
Package
Imports
common
functions
Having real problems updating any apps on Google Play Developer
Console.
This is what I have done 2 or 3 times.. | http://bighow.org/tags/Package/1 | CC-MAIN-2017-39 | refinedweb | 510 | 59.4 |
Any value assigned to an automatic variable within a function is lost once the control returns from the called function to the calling function. However, there may be a situation where the value of the local variable needs to be preserved even after the execution of the function gets over. This need can be fulfilled by declaring the variable as static. A static variable is commonly used when it is necessary for a function to remember a value between its calls. To understand the concept of static variables, consider this example.
Example : A program to demonstrate the use of static variables within a function
#include<iostream>
using namespace std;
void count ()
{
static int c=0;
c++;
cout<<”Function is called "<<c<<" times\n";
} ;
int main ()
{
for (int i=1;i<=5;i++)
count() ;
return 0;
}
The output of the program is
Function is called 1 times
Function is called 2 times
Function is called 3 times
Function is called 4 times
Function is called 5 times
In this example, c is a static variable declared in function count ().This variable is incremented by one each time the function is called. Note that the static variable is initialized to 0 only once when the function is called for the first time. In subsequent calls, the function retains its incremented value from the last call (see | https://ecomputernotes.com/cpp/functions/static-variables-within-functions | CC-MAIN-2020-29 | refinedweb | 224 | 55.58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.